import { PlusOutlined } from '@ant-design/icons';
import { Switch, Popconfirm, Space, Tag, Button, message, Input, Drawer, Modal, Form } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import moment from 'moment';
import CreateForm from './components/CreateForm';
import { CloseOutlined, CheckOutlined } from '@ant-design/icons';
import QRCode from 'qrcode.react';
import {
  GetRechargeActivityPgage,
  AddRechargeActivity,
  UpdateRechargeActivity,
  DeleteRechargeActivity,
  UpdateRechargeActivityRecommend
} from './service';

const key = 'message';

const rechargeactivity = () => {
  const [form] = Form.useForm();
  const actionRef = useRef();
  const [currentRow, setCurrentRow] = useState();
  const [createModalVisible, handleModalVisible] = useState(false);

  //新增
  const handleAdd = async (fields) => {
    message.loading('正在添加...', key);
    try {
      await AddRechargeActivity(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 DeleteRechargeActivity(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.activityType == 3) {

        fields.activityRewards.forEach(element => {
          element.value = `[${element.value.join()}]`
        });
      }
      await UpdateRechargeActivity(JSON.stringify(fields)).then((r) => {
        message.destroy(key);
        if (r.data) {
          message.success('修改成功');
        } else {
          message.error(r.errors);
        }
      });
      //刷新数据
      actionRef.current.reload();
      return true;
    } catch (error) {
      message.destroy(key);
      message.error('修改失败请重试！');
      return false;
    }
  };
  //修改活动状态
  const updateRechargeActivityRecommend = async (fields) => {
    message.loading('正在修改...', key);
    try {
      await UpdateRechargeActivityRecommend(JSON.stringify(fields)).then((r) => {
        message.destroy(key);
        console.log(r)
        if (r.succeeded) {
          message.success('修改成功');
        } else {
          message.error("更新失败");
        }
      });
      //刷新数据
      actionRef.current.reload();
      return true;
    } catch (error) {
      message.destroy(key);
      message.error('修改失败请重试！');
      return false;
    }
  };

  const columns = [
    {
      title: '主键',
      dataIndex: 'id',
      hideInSearch: true,
      hideInTable: true,
      tip: '规则名称是唯一的 key',
    },
    {
      title: '充值金额',
      dataIndex: 'rechargeMoney',
      valueType: 'money',
    },
    {
      title: '赠送金额',
      dataIndex: 'giveMoney',
      valueType: 'money',
    },
    {
      title: '是否推荐',
      dataIndex: 'recommend',
      hideInSearch: true,
      render: (_, record) => (
        <>
          <Switch
            checkedChildren="推荐"
            unCheckedChildren="不推荐"
            checked={record.recommend}
            onChange={(checked) => {
              var data = { Id: record.id, Recommend: checked};
              updateRechargeActivityRecommend(data);
            }}
          />
        </>
      ),
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => {
        let template = [
          <a
            key="update"
            type="primary"
            onClick={() => {
              handleModalVisible(true);
              setCurrentRow(() => {
                return record;
              });
            }}
          >
            更新
          </a>,
        ];
        template.push(
            <Popconfirm
              type="primary"
              key="primary"
              title="确认删除吗？"
              okText="是"
              cancelText="否"
              onConfirm={() => {
                handleRemove([record]);
              }}
              onCancel={() => {}}
            >
              <a href="#">删除</a>
            </Popconfirm>,
          );
        return template;
      },
    },
  ];

  return (
    <PageContainer>
      <ProTable
        headerTitle="活动信息"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        request={async (params) => {
          var data = [];
          var total = 0;
          await GetRechargeActivityPgage(params).then((r) => {
            data = r.data.data;
            total = r.data.total;
          });
          return {
            data: data,
            success: true,
            total: total,
          };
        }}
        toolBarRender={() => [
          <Button
            key="primary"
            type="primary"
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            新建
          </Button>,
        ]}
        columns={columns}
      // rowSelection={{}}
      />

      <CreateForm
        onFinish={async (value) => {
          var success = false;
          if (value.id) {
            success = await handleUpdate(value);
          } else {
            console.log(value)
            success = await handleAdd(value);
          }
          if (success) {
            handleModalVisible(false);
            setCurrentRow(undefined);

            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
          actionRef.current.reload();
        }}
        onCancel={() => {
          setCurrentRow(undefined);
          handleModalVisible(false);
        }}
        createModalVisible={createModalVisible}
        values={currentRow || {}}
        form={form}
      />
    </PageContainer>
  );
};

export default rechargeactivity;
