import { PlusOutlined } from '@ant-design/icons';
import { Button, message, Drawer, 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 MenuForm from './components/MenuForm';
import api from './service';

/**
 * 添加节点
 *
 * @param fields
 */

const handleAdd = async (fields) => {
  try {
    await api.addCompany(fields).then((r) => {
      if (!r.succeeded) {
        message.error(r.errors);
        return false;
      }
      if (r.data) {
        message.success('添加成功');
      } else {
        message.error('添加失败请重试！');
      }
    });
    return true;
  } catch (error) {
    message.error('添加失败请重试！');
    return false;
  }
};
/**
 * 更新节点
 *
 * @param fields
 */

const handleUpdate = async (fields) => {
  try {

    await api.updateCompany(fields).then((r) => {
      if (!r.succeeded) {
        message.error(r.errors);
        return false;
      }
      if (r.data) {
        message.success('配置成功');
      } else {
        message.error('配置失败请重试！');
      }
    });
    return true;
  } catch (error) {
    message.error('配置失败请重试！');
    return false;
  }
};
/**
 * 删除节点
 *
 * @param selectedRows
 */

const handleRemove = async (selectedRows) => {
  if (!selectedRows) return true;
  try {
    await api.removeCompany(selectedRows.map((row) => row.id)).then((r) => {
      if (r) {
        message.success('删除成功，即将刷新');
        return true;
      } else {
        message.error('删除失败，请重试');
      }
    });
    return true;
  } catch (error) {
    message.error('删除失败，请重试');
    return false;
  }
};


const handleMenu = async (fields) => {
  try {
    await api.addRoleMenu(fields).then((r) => {
      if (r.data) {
        message.success('授权成功');
      } else {
        message.error('授权失败请重试！');
      }
    });
    return true;
  } catch (error) {
    message.error('授权失败请重试！');
    return false;
  }
};

const companyManage = () => {
  /** 新建窗口的弹窗 */
  const [createModalVisible, handleModalVisible] = useState();
  /*菜单授权*/
  const [updateMenuModalVisible, handleUpdateMenuModalVisible] = useState();
  const [stepFormValues, setStepFormValues] = useState({});
  /**详情 */
  const [showDetail, setShowDetail] = useState();
  /*绑定数据 */
  const actionRef = useRef();
  const [currentRow, setCurrentRow] = useState();
  /*选中*/
  const [selectedRowsState, setSelectedRows] = useState();

  //获取功能菜单数据
  const [treeData, setTreeData] = useState();

  const [row, setRow] = useState();

  useEffect(() => {
    var parm={getType:'ALL',type:0}
    api.GetMenu(parm).then((r) => {
      if(r.data){
        setTreeData(r.data);
      }
     
    });
  }, []);

  /** 国际化配置 */
  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: 'name',
      ellipsis: true,
    },
    {
      title: '管理员姓名',
      dataIndex: 'adminName',
      ellipsis: true,
    },
    {
      title: '邮箱账号',
      dataIndex: 'email',
      ellipsis: true,
    },
    {
      title: '电话',
      dataIndex: 'phone',
      hideInSearch: true,
    },
    {
      title: '备注',
      dataIndex: 'remark',
      hideInSearch: true,
    },
    {
      title: '创建时间',
      dataIndex: 'createAt',
      valueType: 'date',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      width: 350,
      render: (_, record) => {
        var template = [
          <a
            onClick={() => {
              handleModalVisible(true);
              setStepFormValues(record);
            }}
          >
            {' '}
            更新
          </a>,
          <a
            onClick={() => {
              api.GetRoleMenu(record.sysRoleId).then((r) => {
                setRow(r.data);
                handleUpdateMenuModalVisible(true);
              });
              setStepFormValues(record);
            }}
          >
            {' '}
            企业菜单授权
          </a>,
          <Popconfirm
            type="primary"
            key="primary"
            title="删除加盟商将会删除下面的用户以及菜单权限，确认删除吗？"
            okText="是"
            cancelText="否"
            onConfirm={() => {
              api.removeCompany([record.id]).then((r) => {

                message.success('删除成功，即将刷新');
                actionRef.current.reloadAndRest();
              });
            }}
            onCancel={() => { }}
          >
            <a href="#">删除</a>
          </Popconfirm>,
          //   <a
          //   // onClick={() => {
          //   //   api.GetRoleMenu(record.sysRoleId).then((r) => {
          //   //     setRow(r.data);
          //   //     handleUpdateMenuModalVisible(true);
          //   //   });
          //   //   setStepFormValues(record);
          //   // }}
          // >
          //   {' '}
          //   LOGO设置
          // </a>,
        ];
        return template;
      },
    },
  ];
  return (
    <PageContainer host header={{
      title: '',
      breadcrumb: {},
    }}>
      <ProTable
        headerTitle="企业信息列表"
        actionRef={actionRef}
        rowKey="id"
        pagination={{ defaultPageSize: 10 }}
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        request={async (params) => {
          var companyData = [];
          var total = 0;
          await api.companyPage(params).then((r) => {
            companyData = r.data.data;
            total = r.data.total;
          });
          return {
            data: companyData,
            success: true,
            total: total,
          };
        }}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              项 &nbsp;&nbsp;
            </div>
          }
        >
          {/* <Button
            type="primary"
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            批量删除
          </Button> */}
           <Popconfirm
            type="primary"
            key="primary"
            title="确认删除吗？"
            okText="是"
            cancelText="否"
            onConfirm={() => {
              handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
            onCancel={() => { }}
          >
            <a href="#">批量删除</a>
          </Popconfirm>
        </FooterToolbar>
      )}
      <CreateForm
        onFinish={async (value) => {
          var success = false;
          if (value.id) {
            success = await handleUpdate(value);
          } else {
            value.phone=value.email;
            success = await handleAdd(value);
          }
          if (success) {
            handleModalVisible(false);
            setCurrentRow(undefined);

            if (actionRef.current) {
              actionRef.current.reloadAndRest();
            }
          }
          actionRef.current?.reload();
        }}
        onCancel={() => {
          handleModalVisible(false);
          setStepFormValues({});
        }}
        modalVisible={createModalVisible}
        values={stepFormValues || {}}
      />
      {stepFormValues && Object.keys(stepFormValues).length ? (
        <MenuForm
          treeData={treeData}
          onSubmit={async (value) => {

            const values = {
              sysRoleId: stepFormValues.sysRoleId,
              sysMenuId: value,
            };
            const success = await handleMenu(values);
            if (success) {
              handleUpdateMenuModalVisible(false);
              setStepFormValues({});
              if (actionRef.current) {
                actionRef.current.reloadAndRest();
              }
            }
          }}
          onCancel={() => {
            handleUpdateMenuModalVisible(false);
            setStepFormValues({});
          }}
          modalVisible={updateMenuModalVisible}
          values={row || {}}
          datas={stepFormValues || {}}
        />
      ) : null}
      <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 companyManage;
