/*
 * @Author: your name
 * @Date: 2022-01-12 17:11:11
 * @LastEditTime: 2023-09-28 11:21:22
 * @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 } from 'umi';
import { ProFormDateTimePicker, ProFormDependency, ProFormRadio, ProFormSelect, ProFormText, ProFormTextArea } from '@ant-design/pro-form';
import { getShareHospList } from '@/service/hospList';
import { AddUsersDataType, getUserRelaSeletData, 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';

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 [avatarUrl, setAvatarUrl] = useState<string>('');
  const [loadAvatar, setLoadAvatar] = useState(false);

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

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

      setLoadAvatar(true);

      if (info.file.status !== 'uploading') {
        // console.log(info.file, info.fileList);
        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) => {
    console.log({data});
    if (tableAct == TableActType.ADD) {
      dispatch &&
        dispatch({
          type: 'userManageModel/postAddUserData',
          payload: data,
        });
    }

    if (tableAct == TableActType.EDIT) {
      dispatch &&
        dispatch({
          type: 'userManageModel/postEditUserData',
          payload: data,
        });
    }

    return true;
  };

  const getDirecData = async (key?: string) => {

    const data = await getUserRelaSeletData(key);
    if (data) {
      set_dirData(data);
    }
  }

  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(() => {
    getDirecData();
  }, [])

  return (
    <KCModal
      width={720}
      visible={isShowModal}
      onVisibleChange={onVisibleChangeHandle}
      layout='vertical'
      className='ProfileModal'
      initialValues={
        tableAct == TableActType.EDIT ? { ...currentEditUser,departmentId:{label:currentEditUser?.departmentName,value:currentEditUser?.departmentId} } : {
          //设置当新增时的默认值
          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: 0,
                      },
                      {
                        label: '否',
                        value: 1,
                      },
                    ]}
                    rules={[{ required: true, message: '请选择专业!' }]}
                  />
                </div>

                <div className='formItem'>
                  <ProFormSelect
                    name="position"
                    label="岗位："
                    fieldProps={{ showSearch:true}}
                    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="性别："
                    options={[
                      { label: '男', value: 1 },
                      { label: '女', value: 2 },
                    ]}
                    placeholder="请选择"
                    rules={[{ required: true, message: '请选择性别!' }]}
                  />
                </div>
                <div className='formItem'>
                  <KCProSelect
                    label="所属院区："
                    width="md"
                    name="hospId"
                    fieldProps={{ showSearch:true}}
                    request={async () => {
                      const hospList = await getShareHospList();
                      if (hospList) {
                        return hospList.map((t) => ({
                          label: t.name,
                          value: t.id,
                        }));
                      }
                      return [];
                    }}
                    rules={[
                      {
                        required: true,
                        message: '请选择院区!',
                      },
                    ]}
                  />
                </div>
                <div className='formItem'>
                  <ProFormSelect
                    name="departmentId"
                    label="科室："
                    request={async () => {
                      const resp = await getDepartmentData({pageSize:1000});
                      if(resp){
                        return resp.list.map(a=>({label:a.name,value:a.id})) 
                      }
                      return [];
                     }}
                     fieldProps={{
                        labelInValue:true,
                        showSearch:true
                     }}
                    placeholder="请选择"
                  />
                </div>
                <div className='formItem'>
                  <ProFormSelect
                    name="userCate"
                    label="人员类别："
                    fieldProps={{ showSearch:true}}
                    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}}
                    options={setSelectorData('TITLE_TYPE').list}
                    placeholder="请选择"
                    rules={[{ required: true, message: '请选择职称!' }]}
                  />
                </div>
                <div className='formItem'>
                  <ProFormSelect
                    name="jobTitle"
                    label="职务："
                    fieldProps={{ showSearch:true}}
                    options={setSelectorData('POSITION_TYPE').list}
                    placeholder="请选择"
                    rules={[{ required: true, message: '请选择职务!' }]}
                  />
                </div>
                <ProFormDependency name={['isOnService']}>
                  {({ isOnService }) => (
                    <div className='formItem'>
                      <ProFormDateTimePicker disabled={isOnService == 0} 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}}
                    options={setSelectorData('EDUCATION').list}
                    placeholder="请选择"
                    rules={[{ required: true, message: '请选择学历!' }]}
                  />
                </div>

                <div className='formItem'>
                  <ProFormSelect
                    name="major"
                    label="所学专业："
                    fieldProps={{ showSearch:true}}
                    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="手机号：" placeholder="请输入" />
                </div>


                <ProFormDependency name={['userCate']}>
                  {({ userCate }) => (userCate == 6 || userCate == 5) && (
                    <div className='formItem' style={{ position: 'relative', left: -175 }}>
                      <ProFormSelect
                        name="practiceCate"
                        label="执业类别："
                        fieldProps={{ showSearch:true}}
                        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}}
                        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}}
                        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="医师："
                        fieldProps={{ showSearch:true}}
                        options={setSelectorData('PHYSICIAN_TYPE').list}
                        placeholder="请选择"
                        rules={[{ required: true, message: '请选择!' }]}
                      />
                    </div>
                  )}
                </ProFormDependency>

              </div>
            </div>

            <div style={{ display: 'flex', flexDirection: 'row', width: '100%' }}>
              <ProFormTextArea
                label='备注'
                name="remark"
                width={688}
                placeholder="请输入备注"
              />
            </div>


          </div>
        ) : ''
      }



    </KCModal>
  );
};

export default ActModal;
