/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2024-10-12 10:38:26
 * @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,
  ProFormRadio,
} from '@ant-design/pro-components';
import { ModalForm } from '@ant-design/pro-form';
import { ProColumns } from '@ant-design/pro-table';
import { Input, message, Popconfirm, Tag, Tabs } 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,
  getAccountingSubjectList,
  getAccountTypeDictReq,
} from './service';

import './style.less';
import { renameChildListToChildren } from '@/utils/tooljs';

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

let currentRow: any = undefined;

export const searchTree = (tree: any[], searchTerm: string) => {
  const searchTermLower = searchTerm.toLowerCase();

  function searchNode(node: any) {
    const matchedChildren: any[] = [];

    if (node.children && node.children.length > 0) {
      node.children.forEach((child: any) => {
        const matchedChild = searchNode(child);
        if (matchedChild) {
          matchedChildren.push(matchedChild);
        }
      });
    }

    if (
      node.accountingName.toLowerCase().includes(searchTermLower) ||
      node.accountingCode.toLowerCase().includes(searchTermLower)
    ) {
      return {
        ...node,
        children: matchedChildren.length > 0 ? matchedChildren : node.children,
      };
    } else if (matchedChildren.length > 0) {
      return {
        ...node,
        children: matchedChildren,
      };
    }

    return null;
  }

  return tree
    .map((rootNode) => searchNode(rootNode))
    .filter((node) => node !== null);
};

function sortTreeByCode(
  tree: any[],
  codeKey = 'accountingCode',
  childrenKey = 'children',
) {
  // 首先对当前层级的节点按照 codeKey 进行排序
  tree.sort((a, b) => {
    return Number(a[codeKey]) - Number(b[codeKey]); // 按照 code 从小到大排序
  });

  // 然后对于每个节点的子节点，不进行排序，只递归下去
  tree.forEach((node) => {
    if (node[childrenKey] && node[childrenKey].length > 0) {
      sortTreeByCode(node[childrenKey], codeKey, childrenKey); // 递归处理子节点
    }
  });

  return tree; // 返回排序后的树
}

