/*
 * @Author: your name
 * @Date: 2021-07-26 10:13:13
 * @LastEditTime: 2022-02-28 16:14:22
 * @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,Form} 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,ProFormDateRangePicker } from '@ant-design/pro-form';
import UpdateForm from './updateForm';
import DrawerContent from './component/drawer';
import { getRoleList, roleBindUser, addList, editList, delList,roleBindMenu,roleHasBindUsers,roleHasBindMenus } from './service';
import { getUserList } from '@/pages/PlatformMana/userMana/service';

import moment from 'moment';
import 'moment/locale/zh-cn';
import locale from 'antd/es/date-picker/locale/zh_CN';

import { getMenuList } from '@/pages/PlatformMana/menuManage/service';
import './style.less';

const UserMana = () => {
  const columns = [
    {
      title: '角色名',
      dataIndex: 'roleName',
      key: 'roleName',
    },
    {
      title: '变更人',
      dataIndex: 'modifyUserName',
      key: 'modifyUserName',
      hideInSearch: true,

    },
    {
      title: '变更日期',
      dataIndex: 'modifyTime',
      key: 'modifyTime',
      renderFormItem: (item, { type, defaultRender, formItemProps, fieldProps, ...rest }, form) => {

        if (type === 'form') {
          return null;
        }
        return (
          <Form.Item noStyle>
            <ProFormDateRangePicker  fieldProps={{locale,onChange:(moment)=>{console.log(moment)} }} name="modifyTime" />
          </Form.Item>
        )
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="config"
          onClick={() => {
            bindInitHandle(record,'user');
          }}
        >
          用户
        </a>,
        <a
          key="config"
          onClick={() => {
            bindInitHandle(record,'menu');
          }}
        >
          权限
        </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,
      render:num=><>{num==0?'离职':'在职'}</>
    },
  ];
  
  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 [selectedUsers,setSelectedUsers] = useState([]);
  const [selectedMenus,setSelectedMenus] = useState([]);

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

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

  // 获取列表
  const getList = async (params = {}, sort, filter) => {
    // format: (value) => { return [value[0].format('YYYY-MM-DD'),value[1].format('YYYY-MM-DD')] }
    const {pageSize,current,modifyTime,roleName:keyword} = params;
    const query = modifyTime?{pageSize,current,keyword,startDate:moment(modifyTime[0]).format('YYYY-MM-DD'),endDate:moment(modifyTime[1]).format('YYYY-MM-DD')}:{pageSize,current,keyword}
    const res = await getRoleList(query);
    if(res){
      return {
        data: res.list,
        total: res.totalCount,
        success:true,
      };
    }
  };

  // 获取Drawer用户列表
  const getUsers = async (params = {}, sort, filter) => {
    const {roleId} = currentRow;
    const resp = await roleHasBindUsers({roleId});
    if(resp){
      const tempArr = resp.map(item=>item.id);
      setSelectedUsers(tempArr);
    }
    const res = await getUserList({...params,roleId:currentRow.roleId});
    if(res){
      return {
        data: res.list,
        total: res.totalCount,
        success: true,
      };
    }
  };

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

  /**
   *
   * @param {Object} value 删除项数据
   */
  const delUserHandler = async (value) => {
    const ids = [value.roleId];
    const resp = await delList({ ids });
    if (resp) {
      if (actionRef.current) {
        actionRef.current.reload();
      }
    }
  };
  
  // 绑定初始化
  /**
   * 
   * @param {Object} record 
   * @param {String} type   user/menu
   */
  const bindInitHandle = async (record,type)=>{
    
    const {roleId} = record;
    setCurrentRow(record);

    if(type == 'user'){
      const resp = await roleHasBindUsers({roleId});
      if(resp){
        const tempArr = resp.map(item=>item.id);
        setSelectedUsers(tempArr);
      }
      setEditRoleBindUsers(true);
    }
    
    if(type == 'menu'){
      const resp = await roleHasBindMenus({roleId});
      if(resp){
        const tempArr = resp.map(item=>item.id);
        setSelectedMenus(tempArr);
      }
      setEditRoleBindUsers(false);
    }
    setDrawerVisible(true);
    setCurrentRow(record);
  }


  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,
        }}
      />

      <ModalForm
        title="新增角色"
        width="800px"
        labelCol={{ span: 5, offset: 3 }}
        layout={'horizontal'}
        visible={createModalVisible}
        onVisibleChange={handleModalVisible}
        modalProps={{
          destroyOnClose:true
        }}
        onFinish={async (value) => {
          const success = await addList(value);
          //   console.log({ success });
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
          return true;
        }}
      >
        <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}
          title="绑定用户"
          defaultSelected={selectedUsers}
          onVisibleChange={(bool) => setDrawerVisible(bool)}
          renderListFunc={getUsers}
          config={{tableSearch:true}}
          onFinishFunc={async (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}
          title="绑定权限"
          defaultSelected={selectedMenus}
          onVisibleChange={(bool) => setDrawerVisible(bool)}
          renderListFunc={getMenus}
          config={{rowKeys:'menuId',tableSearch:false}}
          tableSearch={false}
          onFinishFunc={async (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;
