/*
 * @Author: your name
 * @Date: 2022-01-11 09:43:18
 * @LastEditTime: 2025-05-13 15:32:58
 * @LastEditors: code4eat awesomedema@gmail.com
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: /KC-MiddlePlatform/src/pages/platform/userManage/index.tsx
 */

import { FC, useEffect, useState } from 'react';
import { userManageModelState, ConnectProps, Loading, connect, useModel } from 'umi';
import { Button, Divider, Popconfirm, Popover, Tooltip } from 'antd';
import KCTable from '@/components/kcTable';
import type { ProColumns } from '@ant-design/pro-table';
import { getUserRelaSeletData, getUsers, UserRelaSeletDataListType, UserRelaSeletDataType } from '@/service/user';
import { TableRequestParamsType } from '@/typings';
import ActModal from './modal';
import './style.less';
import { TableListItem } from './typings';
import { ModalForm, ProFormSelect, ProFormUploadButton } from '@ant-design/pro-form';
import KCUpload from '@/components/KCUpload';
import { RcFile } from 'antd/lib/upload/interface';
import { KCInput } from '@/components/KCInput';
import FormItem from 'antd/es/form/FormItem';
import { getDepartmentData } from '../departmentMana/service';

export enum TableActType {
  NOACT,
  ADD,
  DEL,
  EDIT,
}

interface PageProps extends ConnectProps {
  userManageModel: userManageModelState;
  loading: boolean;
}

