import React, { useEffect, useState } from "react";
import { Button, message, Modal, Radio, RadioChangeEvent, Table } from "antd";
import { ColumnsType } from "antd/es/table";
import { PlusOutlined } from "@ant-design/icons";
import { useNavigate } from "react-router-dom";
import moment from "moment";
import SearchView from "~/components/search-box/index";
import { CouponManageAPI } from "~/api";
import { TableBox } from "~/components/tableBox";
import { IncreaseModal } from "~/pages/couponManage/couponList/comp/increaseModal";
import { DataModal } from "~/pages/couponManage/couponList/comp/dataModal";
import { CouponPageListType } from "~/api/interface/couponManage";
import useOperate from "~/common/hook/optionHook";

// 列表的类型
type TableType = (ReturnType<CouponPageListType> extends Promise<infer T>
  ? T
  : never)["result"]["list"];
type ReqType = Parameters<CouponPageListType>[0];
// 搜索表单的数据
let query: ReqType = {};
// 规则状态
const stateOptions = [
  // { id: null, name: "全部状态" },
  { id: true, name: "领取中" },
  { id: false, name: "已结束" },
];
// 优惠券类型
const couponType = [
  { label: "打折券", value: 1 },
  { label: "减免券", value: 2 },
  { label: "无门槛", value: 3 },
];