export default function AccountingSubMana() {
  const [tableDataFilterParams, set_tableDataFilterParams] = useState<
    any | undefined
  >({ accountType: 1 });
  const [tableDataSearchKeywords, set_tableDataSearchKeywords] =
    useState<string>('');
  const tableRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();
  const [selectableLevelList, setSelectableLevelList] = useState([]); //可选的分摊层级列表
  const [tabs, set_tabs] = useState<any[]>([]);
  const [accountType, set_accountType] = useState<Key>(1);
  const columns: ProColumns[] = [
    {
      title: '会计科目名称',
      width: 400,
      ellipsis: true,
      fixed: 'left',
      dataIndex: 'accountingName',
    },
    {
      title: '会计科目编码',
      dataIndex: 'accountingCode',
    },
    {
      title: '会计科目类别',
      dataIndex: 'typeName',
    },
    {
      title: '成本类别',
      hideInTable: accountType == 1,
      dataIndex: 'costType',
      renderText(type) {
        return type == 1 ? '医疗成本' : type == 2 ? '医疗全成本' : '医院全成本';
      },
    },
    {
      title: '成本属性',
      hideInTable: accountType == 1,
      dataIndex: 'isBaseCost',
      renderText(type) {
        return type == 1 ? '固定成本' : '变动成本';
      },
    },
    {
      title: '可控类型',
      dataIndex: 'controlType',
      renderText(type) {
        return type == 1 ? '不可控' : '可控';
      },
    },
    {
      title: '诊别',
      dataIndex: 'medicalType',
      renderText(type) {
        return type == 0 ? '全院' : type == 1 ? '门诊' : '住院';
      },
    },
    {
      title: '操作',
      key: 'option',
      width: 120,
      fixed: 'right',
      valueType: 'option',
      render: (_: any, record: any) => {
        return [
          <UpDataActBtn record={record} type="ADDCHILD" />,
          <UpDataActBtn key={'act'} record={record} type="EDIT" />,
          <Popconfirm
            title="是否确认删除？"
            key="del"
            onConfirm={() => delTableData(record)}
          >
            <a>删除</a>
          </Popconfirm>,
        ];
      },
    },
  ];

  const getTableData = async (params: any) => {
    const { filter } = params;
    const resp = await getAccountingSubjectList({
      ...params,
      accountType,
      pageSize: 500,
    });
    if (resp) {
      let data = [];
      if (filter) {
        data = searchTree(
          renameChildListToChildren(resp.list, 'child'),
          filter,
        );
      } else {
        data = renameChildListToChildren(resp.list, 'child');
      }
      return {
        data: sortTreeByCode(data),
        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',
  ) => {
    if (type == 'ADD' || type == 'ADDCHILD') {
      let id = 0;
      type == 'ADDCHILD' && (id = formVal.id);

      const result =
        accountType == 1
          ? { ...formVal, accountingType: accountType, id: id }
          : { ...formVal, accountingType: accountType, id: id };

      const resp = await addData(result);
      if (resp) {
        currentRow = undefined;
        tableRef.current?.reload();
        message.success('操作成功！');
      }
    }
    if (type == 'EDIT') {
      try {
        const resp = await editData({
          ...formVal,
          isIncomeGroutSetSelect: false,
          isShareParamSelect: false,
          accountType,
        });
        if (resp) {
          tableRef.current?.reload();
          message.success('操作成功！');
        }
      } catch (error) {
        console.log({ error });
      }
    }
    return true;
  };

  const UpDataActBtn = ({
    record,
    type,
  }: {
    record: any;
    type: 'EDIT' | 'ADD' | 'ADDCHILD';
  }) => {
    return (
      <ModalForm
        title={`${type == 'EDIT' ? '编辑' : '新增'}会计科目`}
        width={350}
        formRef={formRef}
        initialValues={
          type == 'EDIT'
            ? {
                ...record,
              }
            : { controlType: 1, medicalType: 0 }
        }
        trigger={
          type == 'EDIT' ? (
            <a key="edit">编辑</a>
          ) : type == 'ADDCHILD' ? (
            <a className="add">添加</a>
          ) : (
            <span className="add">新增</span>
          )
        }
        onFinish={(val) => {
          return updateTable(
            type == 'EDIT'
              ? { ...record, ...val }
              : type == 'ADDCHILD'
              ? { ...val, id: record.id }
              : { ...val },
            type,
          );
        }}
        modalProps={{ destroyOnClose: true }}
        colProps={{ span: 24 }}
        grid
      >
        <ProFormText name="typeName" hidden />
        <ProFormText
          label="会计科目编码"
          disabled={type == 'EDIT'}
          rules={[
            {
              required: true,
              message: '会计科目编码是必填项',
            },
          ]}
          name="accountingCode"
        />
        <ProFormText
          label="会计科目名"
          rules={[
            {
              required: true,
              message: '会计科目名是必填项',
            },
          ]}
          name="accountingName"
        />
        <ProFormDependency name={['accountingCode']}>
          {({ accountingCode }) => {
            return accountType == 2 ? (
              <>
                <ProFormSelect
                  rules={[
                    {
                      required: true,
                      message: '',
                    },
                  ]}
                  options={[
                    {
                      value: 0,
                      label: '不是',
                    },
                    {
                      value: 1,
                      label: '是',
                    },
                  ]}
                  name="isBaseCost"
                  label="是否固定成本"
                />
                <ProFormRadio.Group
                  name="costType"
                  label="成本类别"
                  rules={[
                    {
                      required: true,
                      message: '成本类别是必填项',
                    },
                  ]}
                  options={[
                    {
                      label: '医疗成本',
                      value: 1,
                    },
                    {
                      label: '医疗全成本',
                      value: 2,
                    },
                    {
                      label: '医院全成本',
                      value: 3,
                    },
                  ]}
                />
              </>
            ) : (
              <></>
            );
          }}
        </ProFormDependency>
        <ProFormSelect
          rules={[
            {
              required: true,
              message: '请选择会计科目类别',
            },
          ]}
          request={async () => {
            const resp = await getAccountTypeDictReq(accountType as number);
            if (resp) {
              return resp.map((a: any) => ({ label: a.name, value: a.code }));
            }
            return [];
          }}
          fieldProps={{
            onChange(value, option: any) {
              const { label } = option;
              formRef.current?.setFieldValue('typeName', label);
            },
          }}
          name="type"
          label="会计科目类别"
        />
        <ProFormRadio.Group
          name="controlType"
          label="可控类型"
          rules={[
            {
              required: true,
              message: '可控类型是必填项',
            },
          ]}
          options={[
            {
              label: '不可控',
              value: 1,
            },
            {
              label: '可控',
              value: 2,
            },
          ]}
        />
        <ProFormRadio.Group
          name="medicalType"
          label="就诊类别"
          rules={[
            {
              required: true,
              message: '就诊类别是必填项',
            },
          ]}
          options={[
            {
              label: '全院',
              value: 0,
            },
            {
              label: '门诊',
              value: 1,
            },
            {
              label: '住院',
              value: 3,
            },
          ]}
        />
      </ModalForm>
    );
  };

  const onTabChanged = (key: Key) => {
    set_accountType(key);
    tableRef.current?.reload();
  };

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

  useEffect(() => {
    set_tabs([
      {
        label: '收入',
        key: 1,
      },
      {
        label: '支出',
        key: 2,
      },
    ]);
  }, []);

  return (
    <KCIMPagecontainer className="AccountingSubMana" title={false}>
      <div className="toolBar">
        <Tabs
          defaultActiveKey={tabs.length > 0 ? tabs[0].key : undefined}
          items={tabs}
          key={'key'}
          onChange={(key) => onTabChanged(key)}
        />
        <div
          className="filter"
          style={{
            display: 'flex',
            flexDirection: 'row',
            justifyContent: 'space-between',
            alignItems: 'center',
            marginBottom: 16,
          }}
        >
          <div className="filterItem">
            <span className="label" style={{ whiteSpace: 'nowrap' }}>
              {' '}
              检索：
            </span>
            <Input
              placeholder={'会计科目编码/名称'}
              allowClear
              autoComplete="off"
              suffix={
                <IconFont
                  type="iconsousuo"
                  style={{ color: '#99A6BF' }}
                  onClick={() => tableDataSearchHandle('filter')}
                />
              }
              onChange={(e) => {
                set_tableDataSearchKeywords(e.target.value);
                if (e.target.value.length == 0) {
                  set_tableDataFilterParams({
                    ...tableDataFilterParams,
                    filter: '',
                  });
                }
              }}
              onPressEnter={(e) => {
                set_tableDataFilterParams({
                  ...tableDataFilterParams,
                  filter: (e.target as HTMLInputElement).value,
                });
              }}
            />
          </div>
          <div className="btnGroup">
            <UpDataActBtn record type="ADD" />
          </div>
        </div>
      </div>

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