/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2024-08-23 10:22:11
 * @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 { createFromIconfontCN } from '@ant-design/icons';

import {
  ActionType,
  ProFormDependency,
  ProFormInstance,
  ProFormText,
  ProFormSelect,
  ProFormDigit,
} from '@ant-design/pro-components';
import { ModalForm } from '@ant-design/pro-form';
import { ProColumns } from '@ant-design/pro-table';
import { message, Popconfirm, Form, Select } from 'antd';
import { Key, useEffect, useRef, useState } from 'react';

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

import { addData, delData, editData, getWholeHospCostList } from './service';

import './style.less';

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

export default function WholeHospCostAndIncomeSet() {
  const [tableDataFilterParams, set_tableDataFilterParams] = useState<
    any | undefined
  >({ accountType: 1 });
  const [tableDataSearchKeywords, set_tableDataSearchKeywords] =
    useState<string>('');
  const tableRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();
  const [currentRow, setCurrentRow] = useState<any | undefined>(undefined);
  const [selectableLevelList, setSelectableLevelList] = useState<any[]>([]); //可选的分摊层级列表

  const columns: ProColumns[] = [
    {
      title: '收支类型',
      dataIndex: 'paymentsType',
      renderText(num) {
        return num == 1 ? '收入' : '支出';
      },
    },
    {
      title: '收支名称',
      dataIndex: 'paymentsName',
    },
    {
      title: '操作',
      key: 'option',
      width: 90,
      valueType: 'option',
      render: (_: any, record: any) => {
        return [
          <UpDataActBtn key={'act'} record={record} type="EDIT" />,
          <Popconfirm
            title="是否确认删除？"
            key="del"
            onConfirm={() => delTableData(record)}
          >
            <a>删除</a>
          </Popconfirm>,
        ];
      },
    },
  ];

  const getTableData = async (params: any) => {
    const resp = await getWholeHospCostList({ ...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') => {
    const result = {
      paymentsType: formVal.paymentsType,
      paymentsName: formVal.paymentsName,
    };
    if (type == 'ADD') {
      const resp = await addData(result);
      if (resp) {
        tableRef.current?.reload();
        message.success('操作成功！');
      }
    }
    if (type == 'EDIT') {
      try {
        const resp = await editData({ ...result, id: formVal.id });
        if (resp) {
          tableRef.current?.reload();
          message.success('操作成功！');
        }
      } catch (error) {
        console.log({ error });
      }
    }
    return true;
  };

  const UpDataActBtn = ({
    record,
    type,
  }: {
    record: any;
    type: 'EDIT' | 'ADD';
  }) => {
    setCurrentRow(record);
    return (
      <ModalForm
        title={`${type == 'EDIT' ? '编辑' : '新增'}分摊层级`}
        width={350}
        formRef={formRef}
        initialValues={
          type == 'EDIT'
            ? {
                ...record,
                targetLevel: record.targetLevel
                  ? record.targetLevel.split(',').map((a: string) => Number(a))
                  : [],
              }
            : { targetLevel: [] }
        }
        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
          rules={[
            {
              required: true,
              message: '请选择收支类型',
            },
          ]}
          options={[
            {
              value: 1,
              label: '收入',
            },
            {
              value: 2,
              label: '支出',
            },
          ]}
          name="paymentsType"
          label="选择收支类型"
        />
        <ProFormText
          rules={[
            {
              required: true,
              message: '请填写收支名称',
            },
          ]}
          name="paymentsName"
          label="收支名称"
        />
      </ModalForm>
    );
  };

  return (
    <KCIMPagecontainer className="WholeHospCostAndIncomeSet" title={false}>
      <div className="toolBar">
        <div className="title">全院其他收支设置</div>
        <div className="btnGroup">
          <UpDataActBtn record type="ADD" />
        </div>
      </div>

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