/*
 * @Author: your name
 * @Date: 2022-01-12 17:11:11
 * @LastEditTime: 2025-02-24 10:52:46
 * @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/setting/userManage/modal.tsx
 */

import React, { useEffect, useState } from 'react';
import KCModal from '@/components/KCModal';
import KCProSelect from '@/components/KCProSelect';
import { message, Button, Spin, Upload, UploadProps } from 'antd';
import { userManageModelState, Dispatch, useModel } from 'umi';
import { ProFormDateTimePicker, ProFormDependency, ProFormRadio, ProFormSelect, ProFormText, ProFormTextArea } from '@ant-design/pro-form';
import { getShareHospList } from '@/service/hospList';
import { AddUsersDataType, getUserRelaSeletData, uploadAvatar, UserRelaSeletDataListType, UserRelaSeletDataType } from '@/service/user';
import { LoadingOutlined, PlusOutlined, UploadOutlined } from '@ant-design/icons';
// import { TableActType } from "./typings";

import './style.less';
import { getDepartmentData } from '../departmentMana/service';
import { getSysParamsByCode } from '@/service';
import { getDictByDictTypeAndSysid } from '@/service/dictionary';
import { KcimCenterSysId } from '@/constant';
import { checkRoleTagsIsObjArr } from '../roleManage/modals/modal';

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

interface ActModalProps extends userManageModelState {
  dispatch: Dispatch | undefined;
}

const antIcon = <LoadingOutlined style={{ fontSize: 24 }} spin />;

