/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2024-09-09 10:42:19
 * @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,
  ProFormCascader,
  ProFormInstance,
  ProFormText,
} from '@ant-design/pro-components';
import { ModalForm, ProFormDigit, ProFormSelect } from '@ant-design/pro-form';
import { ProColumns } from '@ant-design/pro-table';
import { Input, message, Popconfirm, Form } 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,
  getCostAccountingDict,
  getStandItemList,
  getKcClassDicData,
  importDataPost,
} from './service';

import './style.less';
import KCIMUpload from '@/components/KCIMUpload';
import { downloadTemplateReq, findAllParents } from '@/utils/tooljs';
import React from 'react';
import DrawerActBtn from './drawer';
import { getDicDataBySysId } from '@/services/getDic';
import { KcimCenterSysId } from '@/constant';

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

export default function StandardProjectMana() {
  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 columns: ProColumns[] = [
    {
      title: '项目编码',
      dataIndex: 'code',
      width: 80,
      ellipsis: true,
    },
    {
      title: '项目名称',
      dataIndex: 'name',
      ellipsis: true,
      width: 300,
    },
    {
      title: '国家编码',
      dataIndex: 'nationalCode',
      ellipsis: true,
      width: 120,
    },
    {
      title: '项目分类',
      dataIndex: 'itemTypeName',
      ellipsis: true,
      width: 120,
    },
    {
      title: '康程分类',
      dataIndex: 'kcClassLevelName',
      ellipsis: true,
      width: 250,
    },
    {
      title: '执行时间（min）',
      width: 130,
      dataIndex: 'executeTime',
    },
    {
      title: '参与人员',
      dataIndex: 'empMaps',
      ellipsis: true,
      renderText(arr, record) {
        return arr
          ? arr.reduce(
              (prev: string, cur: any) =>
                `${prev.length > 0 ? prev + '|' : prev}${cur.empTypeCodeName}*${
                  cur.num
                }*${cur.executeTime}`,
              '',
            )
          : '-';
      },
    },
    {
      title: '使用设备',
      ellipsis: true,
      dataIndex: 'equipmentMaps',
      renderText(arr, record) {
        return arr
          ? arr.reduce(
              (prev: string, cur: any) =>
                `${prev.length > 0 ? prev + '|' : prev}${
                  cur.equipmentCodeName
                }*${cur.num}*${cur.executeTime}`,
              '',
            )
          : '-';
      },
    },
    {
      title: '使用空间',
      dataIndex: 'spaceMaps',
      ellipsis: true,
      renderText(arr, record) {
        return arr
          ? arr.reduce(
              (prev: string, cur: any) =>
                `${prev.length > 0 ? prev + '|' : prev}${cur.spaceCodeName}*${
                  cur.num
                }*${cur.executeTime}`,
              '',
            )
          : '-';
      },
    },
    {
      title: '技术难度',
      dataIndex: 'technicalDifficulty',
      ellipsis: true,
      width: 90,
    },
    {
      title: '风险程度',
      dataIndex: 'riskDegree',
      ellipsis: true,
      width: 90,
    },
    {
      title: '操作',
      key: 'option',
      width: 160,
      fixed: 'right',
      valueType: 'option',
      render: (_: any, record: any) => {
        return [
          <UpDataActBtn key={'act'} record={record} type="EDIT" />,
          <Popconfirm
            title="是否确认删除？"
            key="del"
            onConfirm={() => delTableData(record)}
          >
            <a>删除</a>
          </Popconfirm>,
          <DrawerActBtn
            key="link7"
            record={record}
            onVisibleChange={(bool) => {
              !bool && tableRef.current?.reload();
            }}
          />,
        ];
      },
    },
  ];

  const getTableData = async (params: any) => {
    const resp = await getStandItemList({ ...params });
    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' | 'ADDCHILD',
  ) => {
    const result = {
      code: formVal.code,
      name: formVal.name,
      nationalCode: formVal.nationalCode,
      kcClassCode: formVal.kcClassCode,
      kcClassName: formVal.kcClassName,
      kcClassPath: formVal.kcClassPath,
      kcClassLevelName: formVal.kcClassLevelName,
      executeTime: formVal.executeTime,
      riskDegree: formVal.riskDegree,
      itemType: formVal.itemType,
      technicalDifficulty: formVal.technicalDifficulty,
    };

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

  const UpDataActBtn = ({
    record,
    type,
  }: {
    record: any;
    type: 'EDIT' | 'ADD' | 'ADDCHILD';
  }) => {
    const [cascaderData, set_cascaderData] = useState<any[]>([]);

    return (
      <ModalForm
        title={`${type == 'EDIT' ? '编辑' : '新增'}项目`}
        width={350}
        formRef={formRef}
        initialValues={
          type == 'EDIT'
            ? {
                ...record,
                kcClass: record.kcClassPath
                  ? record.kcClassPath.split(',')
                  : [],
              }
            : { kcClassCode: '', kcClassName: '', kcClassPath: '' }
        }
        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
      >
        <ProFormText
          name="code"
          label="项目编码："
          placeholder="请输入"
          rules={[{ required: true, message: '项目编码不能为空!' }]}
        />
        <ProFormText
          name="name"
          label="项目名称："
          placeholder="请输入"
          rules={[{ required: true, message: '项目名称不能为空!' }]}
        />
        <ProFormText
          name="nationalCode"
          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: true, message: '项目分类不能为空!' }]}
        />
        <ProFormText name="kcClassCode" hidden />
        <ProFormText name="kcClassName" hidden />
        <ProFormText name="kcClassPath" hidden />
        <ProFormText name="kcClassLevelName" hidden />
        <ProFormCascader
          name="kcClass"
          label="康程分类："
          rules={[{ required: true, message: '康程分类不能为空!' }]}
          request={async () => {
            const resp = await getKcClassDicData();
            if (resp) {
              set_cascaderData(resp);
              return resp;
            }
          }}
          fieldProps={{
            fieldNames: { label: 'name', value: 'code', children: 'childList' },
            onChange: async (value: any) => {
              const a = findAllParents(
                cascaderData,
                value[value.length - 1],
                'childList',
              );
              if (a.length > 0) {
                formRef.current?.setFieldsValue({
                  kcClassCode: a[a.length - 1].code,
                  kcClassName: a[a.length - 1].name,
                  kcClassPath: value.join(','),
                  kcClassLevelName: a.map((b: any) => b.name).join('/'),
                });
              }
            },
          }}
        />
        <ProFormDigit
          name="executeTime"
          label="执行时间："
          placeholder="请输入"
          rules={[{ required: true, message: '执行时间不能为空!' }]}
        />
        <ProFormDigit
          name="technicalDifficulty"
          label="技术难度："
          placeholder="请输入"
          rules={[{ required: true, message: '技术难度不能为空!' }]}
        />
        <ProFormDigit
          name="riskDegree"
          label="风险程度："
          placeholder="请输入"
          rules={[{ required: true, message: '风险程度不能为空!' }]}
        />
      </ModalForm>
    );
  };

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

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

  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 [
              // <Button
              //     key="ok"
              //     onClick={auditType == '0' ? () => downloadTemplate(index) : () => { }}
              // >
              //     下载模板
              // </Button>,
              ...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>
    );
  };

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

  return (
    <KCIMPagecontainer className="StandardProjectMana" title={false}>
      <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"
                  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">
          {importData()}
          {/* <span className='import'>导出</span> */}
          <UpDataActBtn record type="ADD" />
        </div>
      </div>

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