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 { Select, Button, message, Drawer, Popconfirm,Modal } from 'antd';
import CreateForm from './components/CreateForm';
import {
  GetPaperCouponList,
  AddPaperCoupon,
  DeletePaperCoupon,
  UpdatePaperCoupon,
  GetPaperCouponType,
  AddPaperCouponType
} from './service';

const Coupon = () => {
  //绑定
  const actionRef = useRef();
  const [selectedRowsState, setSelectedRows] = useState([]);
  /** 新建/更新窗口的弹窗 */
  const [createModalVisible, handleModalVisible] = useState(false);
  //记录分页列表
  const [currentRow, setCurrentRow] = useState();
  const key = 'coupon';
  const [optyid, setOptyid] = useState();
  const [items, setItems] = useState();
  //初始化数据
  useEffect(() => {
    initcouponType()
  }, []);
  const initcouponType = async () => {
    var data = await GetPaperCouponType();
    var op=[]
    data.data.map((item) => (
      op.push({label:item.value,value:item.key})
    ));
    setItems(op)
  };
  //新增
  const handleAdd = async (fields) => {
    message.loading('正在添加...', key);
    try {
      if (fields.validEndTime < fields.validStartTime) {
        message.error('开始时间不能大于结束时间');
        return false;
      }
      await AddPaperCoupon(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 {
      await DeletePaperCoupon(JSON.stringify(value)).then((r) => {
        console.log(r)
        message.destroy(key);
        if (r.data) {
          message.destroy(key);
          message.success('执行成功');
        } else {
          message.error(r.errors);
        }
      });
      //刷新数据
      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 UpdatePaperCoupon(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 onchangevalue=(value)=>{
    console.log(value)
    setOptyid(value)
  }
  //table的展示列
  const columns = [
    {
      title: '主键',
      dataIndex: 'id',
      tip: '规则名称是唯一的 key',
      hideInSearch: true,
      hideInTable: true,
    },
    {
      title: '标题',
      dataIndex: 'title',
      valueType: 'textarea',
    },
    {
      title: '优惠卷类型',
      width: 90,
      dataIndex: 'cTypeName',
      key: 'cTypeName',
      renderFormItem: () => (
        <Select options={items} onChange={onchangevalue} allowClear={true}/>
      ),
    },
    {
      title: '优惠金额',
      dataIndex: 'money',
      width: 80,
      valueType: 'money',
    },
    {
      title: '平台金额',
      dataIndex: 'soureMoney',
      width: 80,
      valueType: 'soureMoney',
    },
    {
      title: '创建时间',
      width: 90,
      dataIndex: 'crateTimeAt',
      valueType: 'date',
      hideInSearch: false,
    },
    {
      title: '操作',
      dataIndex: 'option',
      width: 250,
      valueType: 'option',
      render: (_, record) => {
        let template = [
          <a
            key="primary"
            type="primary"
          
            onClick={() => {
              handleModalVisible(true);
              setCurrentRow(() => {
                // record.validStartTime = moment(record.validStartTime);
                // record.validEndTime = moment(record.validEndTime);
                return record;
              });
            }}
          >
            更新
          </a>,
        ];
        template.push(
          <a  key="primary"
        type="primary" onClick={() => {
          handleRemove(record.id);
        }}>{record.enable?"禁用":"启用"}</a>
        
      );
        return template;
      },
    },
  ];
  return (
    <PageContainer>
      <ProTable
        headerTitle="优惠卷"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        pagination={{
          pageSize: 10,
        }}
        onReset={()=>{
          setOptyid("")
        }}
        toolBarRender={() => [
          <Button
            key="primary"
            type="primary"
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            新建
          </Button>,
        ]}
        columns={columns}
        //数据绑定
        request={async (params,e) => {
          var queryData = [];
          var total = 0;
          if (params.dateRange != undefined && params.dateRange.length >= 2) {
            params.validStartTime = params.dateRange[0];
            params.validEndTime = params.dateRange[1];
          }
          params.CTypeId=optyid;
          console.log(e)
          console.log(params)
          await GetPaperCouponList(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();
            }
          }
          setCurrentRow({});
        }}
        onCancel={() => {
          setCurrentRow({});
          handleModalVisible(false);
        }}
        createModalVisible={createModalVisible}
        values={currentRow || {}}
      />
    </PageContainer>
  );
};

export default Coupon;
