import { FC, useEffect, useRef, useState } from "react";
import { Button, Image, message, Modal, Table } from "antd";
import { ColumnsType } from "antd/es/table";
import dayjs from "dayjs";
import Box from "~/components/box";
import AddOrEditModal from "./components/addOrEditModal";
import ActivityDataModal from "./components/activityDataModal";
import { ActivityManageAPI } from "~/api/modules/activityManage";
import { SplitCouponItemType } from "~/api/interface/couponManage";
import { PaginationEntity } from "~/common/interface/PaginationEntity";
import {
  activityDataType,
  activityItemType,
} from "~/api/interface/activityManage";
import useOperate from "~/common/hook/optionHook";

// 活动数据-类型
type dataType = (ReturnType<activityDataType> extends Promise<infer T>
  ? T
  : never)["result"];
const ActivityList: FC<{}> = () => {
  const activityRef = useRef();

  const tableColumns: ColumnsType<activityItemType> = [
    {
      title: "ID",
      align: "center",
      dataIndex: "id",
    },
    {
      title: "活动标题",
      align: "center",
      dataIndex: "activityName",
    },
    {
      title: "活动类型",
      align: "center",
      dataIndex: "activityType",
      render: (text: string, record: activityItemType) => (
        <div>{record.activityType === 1 ? "裂变活动" : "普通活动"}</div>
      ),
    },
    {
      title: "是否展示",
      align: "center",
      render: (text: number, record: activityItemType) => (
        <div>{record.show ? "展示" : "隐藏"}</div>
      ),
    },
    {
      title: "推广简图",
      align: "center",
      render: (text: string, record: activityItemType) => (
        <Image src={record.activityImg} width={50} />
      ),
    },
    {
      title: "关联优惠",
      align: "center",
      dataIndex: "bindingCouponName",
    },
    {
      title: "参与次数",
      align: "center",
      dataIndex: "limitNum",
    },
    {
      title: "状态",
      align: "center",
      render: (text: string, record: activityItemType) =>
        record.activityStatus === 1 ? "进行中" : "已下线",
    },
    {
      title: "有效期",
      align: "center",
      render: (text: string, record: activityItemType) => (
        <div>
          <div>起：{record.startTime}</div>
          <div>止：{record.endTime}</div>
        </div>
      ),
    },
    {
      title: "操作",
      align: "center",
      render: (text: string, record: activityItemType, index: number) => (
        <>
          <Button
            type="link"
            onClick={() => endActivityClick(record)}
            disabled={record.activityStatus !== 1 || !isEndBtnShow}
          >
            结束
          </Button>
          {/* <Button type="link" onClick={() => addOrEditActivity(record)}> */}
          {/*  编辑 */}
          {/* </Button> */}
          <Button
            type="link"
            onClick={() => showActivityData(record)}
            disabled={!isDataBtnShow}
          >
            数据
          </Button>
        </>
      ),
    },
  ];
  const [tableData, setTableData] = useState<activityItemType[]>([]);
  const [pagination, setPagination] = useState<PaginationEntity>({
    pageNo: 1,
    pageSize: 10,
    totalCount: 0,
  });
  const [loading, setLoading] = useState<boolean>(false);
  // 活动数据
  const [activityData, setActivityData] = useState<dataType>();
  const [addOrEditModalShow, setAddOrEditModalShow] = useState<boolean>(false);
  const [addOrEditModalTitle, setAddOrEditModalTitle] = useState("创建活动");
  const [activityDataModalShow, setActivityDataModalShow] =
    useState<boolean>(false);
  const [couponData, setCouponData] = useState<SplitCouponItemType[]>([]);
  // 按钮权限
  const isEndBtnShow = useOperate(19150);
  const isDataBtnShow = useOperate(19200);

  // 活动列表
  const getActivityList = (
    data: Pick<PaginationEntity, "pageNo" | "pageSize">
  ) => {
    // setLoading(true);
    const list:any =[
      {
        "id": 4,
        "activityName": "裂变活动测试",
        "activityCode": "AC77674",
        "activityImg": "https://pad-video-x.oss-cn-shenzhen.aliyuncs.com/file/87681f78-67db-4603-aaf3-4bdbdb4546d2.jpg",
        "bindingCouponId": 10000148,
        "bindingCouponName": "裂变优惠券测试",
        "activityStatus": 2,
        "activityType": 1,
        "shareNum": 2,
        "startTime": "2023-04-23 00:00:00",
        "endTime": "2023-04-30 23:59:59",
        "limitNum": 1,
        "deleted": null,
        "show": 1,
        "redirectPath": null,
        "couponActivityDTO": null,
        "couponDTO": null
      },
      {
        "id": 3,
        "activityName": "裂变活动测试",
        "activityCode": "AC55159",
        "activityImg": "https://pad-video-x.oss-cn-shenzhen.aliyuncs.com/file/6e4f318f-3081-43b7-ad6a-79afabd9ddb9.jpg",
        "bindingCouponId": 10000141,
        "bindingCouponName": "测试裂变",
        "activityStatus": 2,
        "activityType": 1,
        "shareNum": 2,
        "startTime": "2023-04-23 00:00:00",
        "endTime": "2023-04-30 23:59:59",
        "limitNum": 1,
        "deleted": null,
        "show": 1,
        "redirectPath": null,
        "couponActivityDTO": null,
        "couponDTO": null
      },
      {
        "id": 2,
        "activityName": "认证裂变",
        "activityCode": "AC17946",
        "activityImg": "https://pad-video-x.oss-cn-shenzhen.aliyuncs.com/file/b22e0f43-fd04-4147-adc6-73d96b76c740.png",
        "bindingCouponId": null,
        "bindingCouponName": null,
        "activityStatus": 2,
        "activityType": 1,
        "shareNum": null,
        "startTime": "2023-04-19 00:00:00",
        "endTime": "2023-12-31 23:59:59",
        "limitNum": 1,
        "deleted": null,
        "show": 1,
        "redirectPath": null,
        "couponActivityDTO": null,
        "couponDTO": null
      },
      {
        "id": 1,
        "activityName": "测试裂变",
        "activityCode": "AC01841",
        "activityImg": "https://pad-video-x.oss-cn-shenzhen.aliyuncs.com/file/40f09893-01c5-4cc6-a64a-75dac1963791.jpg",
        "bindingCouponId": 10000141,
        "bindingCouponName": "测试裂变",
        "activityStatus": 2,
        "activityType": 1,
        "shareNum": 2,
        "startTime": "2023-04-19 00:00:00",
        "endTime": "2023-04-19 23:59:59",
        "limitNum": 1,
        "deleted": null,
        "show": 1,
        "redirectPath": null,
        "couponActivityDTO": null,
        "couponDTO": null
      }
    ]
    setTableData(list)
    ActivityManageAPI.getActivityList(data).then(({ result }) => {
      setLoading(false);

      setTableData(result.list || []);
      setPagination({
        pageNo: data.pageNo,
        pageSize: data.pageSize,
        totalCount: result.totalCount,
      });
    });
  };
  // 裂变优惠券数据
  const getActivityCouponPullDown = (type: number) => {
    ActivityManageAPI.getActivityCouponPullDown({ type }).then(({ result }) => {
      setCouponData(result || []);
    });
  };
  // 活动结束
  const endActivityClick = (record: activityItemType) => {
    Modal.confirm({
      content: "即将停止该活动，关联优惠券会停止发放",
      onOk: () => {
        ActivityManageAPI.endActivity({ activityId: record.id }).then(
          ({ code }) => {
            if (code === "200") {
              message.success("操作成功，该活动已结束");
              getActivityList({
                pageNo: pagination.pageNo,
                pageSize: pagination.pageSize,
              });
            }
          }
        );
      },
    });
  };

  // 新增,编辑弹窗
  const addOrEditActivity = (record?: activityItemType) => {
    setAddOrEditModalTitle(record ? "编辑活动" : "创建活动");
    if (record) {
      const activityForm = (activityRef.current as any)?.getForm();
      activityForm.setFieldsValue({
        activityName: record.activityName,
        activityType: record.activityType,
        show: record.show,
        activityImg: record.activityImg,
        bindingCouponId: record.bindingCouponId || undefined,
        redirectPath: record?.redirectPath,
        limitNum: record.limitNum,
        time: [dayjs(record.startTime), dayjs(record.endTime)],
      });
      const setFileList = (activityRef.current as any)?.setFileList;
      setFileList([
        {
          uid: "uid",
          name: "image",
          url: record.activityImg,
          status: "done",
        },
      ]);
    }
    const setId = (activityRef.current as any)?.setId;
    setId(record ? record.id : -1);
    setAddOrEditModalShow(true);
  };
  const addOrEditModalOk = () => {
    setAddOrEditModalShow(false);
    getActivityList({
      pageNo: pagination.pageNo,
      pageSize: pagination.pageSize,
    });
  };
  const addOrEditModalCancel = () => {
    setAddOrEditModalShow(false);
  };
  // 活动数据弹窗
  const showActivityData = (record: activityItemType) => {
    ActivityManageAPI.getActivityData({ activityId: record.id }).then(
      ({ result }) => {
        setActivityData(result || undefined);
      }
    );
    setActivityDataModalShow(true);
  };
  const activityDataModalCancel = () => {
    setActivityDataModalShow(false);
  };
  // 活动类型选择
  const activityTypeChangeEvent = (value: number) => {
    getActivityCouponPullDown(value);
  };
  // 分页
  const paginationChange = (pageNo: number, pageSize: number) => {
    getActivityList({ pageNo, pageSize });
  };
  useEffect(() => {
    getActivityCouponPullDown(1);
    getActivityList({ pageNo: 1, pageSize: 10 });
  }, []);
  return (
    <div className="activity-list">
      <Box>
        <Button type="primary" onClick={() => addOrEditActivity()}>
          新增
        </Button>
      </Box>
      <Table
        columns={tableColumns}
        bordered
        rowKey="id"
        dataSource={tableData}
        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} 条数据`,
        }}
        loading={loading}
      />
      {/* 新增,编辑 */}
      <AddOrEditModal
        isModalVisible={addOrEditModalShow}
        handleOk={addOrEditModalOk}
        handleCancel={addOrEditModalCancel}
        couponData={couponData}
        activityTypeChangeEvent={activityTypeChangeEvent}
        ref={activityRef}
        title={addOrEditModalTitle}
      />
      {/* 活动数据 */}
      <ActivityDataModal
        isModalVisible={activityDataModalShow}
        handleCancel={activityDataModalCancel}
        activityData={activityData}
      />
    </div>
  );
};
export default ActivityList;