const UserManage: FC<PageProps> = ({ userManageModel: state, dispatch }) => {
  const { reloadTable } = state;
  const { initialState, setInitialState } = useModel('@@initialState');
  const [tableDataFilterParams, set_tableDataFilterParams] = useState<TableRequestParamsType>({
    current: 1,
    pageSize: 10,
    name: '',
    account: '',
    departmentId: undefined
  });
  const [tableDataSearchKeywords, set_tableDataSearchKeywords] = useState<string>('');

  const [dirData, set_dirData] = useState<UserRelaSeletDataType[]>([]);

  const columns: ProColumns<TableListItem>[] = [
    {
      title: initialState?.customerType == '2' ? '园区' : '院区',
      dataIndex: 'hospName',
      ellipsis: true,
      width: 210,
    },
    {
      title: '姓名',
      dataIndex: 'name',
      hideInSearch: false,
    },
    {
      title: '工号',
      dataIndex: 'account',
      hideInSearch: false,
    },
    {
      title: '联系电话',
      dataIndex: 'phoneNumber',
    },
    {
      title: '身份证号',
      dataIndex: 'idCardNum',
    },
    {
      title: '在职状态',
      dataIndex: 'isOnService',
      valueEnum: {
        0: { text: '否', status: 'Default' },
        1: { text: '是', status: 'Success' },
      },
    },
    {
      title: initialState?.customerType == '2' ? '人员标签' : '人员标签',
      width: 160,
      ellipsis: true,
      renderText(text: any, record: any) {
        const { tagList = [] } = record;
        return (
          <>
            {tagList.map((a: any, i: number) => (
              <span
                style={{
                  display: 'inline-flex',
                  padding: '2px 5px',
                  fontSize: 12,
                  background: '#EEF3FA',
                  borderRadius: 4,
                  color: '#525866',
                  marginRight: 4,
                }}
              >
                {a.tagName}
              </span>
            ))}
          </>
        );
      },
    },
    {
      title: '操作',
      width: 180,
      key: 'option',
      valueType: 'option',
      render: (text, record) => {
        const getEditBtn = () => {
          const { isEdit } = record;
          if (!isEdit) {
            return [
              <a key="link" onClick={() => editHandle(record)}>
                编辑
              </a>,
              <Divider key="1" type="vertical" style={{ margin: '0 3px' }} />,
              <Popconfirm
                title="是否确定删除?"
                onConfirm={() => delHandle(record)}
                // onCancel={cancel}
                okText="确定"
                cancelText="取消"
                key="link2"
              >
                <a>删除</a>
              </Popconfirm>,
            ];
          } else {
            return [
              <Tooltip title="第三方人员不可编辑！">
                <span style={{ cursor: 'not-allowed', color: 'rgb(176 181 189)' }}>编辑</span>
              </Tooltip>,
              <Divider key="1" type="vertical" style={{ margin: '0 3px' }} />,
              <Tooltip title="第三方人员不可编辑！">
                <span style={{ cursor: 'not-allowed', color: 'rgb(176 181 189)' }}>删除</span>
              </Tooltip>,
            ];
          }
        };
        return [
          ...getEditBtn(),
          <Divider key="2" type="vertical" style={{ margin: '0 3px' }} />,
          <a key="link3" onClick={() => resetUserPaswdHandle(record)}>
            重置密码
          </a>,
        ];
      },
    },
  ];

  const getUserData = async (params: TableRequestParamsType) => {
    const { current = 1, pageSize = 10, name = undefined, account = undefined, departmentId = undefined } = params;

    const resp = await getUsers({
      current,
      pageSize,
      keyword: name ? name : account,
      departmentId,
    });

    //获取万最新数据取消重置reload
    dispatch &&
      dispatch({
        type: 'userManageModel/reloadTable',
        payload: false,
      });

    return {
      data: resp.list ? resp.list : [],
      success: true,
      total: resp.totalCount,
    };
  };

  const addUserHandle = () => {
    dispatch &&
      dispatch({
        type: 'userManageModel/addUser',
        payload: {
          tableAct: TableActType.ADD,
          isShowModal: true,
        },
      });
  };

  const editHandle = (record: TableListItem) => {
    dispatch &&
      dispatch({
        type: 'userManageModel/editUser',
        payload: {
          userData: record,
          act: TableActType.EDIT,
          isShowModal: true,
        },
      });
  };

  const delHandle = (record: TableListItem) => {
    dispatch &&
      dispatch({
        type: 'userManageModel/delUsersRequest',
        payload: [record.id],
      });
  };

  const getUserTemplateHandle = () => {
    dispatch &&
      dispatch({
        type: 'userManageModel/getUserTemplateReq',
      });
  };

  const resetUserPaswdHandle = (record: TableListItem) => {
    dispatch &&
      dispatch({
        type: 'userManageModel/resetUserPwd',
        payload: {
          id: record.id,
        },
      });
  };

  const importUserHandle = (file: RcFile | undefined) => {
    if (file) {
      dispatch &&
        dispatch({
          type: 'userManageModel/importUsers',
          payload: file,
        });
    }
  };

  const getDirecData = async (key?: string) => {
    const data = await getUserRelaSeletData(key);
    if (data) {
      set_dirData(data);
    }
  };

  const tableDataSearchHandle = (paramName: string) => {
    set_tableDataFilterParams({
      ...tableDataFilterParams,
      current: 1,
      [`${paramName}`]: tableDataSearchKeywords
    });
  }

  const handleTableChange = (pagination: any) => {
    set_tableDataFilterParams({
      ...tableDataFilterParams,
      current: pagination.current,
      pageSize: pagination.pageSize
    });
  }

  const importData = (name: string) => {
    return (
      <ModalForm
        title={`导入${name}数据`}
        width={352}
        trigger={<span key="3">导入</span>}
        onFinish={async (values: any) => {
          const {
            importFile: { fileList },
          } = values;

          let formData = new FormData();

          formData.append('file', fileList[0].originFileObj);

          dispatch &&
            dispatch({
              type: 'userManageModel/importUsers',
              payload: formData,
            });
          return true;
        }}
      >
        <FormItem name={'importFile'}>
          <KCUpload downloadTemplateFile={() => getUserTemplateHandle()} />
        </FormItem>
      </ModalForm>
    );
  };

  const setSelectorData = (key: string) => {
    let result = dirData.filter((t: any) => t.code == key);

    if (result.length > 0) {
      let dataArr = result[0].dataVoList;

      let defaultValue = dataArr.filter((t) => t.defaultValue == 1);

      dataArr.sort((prev: UserRelaSeletDataListType, next: UserRelaSeletDataListType) => {
        return prev.sort - next.sort;
      });

      return {
        defaultvalue: defaultValue[0] ? defaultValue[0].value : '',
        list: dataArr.map((t) => {
          return { label: t.name, value: t.code };
        }),
      };
    }

    return {
      defaultvalue: '',
      list: [],
    };
  };

  useEffect(() => {
    getDirecData();
  }, []);

  //  console.log({state});

  return (
    <div className="UserManage">
      <ActModal {...state} dispatch={dispatch} />

      <div className="toolBar">
        <div className="filter">
          <div className="filterItem" style={{ marginRight: 16 }}>
            <span className="label">{initialState?.customerType == '2' ? '组织：' : '科室：'}</span>
            <ProFormSelect
              name="departmentId"
              noStyle
              style={{ width: 160 }}
              placeholder="请选择"
              request={async () => {
                const resp = await getDepartmentData({ pageSize: 1000 });
                if (resp) {
                  return resp.list.map((a) => ({ label: a.name, value: a.id }));
                }
                return [];
              }}
              fieldProps={{
                size: 'small',
                showSearch: true,
                onChange: (val) => {
                  set_tableDataFilterParams({
                    ...tableDataFilterParams,
                    current: 1,
                    departmentId: val,
                  });
                },
              }}
            />
          </div>
          <div className="filterItem">
            <span className="label">检索：</span>
            <KCInput
              placeholder={'请输入姓名/工号'}
              style={{ width: 160 }}
              search
              allowClear
              onChange={(e) => {
                set_tableDataSearchKeywords(e.target.value);
                if (e.target.value.length == 0) {
                  set_tableDataFilterParams({
                    ...tableDataFilterParams,
                    current: 1,
                    name: '',
                    account: ''
                  });
                }
              }}
              onSearch={() => tableDataSearchHandle('name')}
            />
          </div>
        </div>
        <div className="btnGroup">
          {importData('员工')}
          <span className="add" onClick={addUserHandle}>
            新增
          </span>
        </div>
      </div>

      <div style={{ marginTop: 16 }}>
        <KCTable
          columns={columns}
          scroll={{ y: `calc(100vh - 250px)` }}
          reload={reloadTable}
          rowKey="id"
          newVer
          params={tableDataFilterParams}
          request={(params) => getUserData(params)}
          onChange={handleTableChange}
        />
      </div>
    </div>
  );
};

export default connect(({ userManageModel, loading }: { userManageModel: userManageModelState; loading: Loading }) => {
  //  console.log({userManageModel});
  return {
    userManageModel,
    loading: loading.models.userManageModel,
  };
})(UserManage);
