import React, { useState, useRef, useEffect } from 'react';
import { Modal, Card, Tree, Button, message, Drawer, Divider, Menu, Dropdown } from 'antd';
import { PlusOutlined, DownOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import ProTable, { ProColumns, ActionType, TableDropdown } from '@ant-design/pro-table';
import ProDescriptions from '@ant-design/pro-descriptions';
import CreateForm from './components/CreateForm';
import { queryUser, addUser, removeRule, updateUser, setRoles, sysUserGrantData } from './service';
import { gettree } from '../../sys/org/service';

import moment from 'moment';
import { useAccess } from 'umi';
import RoleForm from './components/RoleForm';
import OrgForm from './components/OrgForm';

//import { TableListItem as RoleData } from '../roles/data.d';

/**
 * 添加节点
 * @param fields
 */
const handleAdd = async (fields) => {
  const hide = message.loading('正在添加');
  try {
    await addUser({ ...fields });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

/**
 * 更新节点
 * @param fields
 */
const handleUpdate = async (fields) => {
  const hide = message.loading('正在更新');
  try {
    await updateUser({ ...fields });
    hide();

    message.success('更新成功');
    return true;
  } catch (error) {
    hide();
    message.error('更新失败请重试！');
    return false;
  }
};

/**
 * 分配角色
 * @param fields
 */
const handleRoles = async (fields) => {
  const hide = message.loading('正在分配角色');
  try {
    await setRoles({ ...fields });
    hide();

    message.success('分配角色成功');
    return true;
  } catch (error) {
    hide();
    message.error('分配角色失败请重试！');
    return false;
  }
};

/**
 * 正在分配数据权限
 * @param fields
 */
const handleGrantData = async (fields) => {
  const hide = message.loading('正在分配数据权限');
  try {
    await sysUserGrantData({ ...fields });
    hide();
    message.success('分配数据权限成功');
    return true;
  } catch (error) {
    hide();
    message.error('分配数据权限失败请重试！');
    return false;
  }
};
/**
 *  删除节点
 * @param selectedRows
 */
const handleRemove = async (selectedRows) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
  try {
    await removeRule({
      ids: selectedRows.map((row) => row._id),
    });
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};
const TableList = () => {
  const [createModalVisible, handleModalVisible] = useState();
  const [updateRoleModalVisible, handleUpdateRoleModalVisible] = useState();
  const [updateOrgModalVisible, handleUpdateOrgModalVisible] = useState();
  const [stepFormValues, setStepFormValues] = useState({});
  const actionRef = useRef();
  const [row, setRow] = useState();
  const [selectedRowsState, setSelectedRows] = useState();

  const [treeData, setTreeData] = useState();
  const [Pid, setKey] = useState();

  const access = useAccess();
  const columns = [
    {
      title: '关键词',
      dataIndex: 'SearchValue',
      hideInForm: true,
      hideInTable: true,
      tip: '可以输入账号,姓名',
      placeholder: '',
    },
    {
      title: '机构',
      dataIndex: 'orgId',
      hideInForm: true,
      hideInTable: true,
      hideInSearch: true,
    },
    {
      title: '登录账号',
      dataIndex: 'account',
      tip: '登录账号是唯一的 key',
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '登录账号必填!',
          },
        ],
      },
      renderText: (dom, entity) => {
        return <a onClick={() => setRow(entity)}>{dom}</a>;
      },
    },
    {
      title: '姓名',
      dataIndex: 'name',
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '用户名为必填项',
          },
        ],
      },
    },

    {
      title: '创建时间',
      search: false,
      dataIndex: 'createAt',
      hideInForm: true,
      sorter: true,
      renderText: (val) => moment(val).fromNow(),
    },
    {
      title: '备注',
      dataIndex: 'remark',
      valueType: 'textarea',
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <a
            onClick={() => {
              handleModalVisible(true);
              setStepFormValues(record);
            }}
          >
            修改
          </a>
          <Divider type="vertical" />
          <TableDropdown
            key="actionGroup"
            onSelect={(option) => {
              if (option === 'resetPwd') {
                Modal.confirm({
                  title: '重置密码',
                  icon: <ExclamationCircleOutlined />,
                  content: '是否确认重置密码',
                  okText: '确认',
                  cancelText: '取消',
                  onOk() {
                  },
                });
              } else if (option === 'grantRole') {
                handleUpdateRoleModalVisible(true);
                setStepFormValues(record);
              } else if (option === 'grantData') {
                handleUpdateOrgModalVisible(true);
                setStepFormValues(record);
              } else if (option === 'delete') {
                Modal.confirm({
                  title: '删除用户',
                  icon: <ExclamationCircleOutlined />,
                  content: '是否确认删除用户',
                  okText: '确认',
                  cancelText: '取消',
                });
              }
            }}
            menus={[
              { key: 'resetPwd', name: '重置密码' },
              { key: 'grantRole', name: '授权角色' },
              { key: 'grantData', name: '授权数据' },
              { key: 'delete', name: '删除' },
            ]}
          />
        </>
      ),
    },
  ];
  //初始化数据
  useEffect(() => {
    function initfranchiseeType() {
      gettree().then((r) => {
        setTreeData(r.data);
      });
    }
    initfranchiseeType();
  }, []);
  return (
    <PageContainer>
      <ProTable
        headerTitle="员工列表"
        actionRef={actionRef}
        rowKey="id"
        pagination={{ defaultPageSize: 20 }}
        search={{
          labelWidth: 120,
        }}
        tableRender={(_, dom) => (
          <div
            style={{
              display: 'flex',
              width: '100%',
            }}
          >
            <Card title="机构部门">
              <Tree defaultExpandAll={true} onSelect={(e) => setKey(e[0])} treeData={treeData} />
            </Card>
            <div
              style={{
                flex: 1,
              }}
            >
              {dom}
            </div>
          </div>
        )}
        toolBarRender={() => [
          <Button type="primary" key="create" onClick={() => handleModalVisible(true)}>
            <PlusOutlined /> 新建
          </Button>,
        ]}
        params={{
          Pid,
        }}
        request={async (params) => {
          let UserData = [];
          var total = 0;
          //添加机构组织
          await queryUser(params).then((r) => {
            console.log(r);
            UserData = r.data.data;
            total = r.data.total;
          });
          return {
            data: UserData,
            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>
        </FooterToolbar>
      )}
      <CreateForm
        treeDatas={treeData}
        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();
            }
          }
        }}
        onCancel={() => {
          handleModalVisible(false);
          setStepFormValues({});
        }}
        modalVisible={createModalVisible}
        values={stepFormValues || {}}
      />

      {stepFormValues && Object.keys(stepFormValues).length ? (
        <RoleForm
          onSubmit={async (value) => {
            if (value == null || value == undefined) {
              handleUpdateRoleModalVisible(false);
              setStepFormValues({});
              return true;
            }
            const values = {
              id: stepFormValues.id,
              grantRoleIdList: value.map((key) => key.id),
            };

            const success = await handleRoles(values);
            if (success) {
              handleUpdateRoleModalVisible(false);
              setStepFormValues({});
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          onCancel={() => {
            handleUpdateRoleModalVisible(false);
            setStepFormValues({});
          }}
          updateModalVisible={updateRoleModalVisible}
          values={stepFormValues}
        />
      ) : null}
      {stepFormValues && Object.keys(stepFormValues).length ? (
        <OrgForm
          treeDatas={treeData}
          onSubmit={async (value) => {
            if (value == null || value == undefined) {
              handleUpdateOrgModalVisible(false);
              setStepFormValues({});
              return true;
            }
            const values = {
              id: stepFormValues.id,
              grantRoleIdList: value,
            };

            const success = await handleGrantData(values);
            if (success) {
              handleUpdateOrgModalVisible(false);
              setStepFormValues({});
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          onCancel={() => {
            handleUpdateOrgModalVisible(false);
            setStepFormValues({});
          }}
          updateModalVisible={updateOrgModalVisible}
          values={stepFormValues}
        />
      ) : null}
      <Drawer
        width={600}
        visible={!!row}
        onClose={() => {
          setRow(undefined);
        }}
        closable={false}
      >
        {row?.name && (
          <ProDescriptions
            column={2}
            title={`${row?.name} 的详情`}
            request={async () => ({
              data: row || {},
            })}
            params={{
              id: row?._id,
            }}
            columns={columns}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default TableList;
