import React, { useEffect, useState } from 'react';
import {
  Table,
  Input,
  Button,
  Row,
  Col,
  Space,
  DatePicker,
  Radio,
  Drawer,
  Form,
  Modal,
  Image,
  Upload,
  Spin,
} from 'antd';
const { RangePicker } = DatePicker;
import PaginationCom from '@/common/Pagination';
import { getList, addVersion, editVersion, infoVersion, delVersion } from './request';
const { TextArea } = Input;
import dayjs from 'dayjs';
import Add from '@/assets/images/icon/add.png';
import reload from '@/assets/images/icon/reload.png';
import reset from '@/assets/images/icon/reset.png';
import filter from '@/assets/images/icon/filter.png';
import TableCom from '@/common/TableCom/index';
import { useSelector } from 'react-redux';
import AliOSS from 'ali-oss';
import { getAliOSSSTSToken } from '@/pages/setting/help/addedit/requet';
const AppVersion = () => {
  const [data, setData] = useState([]);
  const [page_size, setpage_size] = useState(10);
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(4);
  const [loading, setLoading] = useState(true);
  const [isEdit, setIsEdit] = useState(false);
  const [delMoadal, setDelModal] = useState(false);
  const [isadd, setisadd] = useState(true);
  const [dateVal, setDateVal] = useState('');
  const [form] = Form.useForm();
  // 获取操作权限
  const { operationPermissionsList } = useSelector((state) => state.user);
  const [initialValues, setinitialValues] = useState({
    version: '',
    url: '',
    remarks: '',
  });
  const [id, setid] = useState(0);
  const [delid, setdelid] = useState(0);
  const [filterObj, setfilterObj] = useState({
    version: '',
    start_time: '',
    end_time: '',
  });

  const [ossClient, setOssClient] = useState(null); // oss 操作
  const [STSToken, setSTSToken] = useState(null); // oss 过期设置
  const [file, setFile] = useState({});
  const [img, setImg] = useState('');
  const [uploading, setUploading] = useState(false);

  let ossClientTemp;

  const getStsAuthToken = () => {
    return new Promise(async (resolve) => {
      const data = await getAliOSSSTSToken();
      if (data) {
        window.sessionStorage.setItem('sts', JSON.stringify(data));
        setSTSToken(data);
        ossClientTemp = await new AliOSS({
          accessKeyId: data.AccessKeyId,
          accessKeySecret: data.AccessKeySecret,
          stsToken: data.SecurityToken,
          endpoint: data.endpoint,
          bucket: 'zxts-common-file',

          timeout: 180000,
          refreshSTSToken: async () => {
            const info = await getAliOSSSTSToken();
            return {
              AccessKeyId: info.AccessKeyId,
              AccessKeySecret: info.AccessKeySecret,
              SecurityToken: info.SecurityToken,
            };
          },
          refreshSTSTokenInterval: 14 * 60 * 1000,
        });
        setOssClient(ossClientTemp);
        console.log('AliOSS', ossClientTemp);
      }
      resolve();
    });
  };
  useEffect(() => {
    getStsAuthToken();
  }, []);

  const props = {
    name: 'file',
    accept: '.apk',
    showUploadList: false,
    beforeUpload: async (file) => {
      const suffixArr = ['apk'];
      const suffix = file.name.substring(file.name.lastIndexOf('.') + 1);
      if (!suffixArr.includes(suffix)) {
        message.error(`只能上传以.apk格式的包，当前文件格式错误`);
        return false;
      }
      setFile(file);
    },
    customRequest: async () => {
      if (!ossClient) {
        message.error('ossClient还未初始化', ossClient);
        return false;
      }

      try {
        setUploading(true);
        const fileExt = file.name.substring(file.name.lastIndexOf('.'));
        const fileName = `app-${dayjs().valueOf()}-${Math.random().toString(36).substring(2)}${fileExt}`;
        const filePath = `${dayjs().format('YYYY/MM/DD')}/${fileName}`;

        const result = await ossClient.put(filePath, file);
        console.log('result', result);
        // 假设 result 中包含了文件的 URL
        const imageUrl = result.url;

        // 更新图片 URL 状态
        setImg(imageUrl);
        form.setFieldsValue({ url: imageUrl });
        setUploading(false);
        // 上传成功，返回 true 表示可以继续上传
        return true;
      } catch (error) {
        // 上传失败，处理错误
        console.error('上传文件失败：', error);
        message.error('上传文件失败，请重试');
        return false;
      }
    },
  };

  const handleReset = () => {
    setfilterObj({ version: '' });
    setDateVal('');
    init();
  };
  const handleEdit = async (id) => {
    const data = await infoVersion({ id });
    setisadd(false);
    setIsEdit(true);
    setImg(data.url);
    setid(data.id);
    form.setFieldsValue(data);
  };
  const onClose = () => {
    setImg('');
    setIsEdit(false);
  };
  const submitForm = async (obj) => {
    console.log('点击了编辑的提交');
    let bool;
    if (isadd) {
      bool = await addVersion({
        url: img,
        version: obj.version,
        remarks: obj.remarks,
        is_compel: obj.is_compel,

        // ...obj,
      });
    } else {
      bool = await editVersion({
        // ...obj,
        url: img,
        version: obj.version,
        remarks: obj.remarks,
        is_compel: obj.is_compel,
        id,
      });
    }
    if (!bool) return;
    init(filterObj);
    setIsEdit(false);
  };
  useEffect(() => {
    if (!isEdit) {
      form.resetFields();
      form.setFieldsValue(initialValues);
    }
  }, [isEdit]);
  // 过滤
  const handleFilter = (flag, val) => {
    if (flag == 'startandend') {
      let val2 = val || [];
      filterObj['start_time'] = parseInt(
        new Date(dayjs(val2[0]).format('YYYY-MM-DD') + ' 00:00:00').getTime() / 1000,
      );
      const endDate = new Date(dayjs(val2[1])).getDate();
      const endTime = parseInt(
        new Date(dayjs(val2[1]).format('YYYY-MM-') + endDate + ' 23:59:59').getTime() / 1000,
      );
      filterObj['end_time'] = endTime;
      setDateVal(val);
      if (!val2.length) {
        delete filterObj['start_time'];
        delete filterObj['end_time'];
      }
    } else {
      filterObj[flag] = val;
    }
    for (const key in filterObj) {
      if (!filterObj[key]) {
        delete filterObj[key];
      }
    }
    setfilterObj({ ...filterObj });
    if (!val) init(filterObj);
  };
  const init = async (obj = {}) => {
    setLoading(true);
    const { total, list } = await getList({ page, page_size, ...obj });
    setTotal(total);
    setData(list);
    setLoading(false);
  };
  // 删除
  const handleDel = async () => {
    const bool = await delVersion({ id: delid });
    bool && init();
    setDelModal(false);
  };

  // 自定义版本号格式验证规则
  const validateVersionFormat = (rule, value) => {
    if (!value) {
      return Promise.resolve();
    }
    const versionPattern = /^\d+(\.\d+){2}$/;
    if (!versionPattern.test(value)) {
      return Promise.reject(new Error('版本号格式错误，应为X.X.X形式，其中X为数字'));
    }
    return Promise.resolve();
  };

  const columns = [
    {
      title: 'ID',
      key: 'id',
      align: 'center',
      dataIndex: 'id',
    },
    {
      title: '版本号',
      key: 'version',
      align: 'center',
      dataIndex: 'version',
      width: 200,
    },
    {
      title: '发布时间',
      key: 'create_time',
      align: 'center',
      dataIndex: 'create_time',
    },
    {
      title: '是否强制更新',
      key: 'is_compel',
      align: 'center',
      dataIndex: 'is_compel',
      render (_, { is_compel }) {
        let txt = is_compel == 0 ? '否' : '是';
        return txt;
      },
      align: 'center',
    },
    {
      title: '操作',
      key: 'handle',
      align: 'center',
      dataIndex: 'handle',
      render: (_, { id }) => {
        return (
          <Space>
            {operationPermissionsList.includes('/setting/applied/getInfoById') && (
              <Button onClick={() => handleEdit(id)}>编辑</Button>
            )}
            {operationPermissionsList.includes('/setting/applied/del') && (
              <Button
                onClick={() => {
                  setdelid(id);
                  setDelModal(true);
                }}
              >
                删除
              </Button>
            )}
          </Space>
        );
      },
    },
  ];
  return (
    <div className='classify'>
      <Row justify={'space-between'}>
        <Col className='form-devices-inline'>
          <Form layout='inline'>
            <Form.Item label='版本号'>
              <Input
                autoComplete='off'
                allowClear
                value={filterObj.version}
                placeholder='请输入版本号'
                id='name'
                onChange={(ev) => handleFilter('version', ev.target.value)}
              ></Input>
            </Form.Item>
            <Form.Item label='发布时间'>
              <RangePicker
                value={dateVal}
                id='createTime'
                onChange={(ev) => handleFilter('startandend', ev)}
              ></RangePicker>
            </Form.Item>
            <Space>
              <Button
                type='primary'
                ghost
                icon={
                  <span
                    style={{
                      display: 'inline-block',
                      width: '11px',
                      height: '10px',
                      pointerEvents: 'none',
                    }}
                  >
                    <Image src={reset} />
                  </span>
                }
                onClick={handleReset}
              >
                重置
              </Button>
              <Button
                type='primary'
                ghost
                icon={
                  <span
                    style={{
                      display: 'inline-block',
                      width: '13px',
                      height: '12px',
                      pointerEvents: 'none',
                    }}
                  >
                    <Image src={filter} />
                  </span>
                }
                onClick={() => {
                  setPage(1);
                  Object.values(filterObj).some((item) => item) ? init(filterObj) : init();
                }}
              >
                筛选
              </Button>
              <Button
                type='primary'
                ghost
                icon={
                  <span
                    style={{
                      display: 'inline-block',
                      width: '10px',
                      height: '12px',
                      pointerEvents: 'none',
                    }}
                  >
                    <Image src={reload} />
                  </span>
                }
                onClick={() =>
                  Object.values(filterObj).some((item) => item) ? init(filterObj) : init()
                }
              >
                刷新
              </Button>
            </Space>
          </Form>
        </Col>
        <Col>
          <Space>
            {operationPermissionsList.includes('/setting/applied/add') && (
              <Button
                type='primary'
                ghost
                icon={
                  <span
                    style={{
                      display: 'inline-block',
                      width: '13px',
                      height: '12px',
                      pointerEvents: 'none',
                    }}
                  >
                    <Image src={Add} />
                  </span>
                }
                onClick={() => {
                  setisadd(true);
                  setIsEdit(true);
                }}
              >
                添加
              </Button>
            )}
          </Space>
        </Col>
      </Row>
      <br />
      {TableCom({ columns, loading, data })}
      <Modal
        mask={false}
        centered
        open={delMoadal}
        onOk={handleDel}
        onCancel={() => setDelModal(false)}
        footer={(_, { OkBtn, CancelBtn }) => {
          return (
            <Row justify={'center'} className='delModal' style={{ marginBottom: '30px' }}>
              <Space size={20}>
                <CancelBtn className='cancel' />
                <OkBtn className='true' />
              </Space>
            </Row>
          );
        }}
        okText='确认'
      >
        <p style={{ textAlign: 'center', padding: '30px 0 18px', fontSize: 16 }}>
          版本将永久删除，是否继续?
        </p>
      </Modal>
      <br />
      <PaginationCom
        total={total}
        page_size={page_size}
        setpage_size={setpage_size}
        page={page}
        init={init}
        filterObj={filterObj}
        setPage={setPage}
      />
      <Drawer placement='right' onClose={onClose} open={isEdit} mask={false}>
        <Form form={form} onFinish={submitForm} labelCol={{ span: 6 }}>
          <Form.Item
            label='版本号'
            rules={[
              { required: true, message: '请输入版本号' },
              { max: 20, message: '最大20字符' },
              { validator: validateVersionFormat, trigger: ['change', 'blur'] },
            ]}
            name='version'
          >
            <Input autoComplete='off' placeholder='请输入版本号（格式：X.X.X）' />
          </Form.Item>
          {/* <Form.Item
            name='url'
            label='下载地址'
            rules={[
              { required: true, message: '请输入下载地址' },
              { max: 150, message: '最大150字符' },
            ]}
          >
            <Input autoComplete='off' placeholder='请输入下载地址'></Input>
          </Form.Item> */}
          <Form.Item
            name='url'
            label='上传apk包'
            rules={[{ required: true, message: '请上传apk包' }]}
          >
            <Spin spinning={uploading}>
              <Upload {...props}>
                <Button ghost type='primary'>
                  点击上传
                </Button>
              </Upload>
            </Spin>

            {/* {!isadd && <span style={{ fontSize: 12 }}>apk包为:&nbsp;{img}</span>} */}
          </Form.Item>
          {(!isadd || img) && (
            <Form.Item label='地址'>
              <Input disabled value={img} />
            </Form.Item>
          )}
          <Form.Item
            name='remarks'
            label='更新介绍'
            rules={[
              { required: true, message: '请输入更新介绍' },
              { max: 255, message: '最大255字符' },
            ]}
          >
            <TextArea
              placeholder='请输入更新介绍'
              autoSize={{
                minRows: 3,
                maxRows: 5,
              }}
            ></TextArea>
          </Form.Item>
          <Form.Item
            labelCol={{ span: 6 }}
            name='is_compel'
            label='是否强制更新'
            rules={[{ required: true, message: '请选择是否强制更新' }]}
          >
            <Radio.Group>
              <Radio value={0}>否</Radio>
              <Radio value={1}>是</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 5, span: 16 }} style={{ textAlign: 'center' }}>
            <Space size={20}>
              <Button
                className='cancel'
                onClick={() => {
                  setImg('');
                  setIsEdit(false);
                }}
              >
                取消
              </Button>
              <Button className='submit' htmlType='submit'>
                提交
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Drawer>
    </div>
  );
};

export default AppVersion;
