/*
 * @Author: your name
 * @Date: 2022-01-12 17:11:11
 * @LastEditTime: 2022-07-07 16:26:50
 * @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 } 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 } from '@/service/user';
import { randomString } from '@/utils';
import { TableActType } from '..';
import { Form } from 'antd';
import MenuEditer from '@/pages/platform/components/menuEditer/menu';
import { getPlatformDictionary } 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 [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);
  const [dataSource, setDataSource] = useState<DataSourceType[]>([]);

  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) => {
    console.log({ data });
    if (tableAct == TableActType.ADD) {
      dispatch &&
        dispatch({
          type: 'hospManageModel/postAddData',
          payload: data,
        });
    }

    if (
      tableAct == TableActType.EDIT ||
      tableAct == TableActType.EDITMENU ||
      tableAct == TableActType.BINDACCOUNT
    ) {
      dispatch &&
        dispatch({
          type: 'hospManageModel/postEditData',
          payload: data,
        });
    }
    return true;
  };

  const setModalTitle = () => {
    if (tableAct == TableActType.EDIT) {
      return '编辑院区';
    }
    if (tableAct == TableActType.ADD) {
      return '新增院区';
    }
    if (tableAct == TableActType.EDITMENU) {
      return '绑定菜单';
    }
    if (tableAct == TableActType.BINDACCOUNT) {
      return '院区报告设置';
    }
  };

  const setInitialValues = () => {
    if (tableAct == TableActType.EDIT) {
      return {
        ...currentEdit,
        isDataShare: currentEdit?.dataShare == '是' ? 1 : 0,
      };
    }
    if (tableAct == TableActType.ADD) {
      return { hospSign: randomString(16), isDataShare: 0 };
    }
    if (tableAct == TableActType.EDITMENU) {
      return { ...currentEdit };
    }

    if (tableAct == TableActType.BINDACCOUNT) {
      if (currentEdit?.reportId) {
        return { ...currentEdit, reportId: parseInt(currentEdit.reportId) };
      }
    }
  };

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

  return (
    <KCModal
      visible={isShowModal}
      onVisibleChange={onVisibleChangeHandle}
      layout="horizontal"
      width={600}
      initialValues={setInitialValues()}
      title={setModalTitle()}
      labelCol={{
        span: 6,
      }}
      wrapperCol={{ span: 12 }}
      onFinish={async (data) =>
        onFinishHandle(tableAct == TableActType.BINDACCOUNT ? { ...data, dataSource } : data)
      }
    >
      {tableAct == TableActType.EDITMENU && (
        <Form.Item name="bindMenuIds">
          <MenuEditer />
        </Form.Item>
      )}

      {tableAct != TableActType.EDITMENU && tableAct != TableActType.BINDACCOUNT && (
        <>
          <ProFormText
            width="md"
            name="hospName"
            label="医院名称"
            placeholder="请输入"
            rules={[
              {
                required: true,
                message: '请输入医院名称!',
              },
            ]}
          />
          <KCProSelect
            label="是否主院"
            width="md"
            name="isHospital"
            options={[
              {
                value: 1,
                label: '否',
              },
              {
                value: 0,
                label: '是',
              },
            ]}
            rules={[
              {
                required: true,
                message: '请选择!',
              },
            ]}
          />
          <ProFormDependency name={['isHospital']}>
            {({ isHospital }) => {
              if (isHospital && isHospital == 1) {
                return (
                  <KCProSelect
                    label="选择主院"
                    width="md"
                    name="mainHospId"
                    request={async () => {
                      const hospList = await getHospList();
                      if (hospList) {
                        return hospList.map((t) => ({
                          label: t.name,
                          value: t.id,
                        }));
                      }
                      return [];
                    }}
                    rules={[
                      {
                        required: true,
                        message: '请选择院区!',
                      },
                    ]}
                  />
                );
              }
            }}
          </ProFormDependency>
          <KCProSelect
            label="医院等级"
            width="md"
            name="hospitalLevel"
            request={async () => {
              const resp = await getPlatformDictionary('HOSPITAL_LEVEL');
              if (resp) {
                return resp[0].dataVoList.map((t) => ({
                  label: t.code,
                  value: t.value,
                }));
              }
              return [];
            }}
            rules={[
              {
                required: true,
                message: '请选择!',
              },
            ]}
          />
          <KCProSelect
            label="医院类型"
            width="md"
            name="hospitalType"
            request={async () => {
              const resp = await getPlatformDictionary('HOSPITAL_TYPE');
              if (resp) {
                return resp[0].dataVoList.map((t) => ({
                  label: t.code,
                  value: t.value,
                }));
              }
              return [];
            }}
            rules={[
              {
                required: true,
                message: '请选择!',
              },
            ]}
          />
          <KCProSelect
            label="医院性质"
            width="md"
            name="hospitalNature"
            request={async () => {
              const resp = await getPlatformDictionary('HOSPITAL_NATURE');
              if (resp) {
                return resp[0].dataVoList.map((t) => ({
                  label: t.code,
                  value: t.value,
                }));
              }
              return [];
            }}
            rules={[
              {
                required: true,
                message: '请选择!',
              },
            ]}
          />
          
          <ProFormText width="md" name="hospSign" label="医院标识" disabled />
          <ProFormText width="md" name="hospAbbreviation" label="简称" placeholder="请输入" />
          <ProFormText width="md" name="hospitalCode" label="编码" placeholder="请输入" />
          <ProFormText width="md" name="systemName" label="系统名称" placeholder="请输入" />
          <ProFormRadio.Group
            name="isDataShare"
            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}
            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;
