/*
 * @Author: your name
 * @Date: 2021-07-26 10:13:13
 * @LastEditTime: 2021-08-03 17:32:25
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /TracerMethodology_PC/src/pages/UserMana/index.js
 */

import { PlusOutlined } from '@ant-design/icons';
import { Button, Popconfirm} from 'antd';
import React, { useState, useRef } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import { ModalForm, ProFormText } from '@ant-design/pro-form';
import UpdateForm from './updateForm';
import DrawerContent from './component/drawer';
import { getRoleList, roleBindUser, addList, editList, delList,roleBindMenu } from './service';
import { getUserList } from '@/pages/UserMana/service';

import { getMenuList } from '@/pages/platformMana/menuManage/service';

const UserMana = () => {
  const columns = [
    {
      title: '院区名称',
      dataIndex: 'hospName',
      key: 'hosp_name',
      hideInSearch: true,
    },
    {
      title: '角色名',
      dataIndex: 'roleName',
      key: 'role_name',
    },
    {
      title: '变更人',
      dataIndex: 'modifyUserName',
      key: 'modifyUserName',
      hideInSearch: true,
    },
    {
      title: '变更日期',
      dataIndex: 'modifyTime',
      key: 'modifyTime',
      valueType: 'date',
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="config"
          onClick={() => {
            setEditRoleBindUsers(true);
            setDrawerVisible(true);
            setCurrentRow(record);
          }}
        >
          用户
        </a>,
        <a
          key="config"
          onClick={() => {
            setEditRoleBindUsers(false);
            setDrawerVisible(true);
            setCurrentRow(record);
          }}
        >
          权限
        </a>,
        <a
          key="config"
          onClick={() => {
            handleUpdateModalVisible(true);
            setCurrentRow(record);
          }}
        >
          编辑
        </a>,
        <Popconfirm
          key="subscribeAlert"
          title="是否确定删除?"
          onConfirm={() => {
            delUserHandler(record);
          }}
        >
          <a>删除</a>
        </Popconfirm>,
      ],
    },
  ];

  const DrawerTableUsersColumns = [
    {
      title: 'Id',
      dataIndex: 'id',
      key: 'id',
      hideInSearch: true,
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '用户名',
      dataIndex: 'account',
      key: 'account',
      hideInSearch: true,
    },
    {
      title: '在职状态',
      dataIndex: 'hospitalStatus',
      key: 'hospitalStatus',
      hideInSearch: true,
    },
  ];
  
  const DrawerTableMenusColumns = [
    {
      title: 'Id',
      dataIndex: 'menuId',
      key: 'menuId',
      hideInSearch: true,
    },
    {
      title: '菜单名称',
      dataIndex: 'name',
      key: 'name',
    }
  ];

  const [createModalVisible, handleModalVisible] = useState(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState(false);
  const actionRef = useRef();
  const [currentRow, setCurrentRow] = useState({});
  const [editRoleBindUsers, setEditRoleBindUsers] = useState(false);
  const [drawerVisible, setDrawerVisible] = useState(false);

  // const [shareParamsSetting,setShareParamsSetting] = useState(false);  //是否分摊参数设置

  /**
   *
   * @param {Boolean} bool 弹窗展示状态
   */
  const updateModalVisibleChange = (bool) => {
    handleUpdateModalVisible(bool);
    if (!bool) setCurrentRow(undefined);
  };

  //获取列表
  const getList = async (params = {}, sort, filter) => {
    const res = await getRoleList(params);
    return {
      data: res.data.list,
      total: res.data.totalCount,
      success: res.success,
    };
  };

  //获取Drawer用户列表
  const getUsers = async (params = {}, sort, filter) => {
    const res = await getUserList(params);
    return {
      data: res.data.list,
      total: res.data.totalCount,
      success: res.success,
    };
  };

  //获取Drawer菜单列表
  const getMenus = async (params = {}, sort, filter) => {
    const res = await getMenuList(params);
    return {
      data: res.data.list,
      total: res.data.totalCount,
      success: res.success,
    };
  };

  /**
   *
   * @param {Object} value 删除项数据
   */
  const delUserHandler = async (value) => {
    const ids = [value.roleId];
    const resp = await delList({ ids });
    if (resp.status == 200) {
      if (actionRef.current) {
        actionRef.current.reload();
      }
    }
  };

  return (
    <PageContainer>
      <ProTable
        columns={columns}
        request={getList}
        actionRef={actionRef}
        rowKey="roleId"
        toolBarRender={() => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            type="primary"
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            新增
          </Button>,
        ]}
        pagination={{
          pageSize: 10,
        }}
        search={{
          defaultCollapsed: false,
          labelWidth: 'auto',
        }}
      />

      <ModalForm
        title="新增角色"
        width="800px"
        labelCol={{ span: 5, offset: 3 }}
        layout={'horizontal'}
        visible={createModalVisible}
        onVisibleChange={handleModalVisible}
        onFinish={async (value) => {
          const success = await addList(value);
          //   console.log({ success });
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        <ProFormText
          label="角色名"
          rules={[
            {
              required: true,
              message: '角色名是必填项！',
            },
          ]}
          width="sm"
          name="roleName"
        />
        <ProFormText
          label="备注"
          rules={[
            {
              required: false,
              message: '',
            },
          ]}
          width="sm"
          name="remark"
        />
      </ModalForm>

      {/* 更新 */}
      <UpdateForm
        onSubmit={async (value) => {
          // console.log({value});
          const { roleId, roleName, remark } = value;
          const success = await editList({ roleId, roleName, remark });

          if (success) {
            handleUpdateModalVisible(false);
            setCurrentRow(undefined);

            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleUpdateModalVisible(false);
          setCurrentRow(undefined);
        }}
        updateModalVisible={updateModalVisible}
        updateModalVisibleChange={updateModalVisibleChange}
        values={currentRow || {}}
      />

      {editRoleBindUsers ? (
        //编辑用户
        <DrawerContent
          columns={DrawerTableUsersColumns}
          visible={drawerVisible}
          currentRow={currentRow}
          defaultSelected={[98, 87]}
          onVisibleChange={(bool) => setDrawerVisible(bool)}
          renderListFunc={getUsers}
          config={{tableSearch:true}}
          onFinishFunc={async (value, selectedRowKeys) => {
            // console.log({value,selectedRowKeys});
            const { roleId } = currentRow;
            const resp = await roleBindUser({ roleId, userIds: selectedRowKeys });
            const { status } = resp;
            if (status == 200) {
              setDrawerVisible(false);
              setCurrentRow(undefined);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
        />
      ) : (
        //编辑权限
        <DrawerContent
          columns={DrawerTableMenusColumns}
          visible={drawerVisible}
          currentRow={currentRow}
          defaultSelected={[98, 87]}
          onVisibleChange={(bool) => setDrawerVisible(bool)}
          renderListFunc={getMenus}
          config={{rowKeys:'menuId',tableSearch:false}}
          tableSearch={false}
          onFinishFunc={async (value, selectedRowKeys) => {
            // console.log({value,selectedRowKeys});
            const { roleId } = currentRow;
            const resp = await roleBindMenu({ roleId, menuIds: selectedRowKeys });
            const { status } = resp;
            if (status == 200) {
              setDrawerVisible(false);
              setCurrentRow(undefined);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
        />
      )}
    </PageContainer>
  );
};

export default UserMana;
