import React, { useEffect, useState, useRef } from 'react';
import {
  Table,
  Input,
  Button,
  Row,
  Col,
  Space,
  DatePicker,
  Select,
  Drawer,
  Popover,
  Form,
  Modal,
  Switch,
  Image,
} from 'antd';
const { RangePicker } = DatePicker;
import PaginationCom from '@/common/Pagination';
const { TextArea } = Input;
import {
  getList,
  addCoupon,
  recordCoupon,
  editCoupon,
  delCoupon,
  getCoupon,
  setCoupon,
  getInfoById,
} from './request';
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 coupon from '@/assets/images/icon/coupon.png';
import coupon2 from '@/assets/images/icon/coupon2.png';
import { useSelector } from 'react-redux';
const Coupon = () => {
  const [data, setData] = useState([]);
  const [page_size, setpage_size] = useState(10);
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(4);
  const [couponTel, setcouponTel] = useState('');
  const [loading, setLoading] = useState(true);
  // 添加/编辑的弹框
  const [isEdit, setIsEdit] = useState(false);
  const [delMoadal, setDelModal] = useState(false);
  const [form] = Form.useForm();
  const [form2] = Form.useForm();
  // 获取操作权限
  const { operationPermissionsList } = useSelector((state) => state.user);
  // 是否添加
  const [isadd, setisadd] = useState(true);
  // 操作某一项的id
  const [id, setid] = useState(0);
  const [couponModal, setCouponModal] = useState(false);
  const [initialValues, setinitialValues] = useState({
    name: '',
    norm_price: '',
    reduced_price: '',
    end_time: '',
  });
  const [filterObj, setfilterObj] = useState({
    name: '',
  });
  const [switchFlag, setSwitchFlag] = useState(false);
  const [dateVal, setDateVal] = useState('');
  // 过滤
  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 handleEdit = async (id) => {
    setid(id);
    setisadd(false);
    const data = await getInfoById({ id });
    let { end_time, start_time } = data;
    form.setFieldsValue({ ...data, validity: [dayjs(start_time), dayjs(end_time)] });
    setisadd(false);
    setIsEdit(true);
  };
  const onClose = () => {
    setIsEdit(false);
  };
  // 添加/编辑优惠券
  const submitForm = async (obj) => {
    let { validity } = obj;
    let start_time =
      new Date(dayjs(validity[0]).format('YYYY-MM-DD') + ' 00:00:00').getTime() / 1000;
    let end_time = new Date(dayjs(validity[1]).format('YYYY-MM-DD') + ' 23:59:59').getTime() / 1000;
    let copyObj = { ...obj, end_time, start_time }; // 将变量初始化移到使用之前
    delete copyObj.validity;

    console.log('点击了提交表单');
    console.log('isadd:', isadd);
    console.log('copyObj:', copyObj);

    let bool;
    if (isadd) {
      bool = await addCoupon(copyObj);
    } else {
      bool = await editCoupon({
        ...copyObj,
        id,
      });
    }

    if (!bool) return;
    init(filterObj);
    setIsEdit(false);
  };

  const handleReset = () => {
    setfilterObj({ name: '' });
    init();
  };
  // 发放优惠券
  const handleRecord = async (obj) => {
    const res = await recordCoupon(obj);

    setCouponModal(false);
  };

  const delSuccess = async () => {
    const bool = await delCoupon({ id });
    if (!bool) return;
    setDelModal(false);
    init();
  };
  const init = async (obj = {}) => {
    setLoading(true);
    const { total, list } = await getList({ page, page_size, ...obj });
    setTotal(total);
    setData(list);
    setLoading(false);
  };
  // 获取优惠券开关状态
  const handleCoupon = async () => {
    // if(!flag.current){
    const { coupon_switch } = await getCoupon();
    coupon_switch == '1' ? setSwitchFlag(true) : setSwitchFlag(false);
    // }else{
    // flag.current=false
    // }
  };
  const [swithcLoad, setSwitchLoad] = useState(false);
  // 改变优惠券开关
  const changeCoupon = async (val) => {
    setSwitchLoad(true);
    let coupon_switch = val ? '1' : '0';
    const bool = await setCoupon({ coupon_switch });
    setTimeout(() => {
      setSwitchLoad(false);
    }, 500);
    handleCoupon();
  };
  useEffect(() => {
    if (!isEdit) {
      form.setFieldsValue(initialValues);
      form.resetFields();
    }
    if (!couponModal) {
      form2.setFieldsValue({ phone: '', id: null });
      form2.resetFields();
    }
  }, [isEdit, couponModal]);
  useEffect(() => {
    handleCoupon();
  }, []);
  const columns = [
    {
      title: 'ID',
      key: 'id',
      align: 'center',
      dataIndex: 'id',
    },
    {
      title: '优惠券名称',
      key: 'name',
      align: 'center',
      dataIndex: 'name',
      width: 200,
      render: (text) => (
        <Popover content={text} overlayStyle={{ maxWidth: '400px' }}>
          <div
            style={{
              display: '-webkit-box',
              WebkitLineClamp: '2',
              WebkitBoxOrient: 'vertical',
              overflow: 'hidden',
              textOverflow: 'ellipsis',
              textAlign: 'center',
            }}
          >
            {text}
          </div>
        </Popover>
      ),
    },
    {
      title: '达标金额',
      key: 'norm_price',
      align: 'center',
      dataIndex: 'norm_price',
    },
    {
      title: '满减金额',
      key: 'reduced_price',
      align: 'center',
      dataIndex: 'reduced_price',
    },
    {
      title: '有效期开始时间',
      key: 'start_time',
      align: 'center',
      dataIndex: 'start_time',
    },
    {
      title: '有效期结束时间',
      key: 'end_time',
      align: 'center',
      dataIndex: 'end_time',
    },
    {
      title: '领取人数',
      key: 'receive_num',
      align: 'center',
      dataIndex: 'receive_num',
    },
    {
      title: '使用人数',
      key: 'use_num',
      align: 'center',
      dataIndex: 'use_num',
    },
    {
      title: '操作',
      key: 'handle',
      align: 'center',
      dataIndex: 'handle',
      render: (_, { id }) => {
        return (
          <Space>
            {operationPermissionsList.includes('/setting/coupon/getInfoById') && (
              <Button onClick={() => handleEdit(id)}>编辑</Button>
            )}
            {operationPermissionsList.includes('/setting/coupon/del') && (
              <Button
                onClick={() => {
                  setid(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
                placeholder='请输入优惠券名称'
                value={filterObj.name}
                onChange={(ev) => handleFilter('name', ev.target.value)}
                id='name'
              ></Input>
            </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>
            <label htmlFor='coupon'>优惠券开关</label>
            <Switch
              checked={switchFlag}
              loading={swithcLoad}
              onChange={changeCoupon}
              disabled={!operationPermissionsList.includes('/setting/coupon/getCoupon')}
            ></Switch>
            {operationPermissionsList.includes('/setting/coupon/add') && (
              <Button
                type='primary'
                disabled={!switchFlag}
                ghost
                icon={
                  <img
                    style={{
                      background: !switchFlag,
                      display: 'inline-block',
                      width: '13px',
                      height: '11px',
                      pointerEvents: 'none',
                    }}
                    src={!switchFlag ? coupon2 : coupon}
                  />
                }
                onClick={() => setCouponModal(true)}
              >
                优惠券发放
              </Button>
            )}
            {operationPermissionsList.includes('/setting/coupon/give') && (
              <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={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
        page_size={page_size}
        setpage_size={setpage_size}
        page={page}
        init={init}
        filterObj={filterObj}
        setPage={setPage}
        total={total}
      />
      <Drawer placement='right' onClose={onClose} open={isEdit} mask={false}>
        <Form form={form} onFinish={submitForm} labelCol={{ span: 6 }}>
          <Form.Item
            name='name'
            label='优惠券名称'
            rules={[
              { required: true, message: '请输入优惠券名称' },
              { max: 30, message: '最大30字符' },
            ]}
          >
            <Input autoComplete='off' placeholder='请输入优惠券名称'></Input>
          </Form.Item>
          <Form.Item
            name='norm_price'
            label='达标金额'
            rules={[
              { required: true, message: '请输入达标金额' },

              {
                validator: (_, value) => {
                  return new Promise((resolve, reject) => {
                    if (!value || /^[1-9]\d*$/.test(value)) {
                      resolve();
                    } else {
                      reject(new Error('必须是正整数'));
                    }
                  });
                },
              },
            ]}
          >
            <Input autoComplete='off' placeholder='请输入达标金额'></Input>
          </Form.Item>

          <Form.Item
            name='reduced_price'
            label='满减金额'
            rules={[
              { required: true, message: '请输入满减金额' },
              {
                validator: (_, value) => {
                  return new Promise((resolve, reject) => {
                    if (!value || /^[1-9]\d*$/.test(value)) {
                      resolve();
                    } else if (!(Number(value) <= Number(form.getFieldValue('norm_price')))) {
                      reject('小于等于达标金额');
                    }
                  });
                },
              },
            ]}
          >
            <Input autoComplete='off' placeholder='请输入满减金额'></Input>
          </Form.Item>
          <Form.Item
            name='validity'
            label='有效期'
            rules={[{ required: true, message: '请选择有效期' }]}
          >
            <RangePicker
              value={dateVal}
              onChange={(ev) => handleFilter('startandend', ev)}
              id='createTime'
            ></RangePicker>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 6, span: 16 }} style={{ textAlign: 'center' }}>
            <Space size={20}>
              <Button className='cancel' onClick={() => setIsEdit(false)}>
                取消
              </Button>
              <Button className='submit' htmlType='submit'>
                提交
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Drawer>
      <Drawer
        placement='right'
        onClose={() => setCouponModal(false)}
        open={couponModal}
        mask={false}
      >
        <Form form={form2} onFinish={handleRecord} labelCol={{ span: 6 }}>
          <Form.Item
            name='phone'
            label='用户手机号'
            rules={[{ required: true, message: '请输入用户手机号' }]}
          >
            <TextArea
              placeholder='请输入用户手机号，用英文逗号隔开，每次最多100个'
              autoSize={{
                minRows: 5,
                maxRows: 8,
              }}
            ></TextArea>
          </Form.Item>
          <Form.Item
            name='id'
            label='发放优惠券'
            rules={[{ required: true, message: '请选择优惠券' }]}
          >
            <Select placeholder='请选择优惠券'>
              {data &&
                data.map((item) => (
                  <Select.Option value={item.id} key={item.id}>
                    {item.name}
                  </Select.Option>
                ))}
            </Select>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 5, span: 16 }} style={{ textAlign: 'center' }}>
            <Space size={20}>
              <Button className='cancel' onClick={() => setCouponModal(false)}>
                取消
              </Button>
              <Button className='submit' htmlType='submit'>
                提交
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Drawer>
    </div>
  );
};

export default Coupon;
