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 ConfigurationForm from './components/ConfigurationForm';
import { CloseOutlined, CheckOutlined } from '@ant-design/icons';
import QRCode from 'qrcode.react';
import {
  GetactivityInfo,
  AddActivityInfo,
  UpdateActivityInfo,
  DelActivityInfo,
  GetActivityConfiguration,
  UpdateActivityAllState,
  GetCanUseCoupon,
} from './service';

const key = 'message';

const activityInfManage = () => {
  const [form] = Form.useForm();
  const actionRef = useRef();
  const [currentRow, setCurrentRow] = useState();
  const [createModalVisible, handleModalVisible] = useState(false);
  const [ConfigurationModalVisible, handleConfigurationModalVisible] = useState(false);
  const [activityConfiguration, SetactivityConfiguration] = useState([]);
  const [activityId, SetActivityId] = useState([]);

  //新增
  const handleAdd = async (fields) => {
    message.loading('正在添加...', key);
    try {
      if (fields.activityType == 3) {
        fields.activityRewards.forEach(element => {
          element.value = `[${element.value.join()}]`
        });
      }
      await AddActivityInfo(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 DelActivityInfo(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 UpdateActivityInfo(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 updateActivityState = async (fields) => {
    message.loading('正在修改...', key);
    try {
      await UpdateActivityAllState(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 columns = [
    {
      title: '主键',
      dataIndex: 'id',
      hideInSearch: true,
      hideInTable: true,
      tip: '规则名称是唯一的 key',
    },
    {
      title: '图片',
      dataIndex: 'activityImg',
      valueType: 'textarea',
      hideInSearch: true,
      render: (_, record) => (
        <img src={record.activityImg} style={{ width: '45px', height: '45px' }}></img>
      ),
    },
    {
      title: '活动名称',
      dataIndex: 'activityName',
      valueType: 'textarea',
    },
    {
      title: '活动类型',
      dataIndex: 'activityType',
      valueEnum: {
        1: { text: '送券', status: 'Processing' },
        2: { text: '买满减现', status: 'Success' },
        3: { text: '商品促销', status: 'Success' },
        4: { text: '买满赠送(优惠券)', status: 'Success' },
        5: { text: '买满赠送(商品)', status: 'Success' },
        6: { text: '累计消费换购(阶梯)', status: 'Success' },
        7: { text: '累计消费换购(循环)', status: 'Success' },
        8: { text: '加价换购', status: 'Success' },
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueEnum: {
        0: { text: '启用', status: 'Processing' },
        1: { text: '禁用', status: 'Error' },
      },
    },
    {
      title: '是否显示',
      dataIndex: 'isShow',
      valueEnum: {
        0: { text: '不显示', status: 'Processing' },
        1: { text: '显示', status: 'Error' },
      },
      render: (_, record) => (
        <>
          <Switch
            checkedChildren="显示"
            unCheckedChildren="不显示"
            checked={record.isShow == 1}
            onChange={(checked) => {
              var data = { activityId: record.id, type: 2, value: record.isShow };
              data.value = checked ? 1 : 0;
              updateActivityState(data);
            }}
          />
        </>
      ),
    },
    {
      title: '是否后台计算',
      dataIndex: 'isAutoSend',
      valueEnum: {
        0: { text: '点击参与', status: 'Processing' },
        1: { text: '后台计算', status: 'Error' },
      },
      render: (_, record) => (
        <>
          <Switch
            checkedChildren="点击参与"
            unCheckedChildren="后台计算"
            checked={record.isAutoSend == 1}
            onChange={(checked) => {
              var data = { activityId: record.id, type: 3, value: record.isAutoSend };
              data.value = checked ? 1 : 0;
              updateActivityState(data);
            }}
          />
        </>
      ),
    },
    {
      title: '活动时间',
      hideInSearch: true,
      render: (text, record, index) => {
        return (
          <span>
            <div>
              {moment(record.activityStartTime).format('YYYY-MM-DD')}至
              {moment(record.activityEndTime).format('YYYY-MM-DD')}
            </div>
          </span>
        );
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createAt',
      valueType: 'date',
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        const status = form.getFieldValue('status');

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

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

        return defaultRender(item);
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => {
        let template = [
          <a
            key="update"
            type="primary"
            onClick={() => {
              GetCanUseCoupon(record.id).then((r) => {
                if (r.data) {
                  handleModalVisible(true);
                  setCurrentRow(() => {
                    record.activityStartTime = moment(record.activityStartTime);
                    record.activityEndTime = moment(record.activityEndTime);
                    record.activityRewards = r.data;
                    if (record.activityType == 3) {
                      record.activityRewards.forEach((item) => {
                        item.value = JSON.parse(item.value)
                      })
                    }
                    form.setFieldsValue(record);
                    return record;
                  });
                }
              });
            }}
          >
            更新
          </a>,
          <a
            key="jy"
            type="primary"
            onClick={() => {
              var data = { activityId: record.id, type: 1, value: record.status };
              data.value = record.status == 0 ? 1 : 0;
              updateActivityState(data);
            }}
          >
            {record.status == 0 ? '禁用' : '启用'}
          </a>,
          <a
            key="pz"
            type="primary"
            onClick={() => {
              GetActivityConfiguration(record.id).then((r) => {
                if (r.data) {
                  SetActivityId(record.id);
                  SetactivityConfiguration(r.data);
                  handleConfigurationModalVisible(true);
                }
              });
            }}
          >
            配置
          </a>,
          <Popconfirm
            type="primary"
            key="del"
            title="确认删除吗？"
            okText="是"
            cancelText="否"
            onConfirm={() => {
              handleRemove([record]);
            }}
            onCancel={() => { }}
          >
            <a href="#">删除</a>
          </Popconfirm>,
          <a
            key="primary"
            onClick={() => {
              const config = {
                title: '二维码',
                content: (
                  <QRCode
                    id="qrCode"
                    value={`https://black-pa.com:5443/lead?activityId=${record.id}`}
                    size={200} // 二维码的大小
                    fgColor="#000000" // 二维码的颜色
                    style={{ margin: 'auto' }}
                  />
                ),
              };
              Modal.info(config);

            }}
          >
            {' '}
            二维码
          </a>
        ];
        return template;
      },
    },
  ];

  return (
    <PageContainer>
      <ProTable
        headerTitle="活动信息"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        request={async (params) => {
          var data = [];
          var total = 0;
          await GetactivityInfo(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 {
            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}
      />

      <ConfigurationForm
        onCancel={() => {
          setCurrentRow(undefined);
          handleConfigurationModalVisible(false);
        }}
        activityId={activityId}
        config={activityConfiguration}
        createModalVisible={ConfigurationModalVisible}
        values={currentRow || {}}
      />
    </PageContainer>
  );
};

export default activityInfManage;