const ActModal: React.FC<ActModalProps> = ({ dispatch, isShowModal, tableAct, currentEditUser }) => {
  const { initialState, setInitialState } = useModel('@@initialState');
  const [avatarUrl, setAvatarUrl] = useState<string>('');
  const [loadAvatar, setLoadAvatar] = useState(false);
  const [ifCheckPhoneNumber, set_ifCheckPhoneNumber] = useState(false);

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

  const props: UploadProps = {
    name: 'file',
    maxCount: 1,
    showUploadList: false,
    onChange: async (info: { file: any; fileList: any }) => {
      setLoadAvatar(true);

      if (info.file.status !== 'uploading') {
        const form = new FormData();
        form.append('file', info.file.originFileObj);
        const resp = await uploadAvatar(form);
        if (resp) {
          setAvatarUrl(resp);
        }
        // const reader = new FileReader();
        // reader.readAsDataURL(info.file.originFileObj); //读取图像文件 result 为 DataURL, DataURL 可直接 赋值给 img.src
        // reader.onload = function (event) {
        //   if (event.target && typeof event.target.result == 'string') {
        //     setAvatarUrl(event.target.result); //base64
        //   }
        // };
      }
      if (info.file.status === 'done') {
        setLoadAvatar(false);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 上传失败！`);
      }
    },
  };

  const onVisibleChangeHandle = (bool: boolean) => {
    // console.log({bool});
    if (!bool) {
      setAvatarUrl('');
      dispatch &&
        dispatch({
          type: 'userManageModel/cancelTableAct',
        });
    }
  };

  const onFinishHandle = (data: any & AddUsersDataType) => {
    try {
      if (tableAct == TableActType.ADD) {
        dispatch &&
          dispatch({
            type: 'userManageModel/postAddUserData',
            payload: { ...data, avatarUrl: avatarUrl, tagList: data.tagList?.map((a: any) => ({ tagCode: a.value, tagName: a.label })) },
          });
      }

      if (tableAct == TableActType.EDIT) {
        dispatch &&
          dispatch({
            type: 'userManageModel/postEditUserData',
            payload: {
              ...data,
              avatarUrl: avatarUrl,
              tagList: checkRoleTagsIsObjArr(data.tagList) ? data.tagList.map((a: any) => ({ tagCode: a.value, tagName: a.label })) : currentEditUser?.tagList,
            },
          });
      }
    } catch (error) {
      console.log('onFinishHandleError', error);
    }
    // console.log({ data });

    return true;
  };

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

  const getSystemParams = async () => {
    const resp = await getSysParamsByCode('1547394914533380096', '1861339521505955840');
    if (resp) {
      const needItem = resp.filter((a: any) => a.code == '1861339521505955840');
      if (needItem.length > 0) {
        set_ifCheckPhoneNumber(needItem[0].value == '0' ? false : true);
      }
    }
  };

  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: [],
    };
  };

  const uploadButton = (
    <div>
      {loadAvatar ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>上传头像</div>
    </div>
  );

  useEffect(() => {
    setAvatarUrl(currentEditUser ? currentEditUser.avatarUrl : '');
  }, [currentEditUser]);
  useEffect(() => {
    getDirecData();
    getSystemParams();
  }, []);

  return (
    <KCModal
      width={720}
      visible={isShowModal}
      onVisibleChange={onVisibleChangeHandle}
      layout="vertical"
      className="ProfileModal"
      initialValues={
        tableAct == TableActType.EDIT
          ? { ...currentEditUser, departmentId: { label: currentEditUser?.departmentName, value: currentEditUser?.departmentId }, tagList: currentEditUser?.tagList?.map((a: any) => a.tagCode) ?? [] }
          : {
              //设置当新增时的默认值
              major: setSelectorData('PROFESSIONAL_TYPE').defaultvalue,
              jobTitle: setSelectorData('POSITION_TYPE').defaultvalue,
              doctorLevel: setSelectorData('PHYSICIAN_TYPE').defaultvalue,
              practiceSubject: setSelectorData('PROCESSIONAL_SUBJECTS_TYPE').defaultvalue,
              title: setSelectorData('TITLE_TYPE').defaultvalue,
              practiceCate: setSelectorData('JOB_TYPE').defaultvalue,
              practiceStatus: setSelectorData('PROFESSIONAL_STATUS_TYPE').defaultvalue,
              position: setSelectorData('POSITION').defaultvalue,
              departmentId: setSelectorData('PRACTICE_DEPARTMENT_TYPE').defaultvalue,
              userCate: setSelectorData('PERSONNEL_CATEGORY').defaultvalue,
              degree: setSelectorData('EDUCATION').defaultvalue,
            }
      }
      title={tableAct == TableActType.EDIT ? '编辑用户' : '新增用户'}
      // labelCol={{ span: 5 }}
      // wrapperCol={{ span:8 }}
      onFinish={async (data) => onFinishHandle({ ...data, departmentId: data.departmentId.value, departmentName: data.departmentId.label })}
    >
      {dirData ? (
        <div>
          <div className="wraper">
            <div className="left">
              <span style={{ fontSize: 14, color: '#17181A', marginBottom: 3, display: 'block' }}>照片：</span>
              <div className="avatarContainer">
                <Upload
                  // name="avatar"
                  listType="picture-card"
                  showUploadList={false}
                  {...props}
                >
                  {avatarUrl ? <img src={avatarUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
                </Upload>
              </div>

              <div className="formItem">
                <ProFormRadio.Group
                  name="isOnService"
                  label="在职："
                  options={[
                    {
                      label: '是',
                      value: 1,
                    },
                    {
                      label: '否',
                      value: 0,
                    },
                  ]}
                  rules={[{ required: true, message: '请选择专业!' }]}
                />
              </div>

              <div className="formItem">
                <ProFormSelect
                  name="position"
                  label="岗位："
                  fieldProps={{ showSearch: true, size: 'small' }}
                  options={setSelectorData('POSITION').list}
                  placeholder="请选择"
                  rules={[{ required: true, message: '请选择!' }]}
                />
              </div>
            </div>
            <div className="right">
              <div className="formItem">
                <ProFormText name="name" label="姓名：" placeholder="请输入" rules={[{ required: true, message: '请输入姓名!' }]} />
              </div>
              <div className="formItem">
                <ProFormText name="account" label="工号：" placeholder="请输入" rules={[{ required: true, message: '请输入工号!' }]} />
              </div>
              <div className="formItem">
                <ProFormSelect
                  name="gender"
                  label="性别："
                  fieldProps={{ size: 'small' }}
                  options={[
                    { label: '男', value: 1 },
                    { label: '女', value: 2 },
                  ]}
                  placeholder="请选择"
                  rules={[{ required: true, message: '请选择性别!' }]}
                />
              </div>
              <div className="formItem">
                <KCProSelect
                  label={initialState?.customerType == '2' ? '所属园区：' : '所属院区：'}
                  width="md"
                  name="hospId"
                  fieldProps={{ showSearch: true, size: 'small' }}
                  request={async () => {
                    const hospList = await getShareHospList();
                    if (hospList) {
                      return hospList.map((t) => ({
                        label: t.name,
                        value: t.id,
                      }));
                    }
                    return [];
                  }}
                  rules={[
                    {
                      required: true,
                      message: initialState?.customerType == '2' ? '请选择园区！' : '请选择院区!',
                    },
                  ]}
                />
              </div>
              <div className="formItem">
                <ProFormSelect
                  name="departmentId"
                  label={initialState?.customerType == '2' ? '组织：' : '科室：'}
                  request={async () => {
                    const resp = await getDepartmentData({ pageSize: 1000 });
                    if (resp) {
                      return resp.list.map((a) => ({ label: a.name, value: a.code }));
                    }
                    return [];
                  }}
                  fieldProps={{
                    size: 'small',
                    labelInValue: true,
                    showSearch: true,
                  }}
                  placeholder="请选择"
                />
              </div>
              <div className="formItem">
                <ProFormSelect
                  name="userCate"
                  label={initialState?.customerType == '2' ? '员工类别：' : '人员类别：'}
                  fieldProps={{ showSearch: true, size: 'small' }}
                  options={setSelectorData('PERSONNEL_CATEGORY').list}
                  placeholder="请选择"
                />
              </div>

              <div className="formItem">
                <ProFormDateTimePicker name="entryTime" label="入职时间" placeholder={'请选择日期'} rules={[{ required: true, message: '请选择日期!' }]} />
              </div>
              <div className="formItem">
                <ProFormSelect
                  name="title"
                  label="职称："
                  fieldProps={{ showSearch: true, size: 'small' }}
                  options={setSelectorData('TITLE_TYPE').list}
                  placeholder="请选择"
                  rules={[{ required: true, message: '请选择职称!' }]}
                />
              </div>
              <div className="formItem">
                <ProFormSelect
                  name="jobTitle"
                  label="职务："
                  fieldProps={{ showSearch: true, size: 'small' }}
                  options={setSelectorData('POSITION_TYPE').list}
                  placeholder="请选择"
                  rules={[{ required: true, message: '请选择职务!' }]}
                />
              </div>
              <ProFormDependency name={['isOnService']}>
                {({ isOnService }) => (
                  <div className="formItem">
                    <ProFormDateTimePicker disabled={isOnService == 1} label="离职日期：" name="outTime" placeholder={'请选择离职时间'} />
                  </div>
                )}
              </ProFormDependency>

              <div className="formItem">
                <ProFormText name="graduateSchool" label="毕业院校：" placeholder="请输入" rules={[{ required: false, message: '请输入院校!' }]} />
              </div>

              <div className="formItem">
                <ProFormSelect
                  name="degree"
                  label="学历："
                  fieldProps={{ showSearch: true, size: 'small' }}
                  options={setSelectorData('EDUCATION').list}
                  placeholder="请选择"
                  rules={[{ required: true, message: '请选择学历!' }]}
                />
              </div>

              <div className="formItem">
                <ProFormSelect
                  name="major"
                  label="所学专业："
                  fieldProps={{ showSearch: true, size: 'small' }}
                  options={setSelectorData('PROFESSIONAL_TYPE').list}
                  placeholder="请选择"
                  rules={[{ required: true, message: '请选择专业!' }]}
                />
              </div>

              <div className="formItem">
                <ProFormText name="idCardNum" label="身份证号：" placeholder="请输入" rules={[{ required: false, message: '请选择!' }]} />
              </div>

              <div className="formItem">
                <ProFormText
                  name="phoneNumber"
                  label={initialState?.customerType == '2' ? '联系电话：' : '联系电话：'}
                  placeholder="请输入"
                  rules={
                    ifCheckPhoneNumber
                      ? [
                          {
                            required: true,
                            message: <span style={{ fontSize: 12, paddingLeft: 50 }}>请输入联系电话</span>,
                          },
                          {
                            pattern: /^1[3-9]\d{9}$/,
                            message: <span style={{ fontSize: 12, paddingLeft: 50 }}>手机号格式不正确</span>,
                          },
                          // ({ getFieldValue }) => ({
                          //   validator(_, value) {
                          //     if (!value || value.length === 11) {
                          //       return Promise.resolve();
                          //     }
                          //     return Promise.reject(new Error("手机号必须是11位"));
                          //   },
                          // }),
                        ]
                      : [
                          {
                            required: false,
                            message: '请输入',
                          },
                        ]
                  }
                />
              </div>

              <ProFormDependency name={['userCate']}>
                {({ userCate }) =>
                  (userCate == 6 || userCate == 5) && (
                    <div className="formItem" style={{ position: 'relative', left: -175 }}>
                      <ProFormSelect name="practiceCate" label="执业类别：" fieldProps={{ showSearch: true, size: 'small' }} options={setSelectorData('JOB_TYPE').list} placeholder="请选择" />
                    </div>
                  )
                }
              </ProFormDependency>

              <ProFormDependency name={['userCate']}>
                {({ userCate }) =>
                  (userCate == 6 || userCate == 5) && (
                    <div className="formItem" style={{ position: 'relative', left: -175 }}>
                      <ProFormSelect
                        name="practiceSubject"
                        label="执业科目："
                        fieldProps={{ showSearch: true, size: 'small' }}
                        options={setSelectorData('PROCESSIONAL_SUBJECTS_TYPE').list}
                        placeholder="请选择"
                        rules={[{ required: true, message: '请选择!' }]}
                      />
                    </div>
                  )
                }
              </ProFormDependency>

              <ProFormDependency name={['userCate']}>
                {({ userCate }) =>
                  (userCate == 6 || userCate == 5) && (
                    <div className="formItem" style={{ position: 'relative', left: -175 }}>
                      <ProFormText name="practiceCertificateNo" label="执业证号：" placeholder="请输入" rules={[{ required: true, message: '请选择!' }]} />
                    </div>
                  )
                }
              </ProFormDependency>

              <ProFormDependency name={['userCate']}>
                {({ userCate }) =>
                  (userCate == 6 || userCate == 5) && (
                    <div className="formItem" style={{ position: 'relative', left: -175 }}>
                      <ProFormSelect
                        name="practiceStatus"
                        label="执业状态："
                        fieldProps={{ showSearch: true, size: 'small' }}
                        options={setSelectorData('PROFESSIONAL_STATUS_TYPE').list}
                        placeholder="请选择"
                        rules={[{ required: true, message: '请选择!' }]}
                      />
                    </div>
                  )
                }
              </ProFormDependency>

              <ProFormDependency name={['userCate']}>
                {({ userCate }) =>
                  (userCate == 6 || userCate == 5) && (
                    <div className="formItem" style={{ position: 'relative', left: -175 }}>
                      <ProFormText name="qualificationCertificateNo" label="资格证号：" placeholder="请输入" rules={[{ required: true, message: '请输入!' }]} />
                    </div>
                  )
                }
              </ProFormDependency>

              <ProFormDependency name={['userCate']}>
                {({ userCate }) =>
                  (userCate == 6 || userCate == 5) && (
                    <div className="formItem" style={{ position: 'relative', top: -62 }}>
                      <ProFormSelect
                        name="doctorLevel"
                        label={initialState?.customerType == '2' ? '执业级别：' : '医师级别：'}
                        fieldProps={{ showSearch: true, size: 'small' }}
                        options={setSelectorData('PHYSICIAN_TYPE').list}
                        placeholder="请选择"
                        rules={[{ required: true, message: '请选择!' }]}
                      />
                    </div>
                  )
                }
              </ProFormDependency>
            </div>
          </div>

          <div style={{ display: 'flex', flexDirection: 'row', width: '100%', justifyContent: 'space-between', alignItems: 'center' }}>
            <KCProSelect
              label={initialState?.customerType == '2' ? '人员标签：' : '人员标签：'}
              width={160}
              name="tagList"
              fieldProps={{
                size: 'small',
                labelInValue: true,
                mode: 'tags',
                maxTagCount: 'responsive',
              }}
              request={async () => {
                const resp = await getDictByDictTypeAndSysid(KcimCenterSysId, 'EMPLOYEE_LABEL_DIC');
                if (resp) {
                  return resp.dataVoList.map((t: any) => ({
                    label: t.name,
                    value: t.code,
                  }));
                }
                return [];
              }}
            />
            <ProFormTextArea
              fieldProps={{
                style: { border: '1px solid #cfd7e6', marginTop: '-5px' },
              }}
              label="备注"
              name="remark"
              width={512}
              placeholder="请输入备注"
            />
          </div>
        </div>
      ) : (
        ''
      )}
    </KCModal>
  );
};

export default ActModal;
