/*
 * @Author: your name
 * @Date: 2022-01-12 17:11:11
 * @LastEditTime: 2022-07-08 18:00:41
 * @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 } from 'antd';
import { userManageModelState, Dispatch } from 'umi';
import { ProFormDateTimePicker, ProFormSelect, ProFormText, ProFormTextArea } from '@ant-design/pro-form';
import { getShareHospList } from '@/service/hospList';
import { AddUsersDataType, getUserRelaSeletData, UserRelaSeletDataListType, UserRelaSeletDataType } from '@/service/user';
import { LoadingOutlined, UploadOutlined } from '@ant-design/icons';
// import { TableActType } from "./typings";

import './style.less';

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[]>([]);

  // let dirData: UserRelaSeletDataType[] = []

  const props = {
    name: 'file',
    maxCount: 1,
    showUploadList: false,
    onChange(info: { file: { originFileObj: File, status: string; name: 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) {
      dispatch &&
        dispatch({
          type: 'userManageModel/cancelTableAct',
        });
    }
  };

  const onFinishHandle = (data: any & AddUsersDataType) => {
    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 next.sort - prev.sort;
      });

      // console.log({dataArr,defaultValue});

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

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

  return (
    <KCModal
      visible={isShowModal}
      onVisibleChange={onVisibleChangeHandle}
      layout="horizontal"
      className='ProfileModal'
      initialValues={
        tableAct == TableActType.EDIT ? { ...currentEditUser } : {
               //设置当新增时的默认值
               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
        }
      }
      title={tableAct == TableActType.EDIT ? '编辑用户' : '新增用户'}
      labelCol={{ span: 5 }}
      wrapperCol={{ span: 18 }}
      onFinish={async (data) => onFinishHandle(data)}
    >

      {
        dirData ? (
          <div>
            <div className='wraper'>
              <div className='left'>
                <div className='avatarContainer'>
                  <span>个人照片:</span>
                  <div className='avatar'>
                    {avatarUrl && <img src={avatarUrl} alt="avatar" />}
                    {loadAvatar && <Spin className='spin' indicator={antIcon} />}
                  </div>
                  <Upload {...props} className='UploadBtn'>
                    <Button icon={<UploadOutlined />}>上传照片(100*130)</Button>
                  </Upload>
                </div>
                <div className='formItem'>
                  <KCProSelect
                    label="院区"
                    width="md"
                    name="hospId"
                    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="major"
                    label="所学专业："
                    
                    options={(setSelectorData('PROFESSIONAL_TYPE')).list}
                    placeholder="请选择"
                    rules={[{ required: true, message: '请选择专业!' }]}
                  />
                </div>
                <div className='formItem'>
                  <ProFormSelect
                    name="jobTitle"
                    label="职务："
                    options={setSelectorData('POSITION_TYPE').list}
                    placeholder="请选择"
                    rules={[{ required: true, message: '请选择职务!' }]}
                  />
                </div>
                <div className='formItem'>
                  <ProFormText name="idCardNum" label="身份证号：" placeholder="请输入" />
                </div>
                <div className='formItem'>
                  <ProFormText name="phoneNum" label="手机号：" placeholder="请输入" />
                </div>
                <div className='formItem'>
                  <ProFormText name="qualificationCertificateNo" label="资格证号：" placeholder="请输入" />
                </div>
                <div className='formItem'>
                  <ProFormSelect
                    name="doctorLevel"
                    label="医师级别："
                    options={setSelectorData('PHYSICIAN_TYPE').list}
                    placeholder="请选择"
                  />
                </div>
                <div className='formItem'>
                  <ProFormSelect
                    name="practiceSubject"
                    label="执业科目："
                    options={setSelectorData('PROCESSIONAL_SUBJECTS_TYPE').list}
                    placeholder="请选择"
                  />
                </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="性别："
                    request={async () => [
                      { label: '男', value: '男' },
                      { label: '女', value: '女' },
                    ]}
                    placeholder="请选择"
                    rules={[{ required: true, message: '请选择性别!' }]}
                  />
                </div>
                <div className='formItem'>
                  <ProFormText name="text" label="科室：" placeholder="请输入" rules={[{ required: true, message: '请输入工号!' }]} />
                </div>
                <div className='formItem'>
                  <ProFormSelect
                    name="title"
                    label="职称："
                    options={setSelectorData('TITLE_TYPE').list}
                    placeholder="请选择"
                    rules={[{ required: true, message: '请选择职称!' }]}
                  />
                </div>
                <div className='formItem'>
                  <ProFormDateTimePicker name="entryTime" label="入职时间" placeholder={'请选择日期'} />
                </div>
                <div className='formItem'>
                  <ProFormText name="practiceCertificateNo" label="执业证号：" placeholder="请输入" />
                </div>
                <div className='formItem'>
                  <ProFormSelect
                    name="practiceCate"
                    label="执业类别："
                    options={setSelectorData('JOB_TYPE').list}
                    placeholder="请选择"
                  />
                </div>
                <div className='formItem'>
                  <ProFormSelect
                    name="practiceStatus"
                    label="执业状态："
                    options={setSelectorData('PROFESSIONAL_STATUS_TYPE').list}
                    placeholder="请选择"
                  />
                </div>
              </div>
            </div>

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

          </div>
        ) : ''
      }



    </KCModal>
  );
};

export default ActModal;
