import React, { useState, useRef, useEffect } from 'react';
import moment from 'moment';
import ProTable, { TableDropdown } from '@ant-design/pro-table';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import { Tooltip, Button, message, Drawer, Popconfirm,Modal } from 'antd';
import CreateForm from './components/CreateForm';
import RecordForm from './components/RecordForm';
 import QRCode from 'qrcode.react';
import {
  GetCouponList,
  Addcoupon,
  DeleteCoupon,
  UpdateCoupon,
  abolishCoupon,
  GetCouponStatusOrType,
  AddCouponSendRecord,
  UpdateCouponStatus,
} from './service';

const Coupon = () => {
  //绑定
  const actionRef = useRef();
  const [selectedRowsState, setSelectedRows] = useState([]);
  /** 新建/更新窗口的弹窗 */
  const [createModalVisible, handleModalVisible] = useState(false);
  /** 发放记录窗体 */
  const [recrodModalVisible, showModalVisible] = useState(false);
  //记录分页列表
  const [currentRow, setCurrentRow] = useState();
  const key = 'coupon';
  // //获取店铺上级分组信息
  const [couponType, setcouponType] = useState({});

  //初始化数据
  useEffect(() => {



    
    const initcouponType = async (value) => {
      await GetCouponStatusOrType(2).then((r) => {
        let data = {};
        if (r.succeeded) {
          r.data.forEach((item) => {
            data[item.key] = { text: item.value };
          });
        }
        setcouponType(data);
      });
    };
    initcouponType();
  }, []);

  //新增
  const handleAdd = async (fields) => {
    message.loading('正在添加...', key);
    try {
      if (fields.validEndTime < fields.validStartTime) {
        message.error('开始时间不能大于结束时间');
        return false;
      }
      await Addcoupon(JSON.stringify(fields)).then((r) => {
        message.destroy(key);
        if (r.data) {
          message.success('添加成功');
        } else {
          message.error('添加失败请重试！');
        }
      });
      //刷新数据
      actionRef.current.reload();
      return true;
    } catch (error) {
      message.destroy(key);
      message.error('添加失败请重试！');
      return false;
    }
  };

  //删除（支持批量删除）
  const handleRemove = async (value) => {
    message.loading('正在删除...', key);
    try {
      let ids = [];
      value.forEach((item) => {
        ids.push(item.id);
      });
      await DeleteCoupon(JSON.stringify(ids)).then((r) => {
        message.destroy(key);
        if (r.data) {
          message.destroy(key);
          message.success('删除成功');
        } else {
          message.error('删除失败请重试！');
        }
      });
      //刷新数据
      actionRef.current.reload();
      return true;
    } catch (error) {
      message.destroy(key);
      message.error('删除失败请重试！');
      return false;
    }
  };

  //修改
  const handleUpdate = async (fields) => {
    message.loading('正在修改...', key);
    try {
      if (fields.validEndTime < fields.validStartTime) {
        message.error('开始时间不能大于结束时间');
        return false;
      }
      await UpdateCoupon(JSON.stringify(fields)).then((r) => {
        message.destroy(key);
        if (r.data) {
          message.success('修改成功');
        } else {
          message.error(JSON.sstringify(r.errors));
        }
      });
      //刷新数据
      actionRef.current.reload();
      return true;
    } catch (error) {
      message.destroy(key);
      message.error('修改失败请重试！');
      return false;
    }
  };

  //作废
  const handleAbolish = async (field) => {
    message.loading('正在作废...', key);
    try {
      await abolishCoupon(field.id).then((r) => {
        message.destroy(key);
        if (r.data) {
          message.success('作废成功');
        } else {
          message.error('作废失败请重试！');
        }
      });
      //刷新数据
      actionRef.current.reload();
      return true;
    } catch (error) {
      message.destroy(key);
      message.error('作废失败请重试！');
      return false;
    }
  };

  //新增发放记录
  const AddRecord = async (params) => {
    message.loading('正在添加...', key);
    try {
      params.RangeType=1;
      await AddCouponSendRecord(JSON.stringify(params)).then((r) => {
        if (r.data) {
          message.destroy(key);
          message.success('添加成功');
        }
      });
      return true;
    } catch (error) {
      message.destroy(key);
      message.error('添加失败请重试！');
      return false;
    }
  };

  //停用启用优惠券
  const UpdateStatus = async (params) => {
    message.loading('正在修改...', key);
    try {
      if (params.validStatus == 1) {
        params.validStatus = 4;
      } else if (params.validStatus == 4) {
        params.validStatus = 1;
      } else {
        return false;
      }

      await UpdateCouponStatus(JSON.stringify(params)).then((r) => {
        if (r.data) {
          message.destroy(key);
          message.success('修改成功');
        }
      });
      return true;
    } catch (error) {
      message.destroy(key);
      message.error('修改失败请重试！');
      return false;
    }
  };

  //table的展示列
  const columns = [
    {
      title: '主键',
      dataIndex: 'id',
      tip: '规则名称是唯一的 key',
      hideInSearch: true,
      hideInTable: true,
    },
    {
      title: '标题',
      dataIndex: 'couponTitle',
      valueType: 'textarea',
    },
    {
      title: '优惠卷类型',
      width: 90,
      dataIndex: 'couponType',
      key: 'couponType',
      valueEnum: couponType,
    },
    {
      title: '优惠金额',
      dataIndex: 'couponValue',
      width: 80,
      valueType: 'money',
    },
    {
      title: '满减金额',
      dataIndex: 'condition',
      width: 80,
      valueType: 'money',
    },
    {
      title: '每人可领数量',
      dataIndex: 'getLimit',
      width: 70,
      render: (text, record, index) => {
        return <span>{record.getLimit != 0 ? record.getLimit : '无限制'}</span>;
      },
    },
    {
      title: '发送总量',
      width: 80,
      dataIndex: 'sendNum',
      valueType: 'textarea',
      search: false,
    },
    {
      title: '领取数量',
      width: 80,
      dataIndex: 'getNum',
      valueType: 'digit',
      search: false,
    },
    {
      title: '剩余数量',
      width: 80,
      dataIndex: 'getNum',
      search: false,
      render: (text, record, index) => {
        return (
          <span>
            <a>{record.sendNum - record.getNum}</a>
          </span>
        );
      },
    },

    {
      title: '时间类型',
      width: 80,
      dataIndex: 'timeType',
      valueEnum: {
        1: { text: '时间段' },
        2: { text: '固定时间' },
      },
    },
    // {
    //   title: '固定时间值',
    //   dataIndex: 'validFixedTerm',
    //   valueType: 'digit',
    // },
    // {
    //   title: '开始时间',
    //   dataIndex: 'validStartTime',
    //   valueType: 'date',
    // },
    // {
    //   title: '结束时间',
    //   dataIndex: 'validEndTime',
    //   valueType: 'date',
    // },
    {
      title: '有效时间',
      key: 'dateRange',
      width: 160,
      valueType: 'dateRange',
      render: (text, record, index) => {
        if (record.timeType == 1) {
          return (
            <span>
              <div>{moment(record.validStartTime).format('YYYY-MM-DD')}</div>
              <div>{moment(record.validEndTime).format('YYYY-MM-DD')}</div>
            </span>
          );
        } else {
          return (
            <span>
              自领取后 <a>{record.validFixedTerm}天</a> 内有效
            </span>
          );
        }
      },
    },
    {
      title: '固定时间',
      width: 80,
      dataIndex: 'validFixedTerm',
      valueType: 'digit',
      hideInTable: true,
    },
    {
      title: '状态',
      width: 70,
      key: 'validStatus',
      dataIndex: 'validStatus',
      valueEnum: {
        1: { text: '生效', status: 'Processing' },
        2: { text: '失效', status: 'Success' },
        3: { text: '作废', status: 'Error' },
        4: { text: '停用', status: 'Error' },
      },
    },
    {
      title: '备注',
      search: false,
      dataIndex: 'remarks',
      render: (text, record, index) => {
        console.log('我是remarks', record.remarks);
        return (
          <Tooltip placement="top" title={record.remarks}>
            <span>{record.remarks?.substring(0, 10)}</span>
          </Tooltip>
        );
      },
    },
    {
      title: '创建时间',
      width: 90,
      dataIndex: 'createAt',
      valueType: 'date',
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        const state = form.getFieldValue('state');

        if (`${state}` === '0') {
          return false;
        }

        if (`${state}` === '3') {
          return <Input {...rest} placeholder="请输入异常原因！" />;
        }

        return defaultRender(item);
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      width: 250,
      valueType: 'option',
      render: (_, record) => {
        let template = [
          <a
            key="primary"
            type="primary"
            disabled={!record.isAllowUpdate}
            style={{ pointerEvents: record.isAllowUpdate == false ? 'none' : 'auto' }}
            onClick={() => {
              if (!record.isAllowUpdate) return;
              handleModalVisible(true);
              setCurrentRow(() => {
                record.validStartTime = moment(record.validStartTime);
                record.validEndTime = moment(record.validEndTime);
                return record;
              });
            }}
          >
            更新
          </a>,
          <Popconfirm
            type="primary"
            key="primary"
            title="确认作废吗？"
            okText="是"
            cancelText="否"
            onConfirm={() => {
              handleAbolish(record);
              actionRef.current.reload();
            }}
            onCancel={() => {}}
          >
            <a
              href="#"
              disabled={record.validStatus == 3}
              style={{ pointerEvents: record.validStatus == 3 ? 'none' : 'auto' }}
            >
              作废
            </a>
          </Popconfirm>,
           <a
           key="primary"
           onClick={() => {
             const config = {
               title: '二维码',
               content: (
                 <QRCode
                   id="qrCode"
                   value={`https://black-pa.com:5443/lead?couponId=${record.id}`}
                   size={200} // 二维码的大小
                   fgColor="#000000" // 二维码的颜色
                   style={{ margin: 'auto' }}
                 />
               ),
             };
             Modal.info(config);
 
           }}
         >
           {' '}
           二维码
         </a>
        ];
        if (record.isAllowUpdate == 1) {
          template.push(
            <Popconfirm
              type="primary"
              key="primary"
              title="确认删除吗？"
              okText="是"
              cancelText="否"
              onConfirm={() => {
                handleRemove([record]);
              }}
              onCancel={() => {}}
            >
              <a href="#">删除</a>
            </Popconfirm>,
          );
        } else {
          template.push(
            <a
              disabled={record.validStatus == 3}
              style={{ pointerEvents: record.validStatus == 3 ? 'none' : 'auto' }}
              key="primary"
              type="primary"
              onClick={() => {
                UpdateStatus(record);
                actionRef.current.reload();
              }}
            >
              {record.validStatus == 1 ? '停用' : '启用'}
            </a>,
          );
        }
        if (record.validStatus == 1) {
          template.push(
            <a
              key="primary"
              type="primary"
              onClick={() => {
                showModalVisible(true);
                setCurrentRow(record);
              }}
            >
              发放
            </a>,
          );
        }
        return template;
      },
    },
  ];
  return (
    <PageContainer>
      <ProTable
        headerTitle="优惠卷"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        pagination={{
          pageSize: 10,
        }}
        toolBarRender={() => [
          <Button
            key="primary"
            type="primary"
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            新建
          </Button>,
        ]}
        columns={columns}
        //数据绑定
        request={async (params) => {
          var queryData = [];
          var total = 0;
          if (params.dateRange != undefined && params.dateRange.length >= 2) {
            params.validStartTime = params.dateRange[0];
            params.validEndTime = params.dateRange[1];
          }
          await GetCouponList(params).then((r) => {
            queryData = r.data.data;
            total = r.data.total;
          });
          return {
            data: queryData,
            success: true,
            total: total,
          };
        }}
        //选择行
        // rowSelection={{
        //   onChange: (_, selectedRows) => {
        //     setSelectedRows(selectedRows);
        //   },
        // }}
      ></ProTable>
      {/* 批量删除 */}
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              {' '}
              已选择 <a style={{ fontWeight: 600 }}>{selectedRowsState.length} </a> 项 &nbsp;&nbsp;{' '}
            </div>
          }
        >
          {/* <Button
            onClick={() => {
              handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
            type="primary"
            key="primary"
          >
            批量删除
          </Button> */}
        </FooterToolbar>
      )}

      <CreateForm
        onFinish={async (value) => {
          var success = false;
          if (value.id) {
            success = await handleUpdate(value);
          } else {
            success = await handleAdd(value);
          }
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          setCurrentRow(undefined);
          handleModalVisible(false);
        }}
        createModalVisible={createModalVisible}
        values={currentRow || {}}
      />

      <RecordForm
        onFinish={async (value) => {
          value.Coupon_Id = currentRow.id;
          var success = await AddRecord(value);
          if (success) {
            showModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          setCurrentRow(undefined);
          showModalVisible(false);
        }}
        createModalVisible={recrodModalVisible}
        values={currentRow || {}}
      />
    </PageContainer>
  );
};

export default Coupon;
