/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2024-10-15 15:35:24
 * @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 KCIMPagecontainer from '@/components/KCIMPageContainer';
import { KCIMTable } from '@/components/KCIMTable';
import { formatMoneyNumber } from '@/utils/format';
import { createFromIconfontCN } from '@ant-design/icons';
import FormItem from 'antd/es/form/FormItem';

import {
  ActionType,
  DrawerForm,
  ProFormInstance,
  ProFormText,
  ProTable,
  TableDropdown,
} from '@ant-design/pro-components';
import {
  ModalForm,
  ProFormDigit,
  ProFormSelect,
  ProFormSwitch,
} from '@ant-design/pro-form';
import { ProColumns } from '@ant-design/pro-table';
import type { MenuProps } from 'antd';
import {
  Input,
  message,
  Dropdown,
  Modal,
  Popconfirm,
  Drawer,
  Breadcrumb,
} from 'antd';
import { useEffect, useRef, useState } from 'react';

import 'moment/locale/zh-cn';
import locale from 'antd/es/date-picker/locale/zh_CN';

import {
  addData,
  delData,
  editData,
  getAllNeedMatchItems,
  getDepartmentListsReq,
  getTableDataReq,
  importDataPost,
  mapItemAndStandItem,
} from './service';

import './style.less';
import KCIMUpload from '@/components/KCIMUpload';
import { downloadTemplateReq } from '@/utils/tooljs';
import { getStandItemList } from '../standardProjectMana/service';
import { getDicDataBySysId } from '@/services/getDic';
import { KcimCenterSysId } from '@/constant';
import { Setting } from './components/setting';
import KCIMDrawerForm from '@/components/KCIMDrawerForm';
import { MatchPage } from './components/match';

const IconFont = createFromIconfontCN({
  scriptUrl: '',
});

let currentRow: any = undefined;

export const fetchAllDepartments = async (params: any) => {
  const { keyWords } = params;
  let currentPage = 1;
  const pageSize = 500;
  let allDepartments: any[] = [];
  let hasMore = true;

  do {
    const resp = await getDepartmentListsReq({
      current: currentPage,
      pageSize,
      departName: keyWords,
    });
    if (resp) {
      const { list = [] } = resp;
      allDepartments = [...allDepartments, ...list];
      if (list.length < pageSize) {
        hasMore = false; // 如果返回的数据少于每页数量，说明已经是最后一页
      } else {
        currentPage++; // 否则继续请求下一页
      }
    } else {
      hasMore = false; // 如果请求失败，终止循环
    }
  } while (hasMore);

  return allDepartments.map((a: any) => ({
    label: `${a.name}(${a.code})`,
    value: a.code,
  }));
};

