/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2025-05-13 16:51:44
 * @FilePath: /KC-MiddlePlatform/src/pages/platform/setting/pubDicTypeMana/index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

import { KCInput } from '@/components/KCInput';
import KCTable from '@/components/kcTable';
import KCUpload from '@/components/KCUpload';
import { getAllHosp } from '@/service/hospList';
import { downloadTemplateReq } from '@/utils';
import { ModalForm, ProFormSelect, ProFormText, ProFormTextArea } from '@ant-design/pro-form';
import { ProColumns } from '@ant-design/pro-table';
import { Divider, message, Modal, Popconfirm, Tooltip } from 'antd';
import FormItem from 'antd/lib/form/FormItem';
import { useEffect, useState } from 'react';
import { addData, delData, editData, getDepartmentData, getDepartmentType, getRelaHosp, importDepartmentData } from './service';

import './style.less';
import { useModel } from 'umi';
import KCProSelect from '@/components/KCProSelect';
import { getDictByDictTypeAndSysid } from '@/service/dictionary';
import { KcimCenterSysId } from '@/constant';
import { checkRoleTagsIsObjArr } from '../roleManage/modals/modal';

export default function DepartmentMana() {
  const { initialState, setInitialState } = useModel('@@initialState');
  const [tableDataFilterParams, set_tableDataFilterParams] = useState<{
    current: number;
    pageSize: number;
    name?: string;
  }>({
    current: 1,
    pageSize: 10
  });
  const [tableDataSearchKeywords, set_tableDataSearchKeywords] = useState<string>('');
  const [reload, set_reload] = useState(false);
  const [currentEdit, set_currentEdit] = useState<any>(undefined);

  const [types, set_types] = useState([]);

  const columns = [
    {
      title: initialState?.customerType == '2' ? '组织编码' : '科室代码',
      dataIndex: 'code',
    },
    {
      title: initialState?.customerType == '2' ? '组织名称' : '科室名称',
      dataIndex: 'name',
    },
    {
      title: initialState?.customerType == '2' ? '园区' : '院区',
      dataIndex: 'hospName',
    },
    {
      title: initialState?.customerType == '2' ? '组织类型' : '科室类型',
      dataIndex: 'type',
      valueType: 'select',
      fieldProps: {
        options: types,
      },
    },
    {
      title: initialState?.customerType == '2' ? '组织标签' : '科室标签',
      renderText(text: any, record: any) {
        const { tagList = [] } = record;
        return (
          <>
            {tagList.map((a: any, i: number) => (
              <span
                style={{
                  display: 'inline-flex',
                  padding: '2px 5px',
                  fontSize: 12,
                  background: '#EEF3FA',
                  borderRadius: 4,
                  color: '#525866',
                  marginRight: 4,
                }}
              >
                {a.tagName}
              </span>
            ))}
          </>
        );
      },
    },
    {
      title: '备注',
      dataIndex: 'remark',
    },
    {
      title: '操作',
      key: 'option',
      width: 120,
      valueType: 'option',
      render: (_: any, record: any) => {
        const getEditBtn = () => {
          const { isEdit } = record;
          if (!isEdit) {
            return [
              <UpDataActBtn key={'act'} record={record} type="EDIT" />,
              <Popconfirm title="是否确认删除？" key="del" onConfirm={() => delTableData(record)}>
                <a>删除</a>
              </Popconfirm>,
            ];
          } else {
            return [
              <Tooltip title="第三方科室不可编辑！">
                <span style={{ cursor: 'not-allowed', color: 'rgb(176 181 189)' }}>编辑</span>
              </Tooltip>,
              <Divider key="1" type="vertical" style={{ margin: '0 3px' }} />,
              <Tooltip title="第三方科室不可删除！">
                <span style={{ cursor: 'not-allowed', color: 'rgb(176 181 189)' }}>删除</span>
              </Tooltip>,
            ];
          }
        };
        return [
             ...(getEditBtn())
        ];
      },
    },
  ];

  const getTableData: any = async (params: any) => {
    const resp = await getDepartmentData(params);
    set_reload(false);
    if (resp) {
      return {
        data: resp.list,
        success: true,
        total: resp.totalCount,
        pageSize: resp.pageSize,
        totalPage: resp.totalPage,
      };
    }
    return [];
  };

  const delTableData = async (record: any) => {
    const resp = await delData(record.id);
    if (resp) {
      set_reload(true);
      // message.success('操作成功!');
    }
  };

  const updateTable = async (formVal: any, type: 'EDIT' | 'ADD') => {
    if (type == 'ADD') {
      const resp = await addData({ ...formVal, tagList: formVal.tagList.map((a: any) => ({ tagCode: a.value, tagName: a.label })) });
      if (resp) {
        set_reload(true);
      }
    }

    if (type == 'EDIT') {
      const resp = await editData({
        ...formVal,
        tagList: checkRoleTagsIsObjArr(formVal.tagList) ? formVal.tagList.map((a: any) => ({ tagCode: a.value, tagName: a.label })) : currentEdit?.tagList,
      });
      if (resp) {
        set_reload(true);
      }
    }
  };

  const UpDataActBtn = ({ record, type }: { record: any; type: 'EDIT' | 'ADD' }) => {
    if (type == 'EDIT') set_currentEdit(record);
    return (
      <ModalForm
        title={`${type == 'EDIT' ? '编辑' : '新增'}科室`}
        width={352}
        initialValues={type == 'EDIT' ? { ...record, tagList: record?.tagList?.map((a: any) => a.tagCode) ?? [] } : {}}
        trigger={
          type == 'EDIT' ? (
            <a key="edit">编辑</a>
          ) : (
            <span className="add" style={{ background: '#3377FF', color: '#fff' }}>
              新增
            </span>
          )
        }
        onFinish={(val) => {
          return updateTable(type == 'EDIT' ? { ...val, id: record.id } : val, type);
        }}
      >
        <ProFormText
          name="name"
          label={initialState?.customerType == '2' ? '组织名称：' : '科室名称：'}
          placeholder="请输入"
          rules={[{ required: true, message: initialState?.customerType == '2' ? '组织名称不能为空！' : '科室名称不能为空!' }]}
        />
        <ProFormText
          name="code"
          label={initialState?.customerType == '2' ? '组织编码：' : '科室代码：'}
          placeholder="请输入"
          rules={[{ required: true, message: initialState?.customerType == '2' ? '组织编码不能为空！' : '科室代码不能为空!' }]}
        />
        <ProFormSelect
          name="type"
          label={initialState?.customerType == '2' ? '组织类型：' : '科室类型：'}
          placeholder="请选择类型"
          fieldProps={{ size: 'small' }}
          rules={[{ required: true, message: '类型不能为空!' }]}
          request={async () => {
            return types;
          }}
        />
        <ProFormSelect
          name="hospId"
          label={initialState?.customerType == '2' ? '园区' : '院区：'}
          fieldProps={{ size: 'small' }}
          placeholder="请选择"
          rules={[{ required: true, message: initialState?.customerType == '2' ? '园区能为空!' : '院区不能为空!' }]}
          request={async () => {
            const resp = await getRelaHosp();
            if (resp) {
              const data: any = resp?.map((a: any) => ({
                label: a.name,
                value: a.id,
              }));

              return data;
            }
            return [];
          }}
        />
        <KCProSelect
          label={initialState?.customerType == '2' ? '组织标签：' : '科室标签：'}
          width="md"
          name="tagList"
          fieldProps={{
            size: 'small',
            labelInValue: true,
            mode: 'tags',
          }}
          request={async () => {
            const resp = await getDictByDictTypeAndSysid(KcimCenterSysId, 'ORGANIZATION_LABEL_DIC');
            if (resp) {
              return resp.dataVoList.map((t: any) => ({
                label: t.name,
                value: t.code,
              }));
            }
            return [];
          }}
        />
        <ProFormTextArea name="remark" label="说明：" placeholder="请输入" />
      </ModalForm>
    );
  };

  const handleTableChange = (pagination: any) => {
    set_tableDataFilterParams({
      ...tableDataFilterParams,
      current: pagination.current,
      pageSize: pagination.pageSize
    });
  }

  const tableDataSearchHandle = (paramName: string) => {
    set_tableDataFilterParams({
      ...tableDataFilterParams,
      current: 1,
      [`${paramName}`]: tableDataSearchKeywords
    });
  }

  const downloadTemplateFileHandle = async () => {
    await downloadTemplateReq('/centerSys/sysdepartment/export');
  };

  const importData = (name: string) => {
    return (
      <ModalForm
        title={`导入${name}数据`}
        width={352}
        trigger={<span key="3">导入</span>}
        onFinish={async (values) => {
          const {
            importFile: { fileList },
          } = values;

          let formData = new FormData();
          formData.append('file', fileList[0].originFileObj);
          const resp = await importDepartmentData(formData);

          if (resp) {
            set_reload(true);
            return true;
          }
        }}
      >
        <FormItem name={'importFile'}>
          <KCUpload downloadTemplateFile={() => downloadTemplateFileHandle()} />
        </FormItem>
      </ModalForm>
    );
  };

  const getAllDepartmentType = async () => {
    const resp = await getDepartmentType();
    if (resp) {
      const data: any = resp?.map((a) => ({
        label: a.name,
        value: a.code,
      }));
      set_types(data);
    }
  };

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

  return (
    <div className="DepartmentMana">
      <div className="toolBar">
        <div className="filter">
          <div className="filterItem" style={{ marginRight: 16 }}>
            <span className="label">类型：</span>
            {types.length > 0 && (
              <ProFormSelect
                name="type"
                noStyle
                style={{ width: 160 }}
                placeholder="请选择类型"
                rules={[{ required: true, message: '类型不能为空!' }]}
                request={async () => {
                  return types;
                }}
                fieldProps={{
                  size: 'small',
                  onChange: (e) => {
                    if (e) {
                      set_tableDataFilterParams({
                        ...tableDataFilterParams,
                        current: 1,
                        departType: e,
                      });
                    } else {
                      set_tableDataFilterParams({
                        ...tableDataFilterParams,
                        current: 1,
                        departType: '',
                      });
                    }
                  },
                }}
              />
            )}
          </div>
          <div className="filterItem">
            <span className="label">检索：</span>
            <KCInput
              placeholder={initialState?.customerType == '2' ? '请输入组织名称!' : '请输入科室名称'}
              style={{ width: 160 }}
              search
              allowClear
              onChange={(e) => {
                set_tableDataSearchKeywords(e.target.value);
                if (e.target.value.length == 0) {
                  set_tableDataFilterParams({
                    ...tableDataFilterParams,
                    current: 1,
                    departName: '',
                  });
                }
              }}
              onSearch={() => tableDataSearchHandle('departName')}
            />
          </div>
        </div>
        <div className="btnGroup">
          {importData(initialState?.customerType == '2' ? '组织' : '科室')}
          <UpDataActBtn record type="ADD" />
        </div>
      </div>
      <div style={{ marginTop: 16 }}>
        <KCTable
          columns={columns}
          scroll={{ y: `calc(100vh - 250px)` }}
          reload={reload}
          rowKey="id"
          newVer
          params={tableDataFilterParams}
          request={(params) => getTableData(params)}
          onChange={handleTableChange}
        />
      </div>
    </div>
  );
}
