import { Button, Table } from 'antd';
import { ColumnsType } from 'antd/es/table';
import React, { useEffect, useState } from 'react';
import dayjs from 'dayjs';
import FileSaver from 'file-saver';
import { useNavigate } from 'react-router-dom';
import qs from 'query-string';
import { ExportOutlined } from '@ant-design/icons';
import SearchBox, { searchColumns } from '~/components/search-box';
import { CouponManageAPI } from '~/api';
import { PaginationEntity } from '~/common/interface/PaginationEntity';
import { couponDetailSearchType, couponDetailItemType } from '~/api/interface/couponManage';
import DataModal from './components/dataModal';
import useOperate from '~/common/hook/optionHook';

const gainTypeList = [
  { id: 'receive', name: '用户领取' },
  { id: 'send', name: '系统发放' },
  { id: 'presented', name: '赠送' },
  { id: 'acquire', name: '获赠' },
  { id: 'exchange', name: '积分兑换' },
];
const stateList = [
  { id: 0, name: '未使用' },
  { id: 1, name: '已使用' },
  { id: 2, name: '已失效' },
  { id: 3, name: '已转赠' },
  { id: 4, name: '使用中' },
];

const CouponDetailed = () => {
  const history = useNavigate();
  const searchColumns: searchColumns[] = [
    {
      type: 'input',
      name: 'uid',
      label: 'UID',
      placeholder: '请输入用户UID',
    },
    {
      type: 'input',
      name: 'userPhone',
      label: '手机号',
      placeholder: '请输入用户手机号',
    },
    {
      type: 'input',
      name: 'couponId',
      label: '优惠券ID',
      placeholder: '请输入优惠券ID',
    },
    {
      type: 'DatePicker',
      name: 'createTime',
      label: '领取时间',
      placeholder: '',
    },
    {
      type: 'DatePicker',
      name: 'useTime',
      label: '使用时间',
      placeholder: '',
    },
    {
      type: 'input',
      name: 'orderNumber',
      label: '订单编号',
      placeholder: '请输入订单编号',
    },
    {
      type: 'select',
      name: 'gainType',
      label: '流通方式',
      placeholder: '请选择流通方式',
      options: gainTypeList,
    },

    {
      type: 'select',
      name: 'state',
      label: '全部状态',
      placeholder: '请选择状态',
      options: stateList,
    },
  ];
  const tableColumns: ColumnsType<couponDetailItemType> = [
    {
      title: '优惠券ID',
      align: 'center',
      dataIndex: 'couponId',
    },
    {
      title: '优惠券名称',
      align: 'center',
      dataIndex: 'couponName',
    },
    {
      title: '用户UID',
      align: 'center',
      dataIndex: 'uuid',
    },
    {
      title: '手机号码',
      align: 'center',
      dataIndex: 'userPhone',
    },
    {
      title: '流通方式',
      align: 'center',
      render: (text: string, record: couponDetailItemType) => (
        <div>{gainTypeList.find((v) => v.id === record.gainType)?.name || ''}</div>
      ),
    },
    {
      title: '领取时间',
      align: 'center',
      dataIndex: 'createTime',
    },
    {
      title: '状态',
      align: 'center',
      render: (text: string, record: couponDetailItemType) => (
        <div>{stateList.find((v) => v.id === record.status)?.name || ''}</div>
      ),
    },
    {
      title: '使用时间',
      align: 'center',
      dataIndex: 'useTime',
    },
    {
      title: '订单编号',
      align: 'center',
      dataIndex: 'orderNo',
      render: (text: string, record: couponDetailItemType) =>
        record.orderNo && (
          <Button type='link' onClick={() => toOrderDetail(record)}>
            {record.orderNo}
          </Button>
        ),
    },
    {
      title: '操作',
      align: 'center',
      render: (text: string, record: couponDetailItemType) => (
        <Button
          type='link'
          onClick={() => showDataModalClick(record)}
          disabled={!isLookBtn || record.useType !== 1}
        >
          查看
        </Button>
      ),
    },
  ];
  const [pagination, setPagination] = useState<PaginationEntity>({
    pageNo: 1,
    pageSize: 10,
    totalCount: 0,
  });
  const [tableData, setTableData] = useState<couponDetailItemType[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [query, setQuery] = useState<couponDetailSearchType>();
  const [dataModalShow, setDataModalShow] = useState<boolean>(false);
  const [couponDetailItem, setCouponDetailItem] = useState<couponDetailItemType>();
  // 按钮权限
  const isExportBtn = useOperate(26301);
  const isLookBtn = useOperate(26302);

  // 获取优惠券明细
  const getCouponDetail = (
    data: Pick<PaginationEntity, 'pageNo' | 'pageSize'> & couponDetailSearchType,
  ) => {
    // setLoading(true);
    setTableData([
      {
        id: 45,
        couponId: 10000147,
        cid: null,
        orderNo: null,
        uid: 5058,
        uuid: 'UID8723232',
        userPhone: '13522927229',
        couponName: '科比特品牌优惠券',
        couponType: 1,
        useType: 2,
        couponMoney: null,
        minPrice: null,
        couponDiscount: 5,
        remainingBalance: null,
        gainType: 'send',
        status: 0,
        createTime: '2023-06-01 21:42:45',
        updateTime: null,
        startTime: '2023-04-21 00:00:00',
        endTime: '2023-12-31 23:59:59',
        useTime: null,
        primaryKey: '25',
        conversionRatio: null,
        transferorUid: null,
        receiveUid: null,
        transferorTime: null,
        verificationType: false,
        preferentialLimit: 10000,
        brandIds: null,
        discountCouponPrice: null,
      },
      {
        id: 44,
        couponId: 10000147,
        cid: null,
        orderNo: null,
        uid: 5102,
        uuid: 'UID9585857',
        userPhone: '17507736658',
        couponName: '科比特品牌优惠券',
        couponType: 1,
        useType: 2,
        couponMoney: null,
        minPrice: null,
        couponDiscount: 5,
        remainingBalance: null,
        gainType: 'send',
        status: 0,
        createTime: '2023-05-31 21:01:15',
        updateTime: null,
        startTime: '2023-04-21 00:00:00',
        endTime: '2023-12-31 23:59:59',
        useTime: null,
        primaryKey: '25',
        conversionRatio: null,
        transferorUid: null,
        receiveUid: null,
        transferorTime: null,
        verificationType: false,
        preferentialLimit: 10000,
        brandIds: null,
        discountCouponPrice: null,
      },
      {
        id: 43,
        couponId: 10000147,
        cid: null,
        orderNo: null,
        uid: 68,
        uuid: 'UID0080718',
        userPhone: '19168592452',
        couponName: '科比特品牌优惠券',
        couponType: 1,
        useType: 2,
        couponMoney: null,
        minPrice: null,
        couponDiscount: 5,
        remainingBalance: null,
        gainType: 'send',
        status: 0,
        createTime: '2023-05-29 19:53:05',
        updateTime: null,
        startTime: '2023-04-21 00:00:00',
        endTime: '2023-12-31 23:59:59',
        useTime: null,
        primaryKey: '25',
        conversionRatio: null,
        transferorUid: null,
        receiveUid: null,
        transferorTime: null,
        verificationType: false,
        preferentialLimit: 10000,
        brandIds: null,
        discountCouponPrice: null,
      },
      {
        id: 42,
        couponId: 10000147,
        cid: null,
        orderNo: null,
        uid: 5107,
        uuid: 'UID8562549',
        userPhone: '17891113617',
        couponName: '科比特品牌优惠券',
        couponType: 1,
        useType: 2,
        couponMoney: null,
        minPrice: null,
        couponDiscount: 5,
        remainingBalance: null,
        gainType: 'send',
        status: 0,
        createTime: '2023-05-29 13:23:26',
        updateTime: null,
        startTime: '2023-04-21 00:00:00',
        endTime: '2023-12-31 23:59:59',
        useTime: null,
        primaryKey: '25',
        conversionRatio: null,
        transferorUid: null,
        receiveUid: null,
        transferorTime: null,
        verificationType: false,
        preferentialLimit: 10000,
        brandIds: null,
        discountCouponPrice: null,
      },
      {
        id: 41,
        couponId: 10000147,
        cid: null,
        orderNo: null,
        uid: 5103,
        uuid: 'UID6512850',
        userPhone: '15678897088',
        couponName: '科比特品牌优惠券',
        couponType: 1,
        useType: 2,
        couponMoney: null,
        minPrice: null,
        couponDiscount: 5,
        remainingBalance: null,
        gainType: 'send',
        status: 0,
        createTime: '2023-05-29 10:54:11',
        updateTime: null,
        startTime: '2023-04-21 00:00:00',
        endTime: '2023-12-31 23:59:59',
        useTime: null,
        primaryKey: '25',
        conversionRatio: null,
        transferorUid: null,
        receiveUid: null,
        transferorTime: null,
        verificationType: false,
        preferentialLimit: 10000,
        brandIds: null,
        discountCouponPrice: null,
      },
      {
        id: 40,
        couponId: 10000147,
        cid: null,
        orderNo: null,
        uid: 5101,
        uuid: 'UID3723715',
        userPhone: '15129481077',
        couponName: '科比特品牌优惠券',
        couponType: 1,
        useType: 2,
        couponMoney: null,
        minPrice: null,
        couponDiscount: 5,
        remainingBalance: null,
        gainType: 'send',
        status: 0,
        createTime: '2023-05-29 10:41:45',
        updateTime: null,
        startTime: '2023-04-21 00:00:00',
        endTime: '2023-12-31 23:59:59',
        useTime: null,
        primaryKey: '25',
        conversionRatio: null,
        transferorUid: null,
        receiveUid: null,
        transferorTime: null,
        verificationType: false,
        preferentialLimit: 10000,
        brandIds: null,
        discountCouponPrice: null,
      },
      {
        id: 39,
        couponId: 10000147,
        cid: null,
        orderNo: null,
        uid: 4358,
        uuid: 'UID1649471',
        userPhone: '15991160565',
        couponName: '科比特品牌优惠券',
        couponType: 1,
        useType: 2,
        couponMoney: null,
        minPrice: null,
        couponDiscount: 5,
        remainingBalance: null,
        gainType: 'send',
        status: 0,
        createTime: '2023-05-29 09:06:22',
        updateTime: null,
        startTime: '2023-04-21 00:00:00',
        endTime: '2023-12-31 23:59:59',
        useTime: null,
        primaryKey: '25',
        conversionRatio: null,
        transferorUid: null,
        receiveUid: null,
        transferorTime: null,
        verificationType: false,
        preferentialLimit: 10000,
        brandIds: null,
        discountCouponPrice: null,
      },
      {
        id: 38,
        couponId: 10000147,
        cid: null,
        orderNo: null,
        uid: 5083,
        uuid: 'UID4145719',
        userPhone: '18931209999',
        couponName: '科比特品牌优惠券',
        couponType: 1,
        useType: 2,
        couponMoney: null,
        minPrice: null,
        couponDiscount: 5,
        remainingBalance: null,
        gainType: 'send',
        status: 0,
        createTime: '2023-05-27 18:00:48',
        updateTime: null,
        startTime: '2023-04-21 00:00:00',
        endTime: '2023-12-31 23:59:59',
        useTime: null,
        primaryKey: '25',
        conversionRatio: null,
        transferorUid: null,
        receiveUid: null,
        transferorTime: null,
        verificationType: false,
        preferentialLimit: 10000,
        brandIds: null,
        discountCouponPrice: null,
      },
      {
        id: 37,
        couponId: 10000147,
        cid: null,
        orderNo: null,
        uid: 2376,
        uuid: 'UID3278532',
        userPhone: '15912163681',
        couponName: '科比特品牌优惠券',
        couponType: 1,
        useType: 2,
        couponMoney: null,
        minPrice: null,
        couponDiscount: 5,
        remainingBalance: null,
        gainType: 'send',
        status: 0,
        createTime: '2023-05-25 16:07:09',
        updateTime: null,
        startTime: '2023-04-21 00:00:00',
        endTime: '2023-12-31 23:59:59',
        useTime: null,
        primaryKey: '25',
        conversionRatio: null,
        transferorUid: null,
        receiveUid: null,
        transferorTime: null,
        verificationType: false,
        preferentialLimit: 10000,
        brandIds: null,
        discountCouponPrice: null,
      },
      {
        id: 35,
        couponId: 10000156,
        cid: null,
        orderNo: null,
        uid: 5055,
        uuid: 'UID2886699',
        userPhone: '15185632216',
        couponName: '人党的飞飞',
        couponType: 3,
        useType: 2,
        couponMoney: 12,
        minPrice: null,
        couponDiscount: null,
        remainingBalance: null,
        gainType: 'send',
        status: 0,
        createTime: '2023-05-25 15:34:13',
        updateTime: null,
        startTime: '2023-05-26 00:00:00',
        endTime: '2023-06-22 23:59:59',
        useTime: null,
        primaryKey: '31',
        conversionRatio: null,
        transferorUid: null,
        receiveUid: null,
        transferorTime: null,
        verificationType: false,
        preferentialLimit: null,
        brandIds: null,
        discountCouponPrice: null,
      },
    ]);
    CouponManageAPI.getCouponDetail(data).then(({ result }) => {
      const tableData = (result.list || []).map((v) => ({
        ...v,
        selfId: Math.random(),
      }));
      setLoading(false);
      setTableData(tableData);
      setPagination({
        pageNo: data.pageNo,
        pageSize: data.pageSize,
        totalCount: result.totalCount,
      });
    });
  };
  // 数据筛选
  const searchDataEvents = (data: any) => {
    data.createTime = data.createTime ? dayjs(data.createTime).format('YYYY-MM-DD') : undefined;
    data.useTime = data.useTime ? dayjs(data.useTime).format('YYYY-MM-DD') : undefined;
    setQuery(data);
    getCouponDetail({ pageNo: 1, pageSize: 10, ...data });
  };
  // 导出
  const exportEvent = () => {
    CouponManageAPI.downloadCouponUserList({
      ...query,
      pageNo: pagination.pageNo,
      pageSize: pagination.pageSize,
    }).then((res: any) => {
      const blob = new Blob([res], {
        type: 'application/vnd.ms-excel',
      });
      FileSaver.saveAs(blob, `优惠券明细数据导出_${new Date().toLocaleString()}`);
    });
  };
  // 分页
  const paginationChange = (pageNo: number, pageSize: number) => {
    getCouponDetail({ pageNo, pageSize, ...query });
  };
  // vip 券数据详情
  const showDataModalClick = (record: couponDetailItemType) => {
    setCouponDetailItem(record);
    setDataModalShow(true);
  };
  const dataModalCancel = () => {
    setDataModalShow(false);
  };
  // 跳转订单详情
  const toOrderDetail = (record: couponDetailItemType) => {
    history({
      pathname: '/orderManage/list/detail',
      search: qs.stringify({
        id: record.cid,
      }),
    });
  };

  useEffect(() => {
    getCouponDetail({ pageNo: 1, pageSize: 10 });
  }, []);

  return (
    <div className='coupon-detailed'>
      <SearchBox
        search={searchColumns}
        searchData={searchDataEvents}
        otherChild={
          <Button
            onClick={exportEvent}
            type='primary'
            icon={<ExportOutlined disabled={!isExportBtn} />}
          >
            导出
          </Button>
        }
      />
      <Table
        columns={tableColumns}
        bordered
        dataSource={tableData}
        rowKey='selfId'
        loading={loading}
        pagination={{
          total: pagination.totalCount,
          pageSize: pagination.pageSize,
          current: pagination.pageNo,
          showSizeChanger: true,
          showQuickJumper: true,
          onChange: (page: number, pageSize: number) => paginationChange(page, pageSize),
          showTotal: (total, range) => `当前 ${range[0]}-${range[1]} 条记录 / 共 ${total} 条数据`,
        }}
      />
      <DataModal
        isModalVisible={dataModalShow}
        handleCancel={dataModalCancel}
        couponDetailItem={couponDetailItem}
      />
    </div>
  );
};
export default CouponDetailed;
