import React, { useEffect, useState, useRef } from 'react';
import {
  Table,
  Input,
  Popover,
  Tooltip,
  Button,
  Row,
  Col,
  Space,
  DatePicker,
  Drawer,
  Image,
  Form,
  Modal,
  Switch,
  Select,
  Upload,
  Spin,
  message,
} from 'antd';
import { useNavigate } from 'react-router-dom';
import { useSelector } from 'react-redux';
const { RangePicker } = DatePicker;
import PaginationCom from '@/common/Pagination';
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 add from '@/assets/images/icon/add.png';
import { addAd, getList, InfoAd, editAd, delAd, changeStatus } from './request';
import { uploadFiles } from '@/utils/upload';
import { getPositionList } from '../adsense/request';
import dayjs from 'dayjs';
import AliOSS from 'ali-oss';
import { getAliOSSSTSToken } from '@/pages/setting/help/addedit/requet';
import TableCom from '@/common/TableCom/index';

const Advertising = () => {
  const [data, setData] = useState([]);
  const navigate = useNavigate();
  const [page_size, setpage_size] = useState(10);
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(true);
  const [showModal, setshowModal] = useState(false);
  const [isAdd, setIsAdd] = useState(false);
  const [delMoadal, setDelModal] = useState(false);
  const [form] = Form.useForm();
  const flag = useRef(true);
  // 获取操作权限
  const { operationPermissionsList } = useSelector((state) => state.user);
  // 广告位数据
  const [positionData, setPositionData] = useState([]);
  const [filterObj, setfilterObj] = useState({
    name: '',
    position_id: null,
    start_time: '',
    end_time: '',
  });
  const [dateVal, setDateVal] = useState('');

  const [ossClient, setOssClient] = useState(null); // oss 操作
  const [STSToken, setSTSToken] = useState(null); // oss 过期设置
  const [file, setFile] = useState({});
  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-ad-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);
      }
      resolve();
    });
  };
  // 过滤
  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 handleReset = () => {
    setfilterObj({ name: '', position_id: '' });
    setDateVal('');
    init();
  };
  const handleStatus = async (val, id) => {
    const bool = await changeStatus({ id, status: val ? '1' : '0' });
    bool && init();
  };
  const init = async (obj = {}) => {
    setLoading(true);
    const { total, list } = await getList({ page, page_size, ...obj });
    setTotal(total);
    setData(list);
    setLoading(false);
  };
  const [id, setId] = useState(0);
  const handleEdit = async (obj) => {
    const data = await InfoAd({ id: obj.id });
    let { start_validity, end_validity, id } = data;
    setIsAdd(false);
    setshowModal(true);
    form.setFieldsValue({ ...data, validity: [dayjs(start_validity), dayjs(end_validity)] });
    setUploadimg(data.pic);
    setId(id);
  };
  const onClose = () => {
    setshowModal(false);
  };
  const submitForm = async (obj) => {
    let bool;
    let { validity } = obj;
    let start_validity =
      new Date(dayjs(validity[0]).format('YYYY-MM-DD') + ' 00:00:00').getTime() / 1000;
    let end_validity =
      new Date(dayjs(validity[1]).format('YYYY-MM-DD') + ' 23:59:59').getTime() / 1000;
    let uploadObj = { ...obj };
    delete uploadObj.validity;
    if (isAdd) {
      bool = await addAd({ ...uploadObj, start_validity, end_validity, pic: uploadimg });
    } else {
      bool = await editAd({ ...uploadObj, id, start_validity, end_validity, pic: uploadimg });
    }
    if (!bool) return;
    init();
    setshowModal(false);
  };
  const delSuccess = async () => {
    setDelModal(false);
    const bool = await delAd({ id });
    bool && init();
  };
  const getPosition = async () => {
    const { list } = await getPositionList();
    setPositionData(list);
  };
  useEffect(() => {
    // if(!flag.current){
    getPosition();
    getStsAuthToken();
    // }else{
    //   flag.current=false
    // }
  }, []);
  const columns = [
    {
      title: 'ID',
      key: 'id',
      dataIndex: 'id',
    },
    {
      title: '所属广告位',
      key: 'position_name',
      align: 'center',
      dataIndex: 'position_name',
    },
    {
      title: '广告名称',
      key: 'name',
      dataIndex: 'name',
      width: 200,
      align: 'center',
      render: (text) => (
        <Popover content={text} overlayStyle={{ maxWidth: '400px' }} visible={false}>
          <div
            style={{
              display: '-webkit-box',
              WebkitLineClamp: '3',
              WebkitBoxOrient: 'vertical',
              overflow: 'hidden',
              textOverflow: 'ellipsis',
              textAlign: 'center',
            }}
          >
            {text}
          </div>
        </Popover>
      ),
    },
    {
      title: '广告图片',
      key: 'pic',
      dataIndex: 'pic',
      align: 'center',
      render: (_, { pic }) => (
        <Image
          width={80}
          height={80}
          src={pic}
          fallback='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMIAAADDCAYAAADQvc6UAAABRWlDQ1BJQ0MgUHJvZmlsZQAAKJFjYGASSSwoyGFhYGDIzSspCnJ3UoiIjFJgf8LAwSDCIMogwMCcmFxc4BgQ4ANUwgCjUcG3awyMIPqyLsis7PPOq3QdDFcvjV3jOD1boQVTPQrgSkktTgbSf4A4LbmgqISBgTEFyFYuLykAsTuAbJEioKOA7DkgdjqEvQHEToKwj4DVhAQ5A9k3gGyB5IxEoBmML4BsnSQk8XQkNtReEOBxcfXxUQg1Mjc0dyHgXNJBSWpFCYh2zi+oLMpMzyhRcASGUqqCZ16yno6CkYGRAQMDKMwhqj/fAIcloxgHQqxAjIHBEugw5sUIsSQpBobtQPdLciLEVJYzMPBHMDBsayhILEqEO4DxG0txmrERhM29nYGBddr//5/DGRjYNRkY/l7////39v///y4Dmn+LgeHANwDrkl1AuO+pmgAAADhlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAAqACAAQAAAABAAAAwqADAAQAAAABAAAAwwAAAAD9b/HnAAAHlklEQVR4Ae3dP3PTWBSGcbGzM6GCKqlIBRV0dHRJFarQ0eUT8LH4BnRU0NHR0UEFVdIlFRV7TzRksomPY8uykTk/zewQfKw/9znv4yvJynLv4uLiV2dBoDiBf4qP3/ARuCRABEFAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghggQAQZQKAnYEaQBAQaASKIAQJEkAEEegJmBElAoBEgghgg0Aj8i0JO4OzsrPv69Wv+hi2qPHr0qNvf39+iI97soRIh4f3z58/u7du3SXX7Xt7Z2enevHmzfQe+oSN2apSAPj09TSrb+XKI/f379+08+A0cNRE2ANk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ts/EbcvGAHhHyfBIhZ6NSiIBTo0LNNtScABFyNiqFCBChULMNNSdAhJyNSiECRCjUbEPNCRAhZ6NSiAARCjXbUHMCRMjZqBQiQIRCzTbUnAARcjYqhQgQoVCzDTUnQIScjUohAkQo1GxDzQkQIWejUogAEQo121BzAkTI2agUIkCEQs021JwAEXI2KoUIEKFQsw01J0CEnI1KIQJEKNRsQ80JECFno1KIABEKNdtQcwJEyNmoFCJAhELNNtScABFyNiqFCBChULMNNSdAhJyNSiECRCjUbEPNCRAhZ6NSiAARCjXbUHMCRMjZqBQiQIRCzTbUnAARcjYqhQgQoVCzDTUnQIScjUohAkQo1GxDzQkQIWejUogAEQo121BzAkTI2agUIkCEQs021JwAEXI2KoUIEKFQsw01J0CEnI1KIQJEKNRsQ80JECFno1KIABEKNdtQcwJEyNmoFCJAhELNNtScABFyNiqFCBChULMNNSdAhJyNSiECRCjUbEPNCRAhZ6NSiAARCjXbUHMCRMjZqBQiQIRCzTbUnAARcjYqhQgQoVCzDTUnQIScjUohAkQo1GxDzQkQIWejUogAEQo121BzAkTI2agUIkCEQs021JwAEXI2KoUIEKFQsw01J0CEnI1KIQJEKNRsQ80JECFno1KIABEKNdtQcwJEyNmoFCJAhELNNtScABFyNiqFCBChULMNNSdAhJyNSiEC/wGgKKC4YMA4TAAAAABJRU5ErkJggg=='
        />
      ),
    },
    {
      title: '广告链接地址',
      key: 'url',
      dataIndex: 'url',
      align: 'center',
      width: 200,
      render: (text) => (
        <Popover
          content={text}
          overlayStyle={{
            maxWidth: '400px',
            whiteSpace: 'pre-wrap',
            wordBreak: 'breal-all',
            wordWrap: 'break-word',
          }}
        >
          <div
            style={{
              textAlign: 'left',
              maxWidth: '300px',
            }}
          >
            <a href={text} target='_blank' rel='noreferrer'>
              {text.length > 80 ? `${text.substring(0, 80)}...` : text}
            </a>
          </div>
        </Popover>
      ),
    },
    {
      title: '状态',
      key: 'status',
      align: 'center',
      dataIndex: 'status',
      render (_, { id, status }) {
        return (
          <Switch
            defaultChecked={status == '1' ? true : false}
            onChange={(ev) => handleStatus(ev, id)}
            disabled={!operationPermissionsList.includes('/advertisement/advert/changeStatus')}
          />
        );
      },
    },
    {
      title: '有效期开始时间',
      key: 'start_validity',
      dataIndex: 'start_validity',
      align: 'center',
    },
    {
      title: '有效期结束时间',
      key: 'end_validity',
      dataIndex: 'end_validity',
      align: 'center',
    },
    {
      title: '操作',
      key: 'handle',
      dataIndex: 'handle',
      align: 'center',
      render: (_, record) => {
        return (
          <Space>
            {operationPermissionsList.includes('/advertisement/advert/getInfoById') && (
              <Button onClick={() => handleEdit(record)}>编辑</Button>
            )}
            {operationPermissionsList.includes('/advertisement/advert/del') && (
              <Button
                onClick={() => {
                  setId(record.id);
                  setDelModal(true);
                }}
              >
                删除
              </Button>
            )}
          </Space>
        );
      },
    },
  ];
  const [formload, setFormLoad] = useState(false);
  const [uploadimg, setUploadimg] = useState('');
  // 图片上传
  const uploadImg = async (file) => {
    setFormLoad(true);
    const { url } = await uploadFiles({ file, file_type: 'ad' });
    setUploadimg(url);
    setFormLoad(false);
  };
  const props = {
    name: 'file',
    accept: '.jpg,.png',
    showUploadList: false,
    beforeUpload (file) {
      const suffixArr = ['jpg', 'png'];
      const suffix = file.name.substring(file.name.lastIndexOf('.') + 1);
      if (!suffixArr.includes(suffix)) {
        message.error(`请上传以${suffixArr.join('、')}格式的书籍`);
        return false;
      }
      setFile(file);
    },
    customRequest: async () => {
      if (!ossClient) {
        message.error('ossClient还未初始化', ossClient);
        return false;
      }

      try {
        const fileExt = file.name.substring(file.name.lastIndexOf('.'));
        const fileName = `ad-${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 状态
        setUploadimg(imageUrl);
        form.setFieldsValue({ pic: imageUrl });

        // 上传成功，返回 true 表示可以继续上传
        return true;
      } catch (error) {
        // 上传失败，处理错误
        console.error('上传文件失败：', error);
        message.error('上传文件失败，请重试');
        return false;
      }
    },
  };
  const [initialValues, setinitialValues] = useState({
    position_id: null,
    name: '',
    pic: '',
    validity: '',
    url: '',
  });
  useEffect(() => {
    if (!showModal) {
      form.resetFields();
      form.setFieldsValue(initialValues);
      setUploadimg('');
    }
  }, [showModal]);
  return (
    <div>
      <Row justify={'space-between'}>
        <Col className='form-devices-inline'>
          <Form layout='inline'>
            <Form.Item label='所属广告位'>
              <Select
                style={{ width: 160 }}
                value={filterObj.position_id}
                allowClear
                id='position_id'
                placeholder='请选择所属广告位'
                onChange={(ev) => handleFilter('position_id', ev)}
              >
                {positionData.length &&
                  positionData.map((item) => (
                    <Select.Option key={item.id} value={item.id}>
                      {item.position_name}
                    </Select.Option>
                  ))}
              </Select>
            </Form.Item>
            <Form.Item label='广告名称'>
              <Input
                autoComplete='off'
                allowClear
                value={filterObj.name}
                onChange={(ev) => handleFilter('name', ev.target.value)}
                placeholder='请输入广告名称'
                id='name'
              ></Input>
            </Form.Item>
            <Form.Item label='有效期'>
              <RangePicker
                value={dateVal}
                onChange={(ev) => handleFilter('startandend', ev)}
                id='createTime'
              ></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('/advertisement/advert/add') && (
              <Button
                type='primary'
                ghost
                onClick={() => {
                  setIsAdd(true);
                  setshowModal(true);
                }}
                icon={
                  <span
                    style={{
                      display: 'inline-block',
                      width: '13px',
                      height: '12px',
                      pointerEvents: 'none',
                    }}
                  >
                    <Image src={add} />
                  </span>
                }
              >
                添加
              </Button>
            )}
          </Space>
        </Col>
      </Row>
      <br />
      {TableCom({ columns, loading, data })}
      <Modal
        mask={false}
        centered
        open={delMoadal}
        onOk={delSuccess}
        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}
        setPage={setPage}
        init={init}
        filterObj={filterObj}
      />
      <Drawer placement='right' onClose={onClose} open={showModal} mask={false}>
        <Spin spinning={formload}>
          <Form form={form} onFinish={submitForm} labelCol={{ span: 7 }}>
            <Form.Item
              label='所属广告位'
              rules={[{ required: true, message: '请选择所属广告位' }]}
              name='position_id'
            >
              <Select placeholder='请选择所属广告位'>
                {positionData.length &&
                  positionData.map((item) => (
                    <Select.Option key={item.id} value={item.id}>
                      {item.position_name}
                    </Select.Option>
                  ))}
              </Select>
            </Form.Item>
            <Form.Item
              label='广告名称'
              rules={[
                { required: true, message: '请输入广告名称' },
                { max: 80, message: '最大80个字符' },
              ]}
              name='name'
            >
              <Input autoComplete='off' placeholder='请输入广告名称'></Input>
            </Form.Item>
            <Form.Item
              name='pic'
              label='广告图片'
              rules={[{ required: true, message: '请选择广告图片' }]}
            >
              <div>
                <Upload {...props}>
                  <Button ghost type='primary'>
                    点击上传
                  </Button>
                </Upload>
                {uploadimg && (
                  <div className='img' style={{ marginTop: 10 }}>
                    <Image src={uploadimg} width={80} height={80} />
                  </div>
                )}
              </div>
            </Form.Item>
            <Form.Item
              name='validity'
              label='广告有效期'
              rules={[
                { required: true, message: '请选择广告有效期' },

                {
                  validator (_, val) {
                    if (!val || val.length !== 2) {
                      return Promise.reject('');
                    }

                    const today = new Date();
                    const startDate = new Date(
                      today.getFullYear(),
                      today.getMonth(),
                      today.getDate(),
                    );
                    const endDate = new Date(
                      today.getFullYear(),
                      today.getMonth(),
                      today.getDate(),
                      23,
                      59,
                    );

                    if (endDate.getFullYear() > 2101) {
                      return Promise.reject('有效期结束时间最大限制2100-12-31');
                    } else if (startDate <= endDate) {
                      return Promise.resolve();
                    } else {
                      return Promise.reject('开始时间要小于结束时间');
                    }
                  },
                },
              ]}
            >
              <RangePicker />
            </Form.Item>
            <Form.Item
              name='url'
              label='广告链接地址'
              rules={[{ max: 500, message: '最大长度500' }]}
            >
              <Input autoComplete='off' placeholder='请输入广告链接地址' />
            </Form.Item>
            <Form.Item wrapperCol={{ offset: 11, span: 16 }}>
              <Space size={20}>
                <Button className='cancel' onClick={() => setshowModal(false)}>
                  取消
                </Button>
                <Button className='submit' htmlType='submit'>
                  提交
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Spin>
      </Drawer>
    </div>
  );
};

export default Advertising;