export default function CouponList  () {
  const { confirm } = Modal;
  // 路由操作
  const history = useNavigate();
  const [useType, setUseType] = useState(2);
  // 增发弹窗是否显示
  const [increaseVisible, setIncreaseVisible] = useState(false);
  // 数据弹窗是否显示
  const [dataVisible, setDataVisible] = useState(false);
  // 编辑的数据
  const [recordData, setRecordData] = useState<TableType[0]>();
  // 表格数据
  const [tableData, setTableData] = useState<TableType>([]);
  // 表格分页配置
  const [pagination, setPagination] = useState({
    total: 0,
    pageSize: 10,
    current: 1,
    totalPage: 0,
  });
  // 按钮权限
  const isAddCouponBtn = useOperate(26101);
  const isLookCouponBtn = useOperate(26102);
  const isAddIssueCouponBtn = useOperate(26103);
  const isDataCouponBtn = useOperate(26104);
  const isEndCouponBtn = useOperate(26105);
  // +++++++++++++++++++++++++++++++++++++++++++++++++++ //
  // 新版通用部分(ES6+ for React) ZhangLK 2022/08/30 Start
  // 加载列表
  const getTableList = async (value = {}) => {
    // 只需要修改这个地方的接口即可
    setTableData([
      {
        "id": 10000157,
        "couponName": "2223",
        "couponMoney": 22,
        "couponDiscount": null,
        "isLimited": true,
        "restrictedAccess": null,
        "couponTotal": 13,
        "lastTotal": 13,
        "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,
        "couponStatus": true,
        "isDel": false,
        "preferentialLimit": null,
        "verificationType": false,
        "createTime": "2023-05-24 17:47:50",
        "updateTime": null,
        "fileUrl": null
      },
      {
        "id": 10000158,
        "couponName": "2223",
        "couponMoney": 22,
        "couponDiscount": null,
        "isLimited": true,
        "restrictedAccess": 1,
        "couponTotal": 12,
        "lastTotal": 12,
        "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,
        "couponStatus": true,
        "isDel": false,
        "preferentialLimit": null,
        "verificationType": false,
        "createTime": "2023-05-24 17:47:50",
        "updateTime": null,
        "fileUrl": null
      },
      {
        "id": 10000156,
        "couponName": "人党的飞飞",
        "couponMoney": 12,
        "couponDiscount": null,
        "isLimited": true,
        "restrictedAccess": 3,
        "couponTotal": 12,
        "lastTotal": 0,
        "couponType": 3,
        "useType": 2,
        "minPrice": null,
        "primaryKey": "31",
        "isFixedTime": 0,
        "useStartTime": "2023-05-26 00:00:00",
        "useEndTime": "2023-06-22 23:59:59",
        "couponDay": null,
        "getType": 2,
        "userTag": 1,
        "couponStatus": true,
        "isDel": false,
        "preferentialLimit": null,
        "verificationType": false,
        "createTime": "2023-05-24 17:05:52",
        "updateTime": null,
        "fileUrl": null
      },
      {
        "id": 10000155,
        "couponName": "44444",
        "couponMoney": 44,
        "couponDiscount": null,
        "isLimited": true,
        "restrictedAccess": 3,
        "couponTotal": 44,
        "lastTotal": 44,
        "couponType": 3,
        "useType": 2,
        "minPrice": null,
        "primaryKey": "32,24",
        "isFixedTime": 0,
        "useStartTime": "2023-05-24 00:00:00",
        "useEndTime": "2023-06-19 23:59:59",
        "couponDay": null,
        "getType": 1,
        "userTag": null,
        "couponStatus": true,
        "isDel": false,
        "preferentialLimit": null,
        "verificationType": false,
        "createTime": "2023-05-24 17:01:11",
        "updateTime": null,
        "fileUrl": null
      },
      {
        "id": 10000153,
        "couponName": "列表优惠券测试小嗯嗯",
        "couponMoney": 22,
        "couponDiscount": null,
        "isLimited": true,
        "restrictedAccess": null,
        "couponTotal": 3,
        "lastTotal": 3,
        "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,
        "couponStatus": false,
        "isDel": false,
        "preferentialLimit": null,
        "verificationType": false,
        "createTime": "2023-05-24 17:00:06",
        "updateTime": null,
        "fileUrl": null
      },
      {
        "id": 10000154,
        "couponName": "列表优惠券测试小嗯嗯",
        "couponMoney": 22,
        "couponDiscount": null,
        "isLimited": true,
        "restrictedAccess": 1,
        "couponTotal": 33,
        "lastTotal": 33,
        "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,
        "couponStatus": false,
        "isDel": false,
        "preferentialLimit": null,
        "verificationType": false,
        "createTime": "2023-05-24 17:00:06",
        "updateTime": null,
        "fileUrl": null
      },
      {
        "id": 10000152,
        "couponName": "444",
        "couponMoney": 444,
        "couponDiscount": null,
        "isLimited": true,
        "restrictedAccess": 2,
        "couponTotal": 444,
        "lastTotal": 444,
        "couponType": 3,
        "useType": 2,
        "minPrice": null,
        "primaryKey": "32",
        "isFixedTime": 0,
        "useStartTime": "2023-05-24 00:00:00",
        "useEndTime": "2023-06-22 23:59:59",
        "couponDay": null,
        "getType": 2,
        "userTag": 1,
        "couponStatus": false,
        "isDel": false,
        "preferentialLimit": null,
        "verificationType": false,
        "createTime": "2023-05-24 16:57:44",
        "updateTime": null,
        "fileUrl": null
      },
      {
        "id": 10000151,
        "couponName": "iii",
        "couponMoney": 12,
        "couponDiscount": null,
        "isLimited": true,
        "restrictedAccess": 2,
        "couponTotal": 12,
        "lastTotal": 12,
        "couponType": 3,
        "useType": 2,
        "minPrice": null,
        "primaryKey": "32",
        "isFixedTime": 0,
        "useStartTime": "2023-05-24 00:00:00",
        "useEndTime": "2023-06-20 23:59:59",
        "couponDay": null,
        "getType": 1,
        "userTag": null,
        "couponStatus": false,
        "isDel": false,
        "preferentialLimit": null,
        "verificationType": false,
        "createTime": "2023-05-24 16:53:16",
        "updateTime": null,
        "fileUrl": null
      },
      {
        "id": 10000150,
        "couponName": "333",
        "couponMoney": 33,
        "couponDiscount": null,
        "isLimited": true,
        "restrictedAccess": 2,
        "couponTotal": 33,
        "lastTotal": 33,
        "couponType": 3,
        "useType": 2,
        "minPrice": null,
        "primaryKey": "32,31",
        "isFixedTime": 0,
        "useStartTime": "2023-05-24 00:00:00",
        "useEndTime": "2023-06-20 23:59:59",
        "couponDay": null,
        "getType": 2,
        "userTag": 1,
        "couponStatus": false,
        "isDel": false,
        "preferentialLimit": null,
        "verificationType": false,
        "createTime": "2023-05-24 16:46:32",
        "updateTime": null,
        "fileUrl": null
      },
      {
        "id": 10000148,
        "couponName": "裂变优惠券测试",
        "couponMoney": 1000,
        "couponDiscount": 9,
        "isLimited": true,
        "restrictedAccess": null,
        "couponTotal": 3,
        "lastTotal": 3,
        "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,
        "couponStatus": false,
        "isDel": false,
        "preferentialLimit": null,
        "verificationType": false,
        "createTime": "2023-04-23 16:10:18",
        "updateTime": null,
        "fileUrl": null
      }
    ])
    const res = await CouponManageAPI.CouponPageList({
      useType,
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
      ...value,
      ...query,
    });
    if (res && res.code === "200") {
      const { list, pageNo, totalCount, pageSize, totalPage } = res.result; // 解构
      // console.log("getTableList --->", list);
      setPagination({
        total: totalCount,
        current: pageNo,
        pageSize,
        totalPage,
      });
      setTableData(list);
    } else {
      message.warning(res.message);
      // 递归遍历一个数组
    }
  };
  // 翻页
  const paginationChange = (pageNo: number, pageSize: number) => {
    getTableList({ pageNo, pageSize }).then();
  };
  // 表单提交
  const onFinish = (data: any) => {
    const obj = {
      ...data,
      startTime: data.effectTime && data.effectTime[0],
      endTime: data.effectTime && data.effectTime[1],
    };
    // console.log(data.effectTime);
    pagination.current = 1;
    query = obj;
    getTableList(obj).then();
  };
  // +++++++++++++++++++++++++++++++++++++++++++++++++++ //
  // 切换表格的数据
  const handleChange = async ({ target: { value } }: RadioChangeEvent) => {
    setUseType(value);
    setPagination({
      total: 0,
      pageSize: 10,
      current: 1,
      totalPage: 0,
    });
    await getTableList();
  };
  // 结束优惠券
  const handleEnd = (record: TableType[0]) => {
    confirm({
      title: "提示",
      content: "确认结束后，将停止发放该券，已领的优惠券可继续使用",
      onOk: async () => {
        const res = await CouponManageAPI.CouponShutDown({
          id: record.id,
        });
        if (res && res.code === "200") {
          message.success("操作成功").then();
          paginationChange(pagination.current, pagination.pageSize);
        }
        // console.log("删除成功 --->", record);
      },
    });
  };
  // 一键关闭全部弹窗
  const handleCloseAll = () => {
    setIncreaseVisible(false);
    setDataVisible(false);
    setRecordData(undefined);
    // 刷新当前页面
    paginationChange(pagination.current, pagination.pageSize);
  };
  // 查看详情
  const handleAdd = (record?: TableType[0]) => {
    if (record?.id) {
      history({
        pathname: "/couponManage/couponList/detail",
        search: `id=${record?.id}&type=${useType}`,
      })
      // history.push({
      //   pathname: "/couponManage/couponList/detail",
      //   search: `id=${record?.id}&type=${useType}`,
      // });
    } else {
      history({
        pathname: "/couponManage/couponList/detail",
        search: `type=${useType}`,
      });
      // history.push({
      //   pathname: "/couponManage/couponList/detail",
      //   search: `type=${useType}`,
      // });
    }
    // console.log("handleAdd -->", type, record);
  };
  // 表格结构
  const columns: ColumnsType<TableType[0]> = [
    {
      title: "优惠券ID",
      dataIndex: "id",
      align: "center",
    },
    {
      title: "优惠券名称",
      dataIndex: "couponName",
      align: "center",
    },
    {
      title: "满减规则",
      align: "center",
      render: (value, record) => {
        if (record.couponType === 1)
          return `${record.couponDiscount}折${
            couponType.find((i) => i.value === record.couponType)?.label
          }`;
        if (record.couponType === 2)
          return `满${record.minPrice}元减${record.couponMoney}元`;
        if (record.couponType === 3)
          return `${record.couponMoney}元${
            couponType.find((i) => i.value === record.couponType)?.label
          }`;
      },
    },
    {
      title: "有效期",
      align: "center",
      width: 280,
      render: (value, record) => {
        if (record.isFixedTime === 0)
          return `${record.useStartTime} 至 ${record.useEndTime}`;
        if (record.isFixedTime === 1)
          return `领取成功后${record.couponDay}天内可用`;
        if (record.isFixedTime === 2)
          return `领取成功后次日${record.couponDay}天内可用`;
      },
    },
    {
      title: "状态",
      align: "center",
      render: (value, record) => {
        if (!record.couponStatus) return "已结束";
        if (record.couponDay) return "领取中";
        // const after = moment(record.useStartTime).isAfter(moment());
        const before = moment(record.useEndTime).isBefore(moment());
        // if (after) return "未开始";
        if (before) return "已过期";
        return "领取中";
      },
    },
    {
      title: "限领",
      dataIndex: "restrictedAccess",
      align: "center",
    },
    {
      title: "剩余/发行量",
      dataIndex: "proportion",
      align: "center",
      render: (value, record, index) =>
        record.isLimited
          ? `${record.lastTotal}/${record.couponTotal}`
          : "不限量",
    },
    // {
    //   title: "使用量",
    //   dataIndex: "proportion",
    //   align: "center",
    //   render: (value, record, index) =>
    //     record.isLimited
    //       ? Math.floor(record.couponTotal - record.lastTotal)
    //       : "不限量",
    // },
    {
      title: "创建时间",
      dataIndex: "createTime",
      align: "center",
    },
    {
      title: "操作",
      align: "center",
      fixed: "right",
      width: "180px",
      render: (value, record, index) => {
        const disabled =
          moment(record.useEndTime).isBefore(moment()) ||
          record.isDel ||
          !record.couponStatus;
        return (
          <div className="table-body-action">
            <Button
              type="link"
              onClick={() => handleAdd(record)}
              disabled={!isLookCouponBtn}
            >
              查看
            </Button>
            <Button
              type="link"
              onClick={() => {
                setRecordData(JSON.parse(JSON.stringify(record)));
                setIncreaseVisible(true);
              }}
              disabled={disabled || !isAddIssueCouponBtn || !record.isLimited}
            >
              增发
            </Button>
            <Button
              type="link"
              onClick={() => {
                setRecordData(JSON.parse(JSON.stringify(record)));
                setDataVisible(true);
              }}
              disabled={!isDataCouponBtn}
            >
              数据
            </Button>
            <Button
              type="link"
              onClick={() => handleEnd(record)}
              disabled={disabled || !isEndCouponBtn}
            >
              结束
            </Button>
          </div>
        );
      },
    },
  ];
  useEffect(() => {
    query = {};
    (async () => {
      await getTableList();
    })();
  }, []);
  return (
    <>
      <SearchView
        search={[
          {
            label: "规则状态",
            name: "state",
            type: "select",
            placeholder: "请选择规则状态",
            options: stateOptions,
          },
          {
            label: "生效时间",
            name: "effectTime",
            type: "rangePicker",
            placeholder: "请选择生效时间",
          },
          {
            label: "优惠券ID",
            name: "couponId",
            type: "input",
            placeholder: "请输入优惠券ID",
          },
          {
            label: "优惠券名称",
            name: "couponName",
            type: "input",
            placeholder: "请输入优惠券名称",
          },
        ]}
        searchData={onFinish}
        sufFixBtn={
          <>
            <Button
              icon={<PlusOutlined />}
              type="primary"
              onClick={() => {
                handleAdd();
              }}
              // disabled={!isAddCouponBtn}
            >
              创建品牌券
            </Button>
            <Button icon={<PlusOutlined />} type="primary" disabled>
              创建商品券
            </Button>
            <Button icon={<PlusOutlined />} type="primary" disabled>
              创建店铺券
            </Button>
          </>
        }
      />
      <TableBox>
        <Radio.Group
          onChange={handleChange}
          value={useType}
          options={[
            // { label: "VIP券", value: 1 },
            { label: "品牌优惠券", value: 2 },
            { label: "商品优惠券", value: 3, disabled: true },
            { label: "店铺优惠券", value: 4, disabled: true },
            { label: "数据概览", value: 5, disabled: true },
          ]}
          optionType="button"
          style={{ marginBottom: "10px" }}
        />
        <Table
          size="small"
          dataSource={tableData}
          columns={columns}
          rowKey="id"
          scroll={{ x: 1500 }}
          bordered
          pagination={{
            total: pagination.total,
            pageSize: pagination.pageSize,
            current: pagination.current,
            showSizeChanger: true,
            showQuickJumper: true,
            onChange: (page: number, pageSize: number) =>
              paginationChange(page, pageSize),
            showTotal: (total, range) =>
              `当前 ${range[0]}-${range[1]} 条记录 / 共 ${total} 条数据`,
          }}
        />
      </TableBox>
      <IncreaseModal
        open={increaseVisible}
        title="增发优惠券"
        data={recordData}
        closed={handleCloseAll}
      />
      <DataModal
        open={dataVisible}
        title="优惠券使用数据"
        data={recordData}
        closed={handleCloseAll}
      />
    </>
  );
};
