import { DropboxOutlined, PlusOutlined } from '@ant-design/icons';
import { Button, message, Input, Drawer, Modal, Popconfirm } 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 ProDescriptions from '@ant-design/pro-descriptions';
import CreateForm from './components/CreateForm';
import moment from 'moment';
import { GetCompany, GetPage, Add, update, Enable, Disable, Copy, Stop, GetBusinessAsync } from './services';

//页面 相当于 class
const AccountDetailsManage = () => {
  const [Company, setCompany] = useState();

  const [CompanyList, setCompanyList] = useState([]);
  //初始化数据
  useEffect(() => {
    //获取企业信息
    const initCompany = () => {
      var list = [];
      GetCompany().then((data) => {
        setCompany(data.data);
        for (let k in data.data) {
          list.push({ id: k.toString(), text: data.data[k.toString()] });
        }
      });
      setCompanyList(list);
    };
    initCompany();
  }, []);

  /** 新建/更新窗口的弹窗 */
  const [createModalVisible, handleModalVisible] = useState(false);
  /** 分布更新窗口的弹窗 */

  const [showDetail, setShowDetail] = useState(false);
  //绑定
  const actionRef = useRef();
  const [currentRow, setCurrentRow] = useState();

  //选中的行
  const [selectedRowsState, setSelectedRows] = useState([]);

  /**
   * 添加节点
   *
   * @param fields
   */
  function handleAdd(fields) {
    message.loading('正在添加');
    try {
      Add(JSON.stringify(fields));
      message.success('添加成功');
      //刷新数据
      actionRef.current.reload();
      return true;
    } catch (error) {
      message.error('添加失败请重试！');
      return false;
    }
  }

  /**
   * 更新节点
   *
   * @param fields
   */

  function handleUpdate(fields) {
    try {
      update(JSON.stringify(fields)).then((r) => {
        if (r.data) {
          message.success('配置成功');
          actionRef.current.reload();
        } else {
          message.error('配置失败请重试！');
        }
      });
      return true;
    } catch (error) {
      message.error('配置失败请重试！');
      return false;
    }
  }
  /** 国际化配置 */

  const columns = [
    {
      title: '主键',
      dataIndex: 'id',
      tip: '规则名称是唯一的 key',
      hideInSearch: true,
      hideInTable: true,
      render: (dom, entity) => {
        return (
          <a
            onClick={() => {
              setCurrentRow(entity);
              setShowDetail(true);
            }}
          >
            {dom}
          </a>
        );
      },
    },
    {
      title: '分账方案名称',
      dataIndex: 'planName',
      valueType: 'textarea',
    },
    {
      title: '开始时间',
      hideInSearch: true,
      dataIndex: 'planStartTime',
      valueType: 'dateTime',
    },
    {
      title: '结束时间',
      hideInSearch: true,
      dataIndex: 'planEndTime',
      valueType: 'dateTime',
    },
    {
      title: '服务费比例',
      dataIndex: 'serviceFee',
      valueType: 'textarea',
      hideInSearch: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueEnum: {
        0: { text: '正常' },
        1: { text: '停用' },
        2: { text: '禁用' },
      },
    },
    {
      title: '加盟商',
      width: 80,
      dataIndex: 'franchiseeId',
      hideInSearch: true,
      valueEnum: Company,
    },
    {
      title: '备注',
      dataIndex: 'remark',
      valueType: 'textarea',
      hideInSearch: true,
    },
    {
      title: '创建时间',
      sorter: true,
      dataIndex: 'createAt',
      valueType: 'dateTime',
      hideInSearch: true,
      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',
      valueType: 'option',
      render: (_, record) => {
        var template = [

        ];
        if (record.status != 2) {

          template.push(
            <a
              key="config"
              onClick={() => {
                GetBusinessAsync(record.id).then((r) => {
                  if (r.data) {
                    setCurrentRow(() => {
                      handleModalVisible(true);
                      if (record.planStartTime != null) {
                        record.planStartTime = moment(record.planStartTime);
                        record.planEndTime = moment(record.planEndTime);
                      }
                      record.businessList = r.data;
                      return record;
                    });

                  }
                });
              }}
            >
              更新
            </a>,
            <a
              key="config"
              onClick={() => {
                Stop(record.id);
                message.success('禁用分账');
                //刷新数据
                actionRef.current.reload();
              }}
            >
              删除
            </a>,
          );
        }
        if (record.status == 1) {
          template.push(
            <a
              key="config"
              onClick={() => {
               var isenable =  Enable(record.id);
               if(isenable)
               {
                message.success('启用成功');
               }
               else 
               {
                message.success('启用失败，请检查方案设置！');
               }
                //刷新数据
                actionRef.current.reload();
              }}
            >
              启用
            </a>,
          );
        }
        if (record.status == 0) {
          template.push(
            <a
              key="config"
              onClick={() => {
                Disable(record.id);
                message.success('停用成功');
                //刷新数据
                actionRef.current.reload();
              }}
            >
              停用
            </a>,
          );
        }
        
        template.push(
          <a
            key="config"
            onClick={() => {
              Copy(record.id);
              message.success('复制成功');
              //刷新数据
              actionRef.current.reload();
            }}
          >
            复制
          </a>,
        )
        return template;
      }
    },
  ];

  return (
    <PageContainer>
      <ProTable
        headerTitle="分账方案"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        columns={columns}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalVisible(true);
              setCurrentRow({});
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        //数据绑定
        request={async (params) => {
          var Data = [];
          var total = 0;
          await GetPage(params).then((r) => {
            Data = r.data.data;
            total = r.data.total;
          });
          return {
            data: Data,
            success: true,
            total: total,
          };
        }}
        // 每行选择点击事件
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      ></ProTable>

      {/* 分账账户管理(新增，修改) */}
      <CreateForm
        Company={CompanyList}
        onFinish={async (value) => {
          value.planStartTime = new Date(value.planDate[0]);
          value.planEndTime = new Date(value.planDate[1]);
          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 || {}}
      />
      <Drawer
        width={600}
        visible={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.name && (
          <ProDescriptions
            column={2}
            title={currentRow?.name}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.name,
            }}
            columns={columns}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default AccountDetailsManage;
