/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2024-10-12 16:04:21
 * @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,
} 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 {
  getAccountProductConnectableList,
  getAccountProductConnectList,
  saveAccountProductConnected,
} from './service';

import './style.less';
import TableSelecter from '@/components/KCIMTableSelector';
import { renameChildListToChildren } from '@/utils/tooljs';
import { searchTree } from '../accountingSubMana';

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

const tableSelectorColumns = [
  {
    title: 'Id',
    width: 60,
    dataIndex: 'id',
  },
  // {
  //     title: '会计科目编码',
  //     width:300,
  //     dataIndex: 'accountingCode',
  // },
  {
    title: '成本收入项目',
    dataIndex: 'name',
  },
];

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; // 返回排序后的树
}

let currentRow: any = undefined;

export default function AccountingSubMap() {
  const [tableDataFilterParams, set_tableDataFilterParams] = useState<
    any | undefined
  >({ accountType: 1 });
  const [tableDataSearchKeywords, set_tableDataSearchKeywords] =
    useState<string>('');
  const tableRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();
  const [tabs, set_tabs] = useState<any[]>([]);
  const [accountType, set_accountType] = useState<Key>(1);
  const [tableSelecterVisible, set_tableSelecterVisible] = useState(false);
  const columns: ProColumns[] = [
    {
      title: '会计科目名称',
      width: 400,
      ellipsis: true,
      dataIndex: 'accountingName',
    },
    {
      title: '会计科目编码',
      width: 300,
      ellipsis: true,
      dataIndex: 'accountingCode',
    },
    {
      title: '收入项目',
      dataIndex: 'productVOs',
      ellipsis: true,
      renderText(productVOs, record) {
        if (Array.isArray(productVOs)) {
          return productVOs.map((item, index) => {
            return <Tag key={index}>{item.productName}</Tag>;
          });
        } else {
          return <></>;
        }
      },
    },
    {
      title: '操作',
      key: 'option',
      width: 80,
      valueType: 'option',
      render: (_: any, record: any) => {
        const { isParent } = record;
        return !isParent
          ? [
              <a
                key="config"
                onClick={() => {
                  currentRow = record;
                  set_tableSelecterVisible(true);
                }}
              >
                设置对应
              </a>,
            ]
          : [];
      },
    },
  ];
  const columnsTwo: ProColumns[] = [
    {
      title: '会计科目名称',
      width: 400,
      ellipsis: true,
      dataIndex: 'accountingName',
    },
    {
      title: '会计科目编码',
      width: 300,
      dataIndex: 'accountingCode',
    },
    {
      title: '成本项目',
      dataIndex: 'productVOs',
      ellipsis: true,
      renderText(productVOs, record) {
        if (Array.isArray(productVOs)) {
          return productVOs.map((item, index) => {
            return <Tag key={index}>{item.productName}</Tag>;
          });
        } else {
          return <></>;
        }
      },
    },
    {
      title: '操作',
      key: 'option',
      width: 80,
      valueType: 'option',
      render: (_: any, record: any) => {
        const { isParent } = record;
        return !isParent
          ? [
              <a
                key="config"
                onClick={() => {
                  currentRow = record;
                  set_tableSelecterVisible(true);
                }}
              >
                设置对应
              </a>,
            ]
          : [];
      },
    },
  ];

  const getTableData = async (params: any) => {
    const { filter } = params;
    const resp = await getAccountProductConnectList({
      ...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 onTabChanged = (key: Key) => {
    set_accountType(key);
    tableRef.current?.reload();
  };
  //productCode,productName
  const getTableSelectorData = async () => {
    const { responsibilityId, productVOs = [] } = currentRow;
    const defaultRows = productVOs
      ? productVOs.map((a: any) => ({
          id: a.id,
          name: `${a.productName}[${a.productCode}]`,
        }))
      : [];
    const resp = await getAccountProductConnectableList({
      responsibilityId,
      pageSize: 500,
      current: 1,
    });
    if (resp) {
      return [...resp, ...defaultRows];
    }
  };

  const tableSelecterCommit = async (keys: Key[], rows: any[]) => {
    const { id } = currentRow;
    const resp = await saveAccountProductConnected({ id, products: keys });
    if (resp) {
      set_tableSelecterVisible(false);
      tableRef.current?.reload();
    }
  };

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

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

  return (
    <KCIMPagecontainer className="AccountingSubMap" title={false}>
      <TableSelecter
        columns={[...tableSelectorColumns]}
        onVisibleChange={(bool) => set_tableSelecterVisible(bool)}
        title="关联成本收入项目"
        rowKey={'id'}
        request={getTableSelectorData}
        defaultSelectedKeys={
          currentRow && currentRow.productVOs
            ? [...currentRow.productVOs.map((a: any) => a.id)]
            : []
        }
        record={currentRow}
        open={tableSelecterVisible}
        onFinish={(keys, rows) => tableSelecterCommit(keys, rows)}
      />
      <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',
          }}
        >
          <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>
      </div>

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