export default function ChargeItemsMana() {
  const [tableDataFilterParams, set_tableDataFilterParams] = useState<
    any | undefined
  >();
  const [tableDataSearchKeywords, set_tableDataSearchKeywords] =
    useState<string>('');
  const tableRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();
  const [stopStat, set_stopStat] = useState(0);
  const [drawerVisible, set_drawerVisible] = useState(false);
  const [drawerType, set_drawerType] = useState(1);
  const [currentSelectRow, set_currentSelectRow] = useState(undefined);
  const [ifBatchMatch, set_ifBatchMatch] = useState(false);
  const columns: ProColumns[] = [
    {
      title: '科室',
      dataIndex: 'departmentName',
      width: 160,
      renderText(text, record, index, action) {
        return `[${record.departmentCode}]${record.departmentName}`;
      },
    },
    {
      title: '收费项目编码',
      dataIndex: 'code',
      width: 100,
    },
    {
      title: '收费项目名称',
      dataIndex: 'name',
      width: 260,
    },
    {
      title: '国家编码',
      dataIndex: 'nationalCode',
      width: 100,
    },
    {
      title: '项目类别',
      dataIndex: 'type',
      width: 100,
    },
    {
      title: '项目分类',
      dataIndex: 'itemTypeName',
      width: 100,
    },
    {
      title: '康程分类',
      dataIndex: 'kcCodeName',
      width: 280,
    },
    {
      title: '标准项目编码',
      dataIndex: 'standItemCode',
      width: 100,
    },
    {
      title: '标准项目名称',
      dataIndex: 'standItemName',
      width: 260,
    },
    {
      title: '参与人员',
      dataIndex: 'empMaps',
      width: 260,
      renderText(arr, record, index, action) {
        if (arr)
          return arr.reduce(
            (prev: any, cur: any) =>
              `${prev.length > 0 ? prev + '|' : prev}${
                cur.empTypeCodeName + '*' + cur.num + '*' + cur.executeTime
              }`,
            '',
          );
      },
    },
    {
      title: '使用设备',
      dataIndex: 'equipmentMaps',
      width: 260,
      renderText(arr, record, index, action) {
        if (arr)
          return arr.reduce(
            (prev: any, cur: any) =>
              `${prev.length > 0 ? prev + '|' : prev}${
                cur.equipmentCodeName + '*' + cur.num + '*' + cur.executeTime
              }`,
            '',
          );
      },
    },
    {
      title: '使用空间',
      dataIndex: 'spaceMaps',
      width: 260,
      renderText(arr, record, index, action) {
        if (arr)
          return arr.reduce(
            (prev: any, cur: any) =>
              `${prev.length > 0 ? prev + '|' : prev}${
                cur.spaceCodeName + '*' + cur.num + '*' + cur.executeTime
              }`,
            '',
          );
      },
    },
    {
      title: '计价药材',
      dataIndex: 'valuation',
      width: 260,
      renderText(arr) {
        if (arr)
          return arr.reduce(
            (prev: any, cur: any) =>
              `${prev.length > 0 ? prev + '|' : prev}${
                cur.code + '*' + cur.name + '*' + cur.num
              }`,
            '',
          );
      },
    },
    {
      title: '不计价药材成本',
      dataIndex: 'noValuation',
      width: 260,
      renderText(arr, record, index, action) {
        if (arr)
          return arr.reduce(
            (prev: any, cur: any) =>
              `${prev.length > 0 ? prev + '|' : prev}${
                cur.code + '*' + cur.name + '*' + cur.num
              }`,
            '',
          );
      },
    },
    {
      title: '单价',
      dataIndex: 'price',
      width: 90,
      align: 'right',
    },
    {
      title: '操作',
      key: 'option',
      width: 120,
      fixed: 'right',
      valueType: 'option',
      render: (_: any, record: any) => {
        const items: MenuProps['items'] = [
          {
            key: '1',
            label: <UpDataActBtn key={'act'} record={record} type="EDIT" />,
          },
          // {
          //     key: '2',
          //     label: (
          //         <a >
          //             同步设置
          //         </a>
          //     ),
          // },
          {
            key: '3',
            label: (
              <Popconfirm
                title="是否确认删除？"
                key="del"
                onConfirm={() => delTableData(record)}
              >
                <a>删除</a>
              </Popconfirm>
            ),
          },
        ];
        return [
          // <UpDataActBtn key={'act'} record={record} type='EDIT' />,
          // <Popconfirm
          //     title="是否确认删除？"
          //     key="del"
          //     onConfirm={() => delTableData(record)}
          // >
          //     <a>删除</a>
          // </Popconfirm>
          <a
            key="1"
            onClick={() => {
              set_currentSelectRow(record);
              currentRow = record;
              set_drawerType(2);
              set_drawerVisible(true);
            }}
          >
            匹配
          </a>,
          <a
            key="2"
            onClick={() => {
              currentRow = record;
              set_drawerType(1);
              set_currentSelectRow(record);
              set_drawerVisible(true);
            }}
          >
            设置
          </a>,
          <Dropdown menu={{ items }} placement="bottomLeft" arrow>
            <a>
              <IconFont
                type="icongengduochuizhi"
                style={{ color: '#3377FF', width: 16, height: 16 }}
              />
            </a>
          </Dropdown>,
        ];
      },
    },
  ];

  const getTableData = async (params: any) => {
    const resp = await getTableDataReq({ ...params, type: stopStat });
    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) {
      message.success('操作成功！');
      tableRef.current?.reload();
      // message.success('操作成功!');
    }
  };

  const updateTable = async (formVal: any, type: 'EDIT' | 'ADD') => {
    const result = {
      ...formVal,
      standItemCode: formVal.standItem ? formVal.standItem.label : undefined,
      standItemName: formVal.standItem ? formVal.standItem.label : undefined,
      departmentCode: formVal.department ? formVal.department.value : undefined,
      departmentName: formVal.department ? formVal.department.label : undefined,
      department: null,
    };

    if (type == 'ADD') {
      const resp = await addData(result);
      if (resp) {
        tableRef.current?.reload();
        message.success('操作成功！');
      }
    }
    if (type == 'EDIT') {
      const resp = await editData({ ...result });
      if (resp) {
        tableRef.current?.reload();
        message.success('操作成功！');
      }
    }
    return true;
  };

  const UpDataActBtn = ({
    record,
    type,
  }: {
    record: any;
    type: 'EDIT' | 'ADD';
  }) => {
    return (
      <ModalForm
        title={`${type == 'EDIT' ? '编辑' : '新增'}收费项目`}
        width={350}
        formRef={formRef}
        initialValues={
          type == 'EDIT'
            ? {
                ...record,
                standItem: record.standItemCode,
                department: record.departmentCode,
              }
            : {}
        }
        trigger={
          type == 'EDIT' ? (
            <a key="edit">编辑</a>
          ) : (
            <span className="add">新增</span>
          )
        }
        onFinish={(val) => {
          return updateTable(
            type == 'EDIT' ? { ...record, ...val } : { ...val },
            type,
          );
        }}
        modalProps={{ destroyOnClose: true }}
        colProps={{ span: 24 }}
        grid
      >
        <ProFormSelect
          name="department"
          label="科室："
          placeholder="请输入"
          params={['departName']}
          request={fetchAllDepartments}
          fieldProps={{ labelInValue: true, showSearch: true }}
          rules={[{ required: false, message: '科室不能为空!' }]}
        />
        <ProFormText
          name="code"
          label="收费项目编码："
          placeholder="请输入"
          rules={[{ required: true, message: '收费项目编码不能为空!' }]}
        />
        <ProFormText
          name="name"
          label="收费项目名称："
          placeholder="请输入"
          rules={[{ required: true, message: '收费项目名称不能为空!' }]}
        />
        <ProFormSelect
          name="itemType"
          label="项目分类："
          placeholder="请输入"
          request={async () => {
            const resp = await getDicDataBySysId(
              KcimCenterSysId,
              'MED_SERVICE_ITEM_TYPE',
            );
            if (resp) {
              const { dataVoList = [] } = resp;
              return dataVoList.map((a: any) => ({
                label: a.name,
                value: a.code,
              }));
            }
            return [];
          }}
          rules={[{ required: false, message: '项目分类不能为空!' }]}
        />
        <ProFormText
          name="type"
          label="收费项目类别："
          placeholder="请输入"
          // rules={[{ required: true, message: '收费项目类别不能为空!' }]}
        />
        <ProFormText
          name="nationalCode"
          label="国家编码："
          placeholder="请输入"
        />
        <ProFormSelect
          name="standItem"
          label="标准项目名称："
          placeholder="请选择"
          showSearch
          fieldProps={{
            labelInValue: true,
          }}
          request={async ({ keyWords }) => {
            const resp = await getStandItemList({
              name: keyWords,
              pageSize: 100,
              current: 1,
            });
            if (resp) {
              return resp.list.map((a: any) => ({
                label: a.name,
                value: a.code,
              }));
            } else {
              return [];
            }
          }}
        />
        <ProFormDigit
          name="price"
          label="单价："
          placeholder="请输入"
          rules={[{ required: true, message: '单价不能为空!' }]}
        />
      </ModalForm>
    );
  };

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

  const downloadTemplate = async () => {
    await downloadTemplateReq('/costAccount/setting/exportItem');
  };

  const closeDrawer = () => {
    set_drawerVisible(false);
  };

  const switchBatchHandle = (bool: boolean) => {
    set_ifBatchMatch(bool);
  };

  const importData = () => {
    return (
      <ModalForm
        width={360}
        title={`导入数据`}
        trigger={
          <a className="import" key="3">
            导入
          </a>
        }
        submitter={{
          render: (props, defaultDoms) => {
            const needBtn = defaultDoms.filter((b) => {
              return b.key != 'rest';
            });
            return [...needBtn];
          },
        }}
        onFinish={async (values) => {
          const {
            importFile: { fileList },
          } = values;

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

          if (resp) {
            tableRef.current?.reload();
            return true;
          }
        }}
      >
        <FormItem name={'importFile'}>
          <KCIMUpload downloadTemplateFile={() => downloadTemplate()} />
        </FormItem>
      </ModalForm>
    );
  };

  const batchMatchInit = async () => {
    const resp = await getAllNeedMatchItems();
    if (resp) {
      let needItem = undefined;
      for (const item of resp) {
        if (!item.match) {
          set_currentSelectRow(item);
          needItem = item;
          break; // 满足条件后退出循环
        }
      }

      if (!needItem) {
        set_currentSelectRow(resp[0]);
      }
    }
  };

  useEffect(() => {
    if (ifBatchMatch) {
      batchMatchInit();
    }
  }, [ifBatchMatch]);

  return (
    <>
      <div style={{ padding: '0 16px', paddingTop: 16 }}>
        <Breadcrumb>
          <Breadcrumb.Item>收费项目设置</Breadcrumb.Item>
          <Breadcrumb.Item>
            {ifBatchMatch ? (
              <a onClick={() => set_ifBatchMatch(false)}>收费项目管理</a>
            ) : (
              '收费项目管理'
            )}
          </Breadcrumb.Item>
          {ifBatchMatch && <Breadcrumb.Item>项目匹配</Breadcrumb.Item>}
        </Breadcrumb>
      </div>

      <KCIMPagecontainer
        className="ChargeItemsMana"
        title={false}
        style={{ padding: ifBatchMatch ? 0 : 16 }}
      >
        <Drawer
          width={drawerType == 1 ? 800 : 1200}
          title={false}
          open={drawerVisible}
          afterOpenChange={(bool) => {
            set_drawerVisible(bool);
            if (!bool) {
              set_currentSelectRow(undefined);
              tableRef.current?.reload();
            }
          }}
          headerStyle={{ height: 0, padding: 0, overflow: 'hidden' }}
          bodyStyle={{ padding: 0 }}
          destroyOnClose={true}
        >
          {drawerType == 1 && (
            <Setting
              record={currentSelectRow}
              onVisibleChange={(bool: boolean) => set_drawerVisible(bool)}
            />
          )}
          {drawerType == 2 && (
            <MatchPage
              closeDrawer={closeDrawer}
              record={currentSelectRow}
              onVisibleChange={(bool: boolean) => set_drawerVisible(bool)}
            />
          )}
        </Drawer>

        {!ifBatchMatch ? (
          <>
            <div className="toolBar">
              <div className="filter">
                <div className="filterItem">
                  <span className="label" style={{ whiteSpace: 'nowrap' }}>
                    {' '}
                    检索：
                  </span>
                  <Input
                    placeholder={'项目名称/国家编码'}
                    allowClear
                    autoComplete="off"
                    suffix={
                      <IconFont
                        type="iconsousuo"
                        style={{ color: '#99A6BF' }}
                        onClick={() => tableDataSearchHandle('name')}
                      />
                    }
                    onChange={(e) => {
                      set_tableDataSearchKeywords(e.target.value);
                      if (e.target.value.length == 0) {
                        set_tableDataFilterParams({
                          ...tableDataFilterParams,
                          name: '',
                        });
                      }
                    }}
                    onPressEnter={(e) => {
                      set_tableDataFilterParams({
                        ...tableDataFilterParams,
                        name: (e.target as HTMLInputElement).value,
                      });
                    }}
                  />
                </div>
              </div>
              <div className="btnGroup">
                <span style={{ paddingRight: 16 }}>
                  <ProFormSwitch
                    noStyle
                    fieldProps={{
                      size: 'small',
                      onChange: (bool) => {
                        set_stopStat(bool ? 1 : 0);
                        tableRef.current?.reload();
                      },
                    }}
                  />
                  只显示未对照项目
                </span>
                {/* <span className='mapBtn' onClick={() => mapBtnHandle()}>对照</span> */}
                <span className="mapBtn" onClick={() => set_ifBatchMatch(true)}>
                  批量匹配
                </span>
                {importData()}
                <UpDataActBtn record type="ADD" />
              </div>
            </div>

            <div style={{ marginTop: 16 }}>
              <KCIMTable
                scroll={{ x: 1500, y: `calc(100vh - 271px)` }}
                columns={columns as ProColumns[]}
                actionRef={tableRef}
                rowKey="id"
                params={tableDataFilterParams}
                request={(params) => getTableData(params)}

                // expandable={{ expandedRowRender }}
              />
            </div>
          </>
        ) : (
          currentSelectRow && (
            <MatchPage
              closeDrawer={closeDrawer}
              switchBatchHandle={switchBatchHandle}
              single={false}
              record={currentSelectRow}
              onVisibleChange={(bool: boolean) => set_drawerVisible(bool)}
            />
          )
        )}
      </KCIMPagecontainer>
    </>
  );
}
