/*
 * @Author: your name
 * @Date: 2022-01-11 09:43:18
 * @LastEditTime: 2024-12-02 14:15:06
 * @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 } from 'umi';
import { Button, Divider, Popconfirm } 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 [tableDataFilterParams, set_tableDataFilterParams] = useState<any | undefined>();
  const [tableDataSearchKeywords, set_tableDataSearchKeywords] = useState<string>('');

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

  const columns: ProColumns<TableListItem>[] = [
    {
      title: '院区',
      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: '操作',
      width: 220,
      key: 'option',
      valueType: 'option',
      render: (text, record) => [
        <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>,
        <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 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();
          console.log({ values });
          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">科室：</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: '',
                  });
                }
              }}
              onSearch={() => tableDataSearchHandle('name')}
            />
          </div>
        </div>
        <div className="btnGroup">
          {importData('员工')}
          <span className="add" onClick={addUserHandle}>
            新增
          </span>
        </div>
      </div>

      <KCTable
        rowKey="id"
        headerTitle="查询表格"
        columns={columns}
        reload={reloadTable}
        params={tableDataFilterParams}
        newVer
        scroll={{y:`calc(100vh - 255px)`}}
        expandable={{
          expandedRowRender: (record) => (
            <div className="userExpandInfo">
              <span>进院时间：{record.entryTime}</span>
              <span>手机号：{record.phoneNumber}</span>
              <span>所学专业：{record.major}</span>
              <span>资格证号：{record.qualificationCertificateNo}</span>
              <span>医师级别：{record.doctorLevel}</span>
              <span>执业证号：{record.practiceCertificateNo}</span>
              <span>执业类别：{record.practiceSubject}</span>
              <span>执业科目：{record.practiceCate}</span>
              <span>执业状态：{record.practiceStatus}</span>
              <span>备注：{record.remark}</span>
            </div>
          ),
          rowExpandable: () => true,
        }}
        // toolBarRender={() => [
        //   <KCUpload
        //     title="导入数据"
        //     fieldProps={{
        //       onChange: ({ file, fileList }:{file:any,fileList:any}) => {
        //         if (file.status == 'done') {
        //           importUserHandle(file.originFileObj);
        //         }
        //       },
        //       showUploadList: false,
        //     }}
        //   />,
        //   <Button key="2" onClick={() => getUserTemplateHandle()}>
        //     模板下载
        //   </Button>,
        //   <Button key="3" onClick={addUserHandle}>
        //     新增用户
        //   </Button>,
        // ]}
        request={(params) => getUserData(params)}
      />
    </div>
  );
};

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