/*
 * @Author: your name
 * @Date: 2022-01-12 17:11:11
 * @LastEditTime: 2024-12-09 15:54:33
 * @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, useRef, useState } from 'react';
import KCModal from '@/components/KCModal';
import KCProSelect from '@/components/KCProSelect';
import { hospManageModelState, Dispatch, useModel } from 'umi';

import { ProFormText, ProFormRadio, ProFormDependency, ProFormDigit } from '@ant-design/pro-form';
import type { ProColumns } from '@ant-design/pro-table';
import { EditableProTable } from '@ant-design/pro-table';
import { getHospList, getHospYoushuAccounts, getMainHosp, YoushuAccountsType } from '@/service/hospList';
import type { AddUsersDataType, UserRelaSeletDataListType } from '@/service/user';
import { randomString } from '@/utils';
import { TableActType } from '..';
import { Form } from 'antd';
import MenuEditer from '@/pages/platform/components/menuEditer/menu';
import { getPlatformDictionary, PlatformPubDirDataType } from '@/service/dictionary';

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

type DataSourceType = YoushuAccountsType & { key: number };

const ActModal: React.FC<ActModalProps> = ({ dispatch, isShowModal, tableAct, currentEdit }) => {
  const { initialState,setInitialState } = useModel('@@initialState');
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);
  const [dataSource, setDataSource] = useState<DataSourceType[]>([]);

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

  const columns: ProColumns<DataSourceType>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      key: 'id',
      hideInTable: true,
    },
    {
      title: '账号',
      dataIndex: 'account',
      key: 'account',
    },
    {
      title: '密码',
      key: 'password',
      dataIndex: 'password',
    },
    {
      title: '是否默认',
      dataIndex: 'isDefault',
      valueType: 'select',
      request: async () => [
        {
          value: 1,
          label: '是',
        },
        {
          value: 0,
          label: '否',
        },
      ],
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      width: 120,
      render: (text, record, _, action) => [
        <a
          key="delete"
          onClick={() => {
            setDataSource(dataSource.filter((item) => item.key !== record.key));
          }}
        >
          删除
        </a>,
      ],
    },
  ];

  const onVisibleChangeHandle = (bool: boolean) => {
    if (!bool) {
      dispatch &&
        dispatch({
          type: 'hospManageModel/cancelTableAct',
        });
    }
  };

  const onFinishHandle = (data: any & AddUsersDataType) => {
    if (tableAct == TableActType.ADD) {
      dispatch &&
        dispatch({
          type: 'hospManageModel/postAddData',
          payload: data,
        });
    }

    if (tableAct == TableActType.EDIT || tableAct == TableActType.BINDACCOUNT) {
      console.log({ data });

      dispatch &&
        dispatch({
          type: 'hospManageModel/postEditData',
          payload:
            tableAct == TableActType.EDIT
              ? {
                  ...data,
                  parentId: data.isHospital ? data.parentId.value : undefined,
                  parentName: data.isHospital ? data.parentId.label : '-',
                }
              : data,
        });
    }
    return true;
  };

  const setModalTitle = () => {
    if (tableAct == TableActType.EDIT) {
      return initialState?.customerType == '2'?'编辑园区':'编辑院区';
    }
    if (tableAct == TableActType.ADD) {
      return initialState?.customerType == '2'?'新增园区':'新增院区';
    }
    if (tableAct == TableActType.BINDACCOUNT) {
      return initialState?.customerType == '2'?'园区报告设置':'院区报告设置';
    }
  };

  const setInitialValues: any = () => {
    if (tableAct == TableActType.EDIT) {
      return {
        ...currentEdit,
        parentId: currentEdit?.parentId,
        parentName: currentEdit?.parentName,
        isDataShare: currentEdit?.dataShare == '是' ? 1 : 0,
      };
    }
    if (tableAct == TableActType.ADD) {
      return {
        hospSign: randomString(16),
        isDataShare: 0,
        hospitalLevel: setSelectorData('HOSPITAL_LEVEL').defaultvalue,
        hospitalType: setSelectorData('HOSPITAL_TYPE').defaultvalue,
        hospitalNature: setSelectorData('HOSPITAL_NATURE').defaultvalue,
      };
    }
    if (tableAct == TableActType.BINDACCOUNT) {
      if (currentEdit?.reportId) {
        return { ...currentEdit, reportId: parseInt(currentEdit.reportId) };
      }
    }
  };

  const getDirecData = async (key?: string) => {
    const data = await getPlatformDictionary();
    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: any, next: any) => {
        return prev.sort - next.sort;
      });

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

  useEffect(() => {
    //加装key字段
    const fixedDataSource = currentEdit?.youshuUsers
      ? currentEdit.youshuUsers.map((t) => ({
          ...t,
          key: Number((Math.random() * 1000000).toFixed(0)),
        }))
      : [];
    setDataSource(fixedDataSource);
  }, [currentEdit]);

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

  return (
    <KCModal
      visible={isShowModal}
      onVisibleChange={onVisibleChangeHandle}
      layout="horizontal"
      width={480}
      initialValues={setInitialValues()}
      title={setModalTitle()}
      labelCol={{
        span: 5,
      }}
      wrapperCol={{ span: 12 }}
      onFinish={async (data) => onFinishHandle(tableAct == TableActType.BINDACCOUNT ? { ...data, dataSource } : data)}
    >
      {tableAct != TableActType.BINDACCOUNT && (
        <>
          <ProFormText
            width="md"
            name="hospName"
            label={initialState?.customerType == '2'?'园区名称':'医院名称'}
            placeholder="请输入"
            rules={[
              {
                required: true,
                message: initialState?.customerType == '2'?'请输入园区名称!':'请输入医院名称!',
              },
            ]}
          />
          <KCProSelect
            label={initialState?.customerType == '2'?'是否主园区':'是否主院'}
            width="md"
            name="isHospital"
            fieldProps={{size:'small'}}
            options={[
              {
                value: 1,
                label: '否',
              },
              {
                value: 0,
                label: '是',
              },
            ]}
            rules={[
              {
                required: true,
                message: '请选择!',
              },
            ]}
          />
          <ProFormDependency name={['isHospital']}>
            {({ isHospital }) => {
              if (isHospital && isHospital == 1) {
                return (
                  <KCProSelect
                    label={initialState?.customerType == '2'?'选择主园区':'选择主院'}
                    width="md"
                    name="parentId"
                    fieldProps={{
                      size:'small',
                      labelInValue: true,
                    }}
                    request={async () => {
                      const hospList: any[] = await getHospList();
                      if (hospList) {
                        return hospList.map((t: any) => ({
                          label: t.name,
                          value: t.id,
                        }));
                      }
                      return [];
                    }}
                    rules={[
                      {
                        required: true,
                        message: initialState?.customerType == '2'?'请选择园区!':'请选择院区!',
                      },
                    ]}
                  />
                );
              }
            }}
          </ProFormDependency>
          <KCProSelect
            label={initialState?.customerType == '2'?'园区等级':'医院等级'}
            width="md"
            name="hospitalLevel"
            request={async () => {
              return setSelectorData('HOSPITAL_LEVEL').list;
            }}
            fieldProps={{ showSearch: true,size:'small' }}
            rules={[
              {
                required: true,
                message: '请选择!',
              },
            ]}
          />
          <KCProSelect
            label={initialState?.customerType == '2'?'园区类型':'医院类型'}
            width="md"
            name="hospitalType"
            request={async () => {
              return setSelectorData('HOSPITAL_TYPE').list;
            }}
            fieldProps={{ showSearch: true,size:'small' }}
            rules={[
              {
                required: true,
                message: '请选择!',
              },
            ]}
          />
          <KCProSelect
            label={initialState?.customerType == '2'?'园区性质':'医院性质'}
            width="md"
            name="hospitalNature"
            request={async () => {
              return setSelectorData('HOSPITAL_NATURE').list;
            }}
            fieldProps={{ showSearch: true,size:'small' }}
            rules={[
              {
                required: true,
                message: '请选择!',
              },
            ]}
          />

          <ProFormText width="md" name="hospSign" label={initialState?.customerType == '2'?'园区标识':'医院标识'} disabled />
          <ProFormText
            width="md"
            name="hospAbbreviation"
            label="简称"
            placeholder="请输入"
            rules={[
              {
                required: true,
              },
            ]}
          />

          <ProFormText
            width="md"
            name="systemName"
            label="系统名称"
            placeholder="请输入"
            rules={[
              {
                required: true,
              },
            ]}
          />
          <ProFormText width="md" name="hospitalCode" label="编码" placeholder="请输入" />
          <ProFormRadio.Group
            name="isDataShare"
            label="是否数据分享"
            options={[
              {
                label: '是',
                value: 1,
              },
              {
                label: '否',
                value: 0,
              },
            ]}
          />
          <ProFormRadio.Group
            name="loadType"
            label="登陆模式"
            options={[
              {
                label: '简易',
                value: 1,
              },
              {
                label: '普通',
                value: 0,
              },
            ]}
          />
        </>
      )}
      {tableAct == TableActType.BINDACCOUNT && (
        <>
          <ProFormText
            width="md"
            name="reportUrl"
            label="报告请求地址"
            placeholder="请输入"
            rules={[
              {
                required: true,
                message: '请输入!',
              },
            ]}
          />
          <ProFormDigit
            label="报告项目Id"
            name="reportId"
            min={0}
            width={328}
            fieldProps={{ precision: 0 }}
            rules={[
              {
                required: true,
                message: '请输入!',
              },
            ]}
          />
          <EditableProTable<DataSourceType>
            rowKey="key"
            headerTitle="院区[有数]账号绑定"
            columns={columns}
            value={dataSource}
            recordCreatorProps={{
              record: {
                key: Number((Math.random() * 1000000).toFixed(0)),
                id: -1,
                userName: '',
                account: '',
                password: '',
                isDefault: 0,
              },
            }}
            onChange={setDataSource}
            editable={{
              // type: 'multiple',
              deletePopconfirmMessage: '确定删除此行？',
              editableKeys,
              onChange: setEditableRowKeys,
            }}
          />
        </>
      )}
    </KCModal>
  );
};

export default ActModal;
