import { FC, useEffect, useState } from 'react';
import { Button, Table, Modal, message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { ColumnsType } from 'antd/es/table';
import { useNavigate } from 'react-router-dom';
import qs from 'query-string';
import SearchBox, { searchColumns } from '~/components/search-box';
import { PaginationEntity } from '~/common/interface/PaginationEntity';
import { SplitCouponItemType, SplitCouponSearchType } from '~/api/interface/couponManage';
import { CouponManageAPI } from '~/api';
import { splitCouponType, splitCouponUseType } from '~/utils/dictionary';
import { DataModal } from '~/pages/couponManage/couponList/comp/dataModal';
import useOperate from '~/common/hook/optionHook';
import './index.scss';

const SplitCouponList: FC = () => {
  const history = useNavigate();
  const searchData: searchColumns[] = [
    {
      type: 'input',
      placeholder: '请输入优惠券ID',
      label: 'ID',
      name: 'couponId',
    },
    {
      type: 'input',
      placeholder: '请输入优惠券名称',
      label: '名称',
      name: 'couponName',
    },
    // {
    //   type: "input",
    //   placeholder: "请输入面额",
    //   label: "面额",
    //   name: "",
    // },
    {
      type: 'select',
      placeholder: '请选中状态',
      name: 'state',
      label: '状态',
      options: [
        {
          id: 0,
          name: '已结束',
        },
        {
          id: 1,
          name: '领取中',
        },
      ],
    },
    {
      type: 'rangePicker',
      placeholder: '',
      label: '日期',
      name: 'time',
    },
  ];

  const tableColumns: ColumnsType<SplitCouponItemType> = [
    {
      title: '优惠券ID',
      align: 'center',
      dataIndex: 'id',
      onCell: (record: SplitCouponItemType, rowIndex: any) => ({
        rowSpan: rowIndex % 2 ? 0 : 2,
      }),
    },
    {
      title: '优惠券名称',
      align: 'center',
      dataIndex: 'couponName',
    },
    {
      title: '角色',
      align: 'center',
      dataIndex: 'activityRole',
      render: (text: string, record: SplitCouponItemType) => (
        <div>{record.activityRole === 'share' ? '分享者' : '被分享者'}</div>
      ),
    },
    {
      title: '状态',
      align: 'center',
      dataIndex: 'couponStatus',
      render: (text: string, record: SplitCouponItemType) => (
        <div>{record.couponStatus ? '领取中' : '已结束'}</div>
      ),
    },
    {
      title: '面额',
      align: 'center',
      dataIndex: 'couponMoney',
      render: (text: string, record: SplitCouponItemType) => (
        <div className='table-self-cell'>
          <div>{record.couponMoney.toLocaleString()}</div>
        </div>
      ),
    },
    {
      title: '门槛',
      align: 'center',
      dataIndex: 'couponType',
      render: (text: string, record: SplitCouponItemType) => (
        <div>{getCouponTypeById(record.couponType)}</div>
      ),
    },
    {
      title: '券类型',
      align: 'center',
      dataIndex: 'useType',
      render: (text: string, record: SplitCouponItemType) => (
        <div>{getCouponUseTypeById(record.useType)}</div>
      ),
    },
    {
      title: '有效期',
      align: 'center',
      width: '15%',
      render: (text: string, record: SplitCouponItemType) => (
        <div>
          <div>起：{record.useStartTime}</div>
          <div>止：{record.useEndTime}</div>
        </div>
      ),
    },
    // {
    //   title: "限领",
    //   align: "center",
    //   dataIndex: "restrictedAccess",
    //   render: (text: string, record: SplitCouponItemType) => (
    //     <div>{record.restrictedAccess}</div>
    //   ),
    // },
    {
      title: '发行量',
      align: 'center',
      dataIndex: 'couponTotal',
      render: (text: string, record: SplitCouponItemType) => <div>{record.couponTotal}</div>,
    },
    {
      title: '已领取',
      align: 'center',
      dataIndex: 'amountReceived',
      render: (text: string, record: SplitCouponItemType) => <div>{record.amountReceived}</div>,
    },
    {
      title: '操作',
      align: 'center',
      render: (text: string, record: SplitCouponItemType, index: number) => (
        <>
          <Button
            type='link'
            onClick={() =>
              toAddOrDetailSplitCoupon(
                record.activityRole === 'share' ? record : tableDataSource[index - 1],
              )
            }
            disabled={!isLookBtn}
          >
            查看
          </Button>
          <Button type='link' onClick={() => showDataModalClick(record)} disabled={!isDataBtn}>
            数据
          </Button>
          <Button
            type='link'
            onClick={() =>
              endSplitCoupon(record.activityRole === 'share' ? record : tableDataSource[index - 1])
            }
            disabled={!record.couponStatus || !isEndBtn}
          >
            结束
          </Button>
        </>
      ),
      // onCell: (record: SplitCouponItemType, rowIndex: any) => ({
      //   rowSpan: rowIndex % 2 ? 0 : 2,
      // }),
    },
  ];
  const [tableDataSource, setTableDataSource] = useState<SplitCouponItemType[]>([]);
  const [queryData, setQueryData] = useState<SplitCouponSearchType>({
    useType: 2,
  });
  const [pagination, setPagination] = useState<PaginationEntity>({
    pageNo: 1,
    pageSize: 10,
    totalCount: 0,
  });
  const [loading, setLoading] = useState<boolean>(false);
  const [splitCouponItem, setSplitCouponItem] = useState<SplitCouponItemType>();
  const [dataModalShow, setDataModalShow] = useState<boolean>(false);
  // 按钮权限
  const isAddBtn = useOperate(26201);
  const isLookBtn = useOperate(26202);
  const isDataBtn = useOperate(26203);
  const isEndBtn = useOperate(26204);

  const searchSubmitEvent = (data: any) => {
    const query = {
      ...data,
      startTime: (data.time && data.time[0]) || undefined,
      endTime: (data.time && data.time[1]) || undefined,
      useType: 2,
      state: data.state === undefined ? '' : !!data.state,
    };
    delete query.time;
    setQueryData(query);
    pagination.pageNo = 1;
    pagination.pageSize = 10;
    getSplitCoupon({
      pageNo: pagination.pageNo,
      pageSize: pagination.pageSize,
      ...query,
    });
  };
  // get split coupon
  const getSplitCoupon = (
    data: SplitCouponSearchType & Pick<PaginationEntity, 'pageSize' | 'pageNo'>,
  ) => {
    // setLoading(true);
    setTableDataSource([
      {
        id: 10000157,
        couponName: '2223',
        couponMoney: 22,
        couponDiscount: null,
        isLimited: true,
        restrictedAccess: null,
        couponTotal: 13,
        lastTotal: 13,
        amountReceived: 0,
        couponType: 3,
        useType: 2,
        minPrice: null,
        primaryKey: '32,31',
        isFixedTime: 0,
        useStartTime: '2023-05-27 00:00:00',
        useEndTime: '2023-06-16 23:59:59',
        couponDay: null,
        getType: 4,
        userTag: null,
        verificationType: false,
        createTime: '2023-05-24 17:47:50',
        updateTime: null,
        couponStatus: true,
        parentId: null,
        peopleNumber: 2,
        activityRole: 'share',
        beSharedCoupon: {
          id: 10000158,
          couponName: '2223',
          couponMoney: 22,
          couponDiscount: null,
          isLimited: true,
          restrictedAccess: 1,
          couponTotal: 12,
          lastTotal: 12,
          amountReceived: 0,
          couponType: 3,
          useType: 2,
          minPrice: null,
          primaryKey: '32',
          isFixedTime: 0,
          useStartTime: '2023-05-27 00:00:00',
          useEndTime: '2023-06-16 23:59:59',
          couponDay: null,
          getType: 4,
          userTag: 1,
          verificationType: false,
          createTime: '2023-05-24 17:47:50',
          updateTime: null,
          couponStatus: true,
          parentId: 10000157,
          peopleNumber: null,
          activityRole: 'beShare',
          beSharedCoupon: null,
        },
      },
      {
        id: 10000153,
        couponName: '列表优惠券测试小嗯嗯',
        couponMoney: 22,
        couponDiscount: null,
        isLimited: true,
        restrictedAccess: null,
        couponTotal: 3,
        lastTotal: 3,
        amountReceived: 0,
        couponType: 3,
        useType: 2,
        minPrice: null,
        primaryKey: '32,26',
        isFixedTime: 0,
        useStartTime: '2023-05-24 00:00:00',
        useEndTime: '2023-06-21 23:59:59',
        couponDay: null,
        getType: 4,
        userTag: null,
        verificationType: false,
        createTime: '2023-05-24 17:00:06',
        updateTime: null,
        couponStatus: false,
        parentId: null,
        peopleNumber: 2,
        activityRole: 'share',
        beSharedCoupon: {
          id: 10000154,
          couponName: '列表优惠券测试小嗯嗯',
          couponMoney: 22,
          couponDiscount: null,
          isLimited: true,
          restrictedAccess: 1,
          couponTotal: 33,
          lastTotal: 33,
          amountReceived: 0,
          couponType: 3,
          useType: 2,
          minPrice: null,
          primaryKey: '32',
          isFixedTime: 0,
          useStartTime: '2023-05-24 00:00:00',
          useEndTime: '2023-06-21 23:59:59',
          couponDay: null,
          getType: 4,
          userTag: 1,
          verificationType: false,
          createTime: '2023-05-24 17:00:06',
          updateTime: null,
          couponStatus: false,
          parentId: 10000153,
          peopleNumber: null,
          activityRole: 'beShare',
          beSharedCoupon: null,
        },
      },
      {
        id: 10000148,
        couponName: '裂变优惠券测试',
        couponMoney: 1000,
        couponDiscount: 9,
        isLimited: true,
        restrictedAccess: null,
        couponTotal: 3,
        lastTotal: 3,
        amountReceived: 0,
        couponType: 1,
        useType: 2,
        minPrice: 4000,
        primaryKey: '31',
        isFixedTime: 0,
        useStartTime: '2023-04-23 00:00:00',
        useEndTime: '2023-04-30 23:59:59',
        couponDay: null,
        getType: 4,
        userTag: null,
        verificationType: false,
        createTime: '2023-04-23 16:10:18',
        updateTime: null,
        couponStatus: false,
        parentId: null,
        peopleNumber: 2,
        activityRole: 'share',
        beSharedCoupon: {
          id: 10000149,
          couponName: '裂变优惠券测试',
          couponMoney: 1000,
          couponDiscount: 9,
          isLimited: true,
          restrictedAccess: 1,
          couponTotal: 9,
          lastTotal: 8,
          amountReceived: 1,
          couponType: 1,
          useType: 2,
          minPrice: 4000,
          primaryKey: '31',
          isFixedTime: 0,
          useStartTime: '2023-04-23 00:00:00',
          useEndTime: '2023-04-30 23:59:59',
          couponDay: null,
          getType: 4,
          userTag: 1,
          verificationType: false,
          createTime: '2023-04-23 16:10:18',
          updateTime: null,
          couponStatus: false,
          parentId: 10000148,
          peopleNumber: null,
          activityRole: 'beShare',
          beSharedCoupon: null,
        },
      },
      {
        id: 10000141,
        couponName: '测试裂变',
        couponMoney: 800,
        couponDiscount: 8,
        isLimited: false,
        restrictedAccess: null,
        couponTotal: 10,
        lastTotal: 11,
        amountReceived: -1,
        couponType: 1,
        useType: 2,
        minPrice: 10000,
        primaryKey: '31',
        isFixedTime: 0,
        useStartTime: '2023-04-19 00:00:00',
        useEndTime: '2023-04-19 23:59:59',
        couponDay: null,
        getType: 4,
        userTag: null,
        verificationType: false,
        createTime: '2023-04-19 13:46:06',
        updateTime: null,
        couponStatus: false,
        parentId: null,
        peopleNumber: 2,
        activityRole: 'share',
        beSharedCoupon: {
          id: 10000142,
          couponName: '测试裂变',
          couponMoney: 500,
          couponDiscount: 9,
          isLimited: true,
          restrictedAccess: 1,
          couponTotal: 100,
          lastTotal: 97,
          amountReceived: 3,
          couponType: 1,
          useType: 2,
          minPrice: 10000,
          primaryKey: '31',
          isFixedTime: 0,
          useStartTime: '2023-04-19 00:00:00',
          useEndTime: '2023-04-19 23:59:59',
          couponDay: null,
          getType: 4,
          userTag: null,
          verificationType: false,
          createTime: '2023-04-19 13:46:06',
          updateTime: null,
          couponStatus: false,
          parentId: 10000141,
          peopleNumber: null,
          activityRole: 'beShare',
          beSharedCoupon: null,
        },
      },
    ]);
    CouponManageAPI.getPageActivityList(data).then(({ result }) => {
      if (result.list) {
        const couponList = result.list.reduce(
          (pre: SplitCouponItemType[], cur: SplitCouponItemType) => {
            pre.push(cur);
            if (cur.beSharedCoupon) {
              pre.push(cur.beSharedCoupon);
            }
            return pre;
          },
          [],
        );
        setLoading(false);
        setTableDataSource(couponList);
        pagination.pageSize = data.pageSize;
        pagination.pageNo = data.pageNo;
        pagination.totalCount = result.totalCount;
        setPagination({ ...pagination });
      }
    });
  };

  // 分页监听
  const paginationChange = (pageNo: number, pageSize: number) => {
    getSplitCoupon({ ...queryData, pageNo, pageSize: pageSize / 2 });
  };

  // 新建
  const toAddOrDetailSplitCoupon = (record?: SplitCouponItemType) => {
    history({
      pathname: '/couponManage/addOrEditOrDetail',
      search: record
        ? qs.stringify({
            id: record.id,
          })
        : '',
    });
  };

  const getCouponTypeById = (id: number) => {
    return splitCouponType.find((v) => v.val === id)?.label || '';
  };
  const getCouponUseTypeById = (id: number) => {
    return splitCouponUseType.find((v) => v.val === id)?.label || '';
  };
  // 裂变优惠券数据
  const dataModalClose = () => {
    setDataModalShow(false);
  };
  const showDataModalClick = (record: SplitCouponItemType) => {
    setSplitCouponItem(record);
    setDataModalShow(true);
  };
  // 结束
  const endSplitCoupon = (record: SplitCouponItemType) => {
    Modal.confirm({
      content: '确认结束后，将停止发放该券，已领的优惠券可继续使用',
      onOk: () => {
        CouponManageAPI.CouponShutDown({ id: record.id }).then(({ code }) => {
          if (code === '200') {
            message.success('操作成功');
            getSplitCoupon({
              ...queryData,
              pageNo: pagination.pageNo,
              pageSize: pagination.pageSize,
            });
          }
        });
      },
    });
  };

  useEffect(() => {
    getSplitCoupon({
      pageNo: pagination.pageNo,
      pageSize: pagination.pageSize,
      useType: 2,
    });
  }, []);

  return (
    <div className='split-coupon-list'>
      <SearchBox
        search={searchData}
        searchData={searchSubmitEvent}
        sufFixBtn={
          <Button
            type='primary'
            icon={<PlusOutlined />}
            onClick={() => toAddOrDetailSplitCoupon()}
            // disabled={!isAddBtn}
          >
            新建
          </Button>
        }
      />
      <Table
        columns={tableColumns}
        rowKey='id'
        dataSource={tableDataSource}
        loading={loading}
        pagination={{
          total: pagination.totalCount * 2,
          pageSize: pagination.pageSize * 2,
          current: pagination.pageNo,
          showSizeChanger: false,
          showQuickJumper: true,
          onChange: (page: number, pageSize: number) => paginationChange(page, pageSize),
          showTotal: (total, range) =>
            `当前 ${Math.ceil(range[0] / 2)}-${range[1] / 2} 条记录 / 共 ${total / 2} 条数据`,
        }}
      />
      {/*  优惠券数据 */}
      <DataModal
        title='裂变优惠券数据'
        open={dataModalShow}
        closed={dataModalClose}
        data={splitCouponItem}
      />
    </div>
  );
};
export default SplitCouponList;
