/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2024-09-09 10:55:13
 * @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 { createFromIconfontCN } from '@ant-design/icons';
import { ActionType } from '@ant-design/pro-components';
import {
  ModalForm,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-form';
import { ProColumns } from '@ant-design/pro-table';
import {
  Dropdown,
  Input,
  MenuProps,
  message,
  Tooltip,
  Popconfirm,
  TreeProps,
} from 'antd';

import { Key } from 'react';
import { useEffect, useRef, useState } from 'react';
import DirectoryTree from 'antd/es/tree/DirectoryTree';
import { DataNode } from 'antd/es/tree';

import {
  getAccountingItemMap,
  addTableData,
  delData,
  getAccountingList,
  batchDelTableData,
} from './service';

import './style.less';

import expandedIcon from '../../../../../static/treenode_open.png';
import closeIcon from '../../../../../static/treenode_collapse.png';

import '../../../../utils/zhongtaiB';
import KCIMPagecontainer from '@/components/KCIMPageContainer';
import { KCIMTable } from '@/components/KCIMTable';
import { getTargetDic } from '@/services/auth';
import TableSelecter from './tableSelector';
import { getDeepestTreeData } from '@/utils/tooljs';

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

let _currentSelectedType: any = undefined;

const ChargeItemMap = () => {
  const [tableDataFilterParams, set_tableDataFilterParams] = useState<
    any | undefined
  >();
  const [tableDataSearchKeywords, set_tableDataSearchKeywords] =
    useState<string>('');

  const [currentSelectedType, set_currentSelectedType] = useState<
    any | undefined
  >(undefined);
  const [treeData, set_treeData] = useState<any[]>([]);
  const [currentSelectedTreeNode, set_currentSelectedTreeNode] = useState<
    null | any
  >(null);
  const [expandedKeys, set_expandedKeys] = useState<Key[]>([]);
  const [autoExpandParent, set_autoExpandParent] = useState(true);
  const [searchValue, set_searchValue] = useState('');
  const [currentTreeDataFilter, set_currentTreeDataFilter] = useState({
    name: '全部',
    code: 0,
  });
  const [treeFilterVisible, set_treeFilterVisible] = useState(false);
  const [selectedRowKeys, set_selectedRowKeys] = useState<Key[]>([]);

  const [tableSelecterVisible, set_tableSelecterVisible] = useState(false);

  const [treeDataDefault, set_treeDataDefault] = useState<any[]>([]);

  const [leftDataSearchKeyVal, set_leftDataSearchKeyVal] = useState<
    undefined | string
  >(undefined);

  const tableRef = useRef<ActionType>();

  const column: ProColumns[] = [
    {
      title: '收费项目代码',
      ellipsis: true,
      width: 120,
      dataIndex: 'itemCode',
    },
    {
      title: '收费项目名称',
      dataIndex: 'itemName',
    },
    {
      title: '收费项目类别',
      width: 100,
      dataIndex: 'typeName',
    },
    {
      title: '操作',
      key: 'option',
      width: 60,
      valueType: 'option',
      render: (_: any, record: any) => {
        return [
          <Popconfirm
            title="是否确认删除？"
            key="del"
            onConfirm={() => delTableData(record.id)}
          >
            <a>删除</a>
          </Popconfirm>,
        ];
      },
    },
  ];

  const getTableData = async (params: any) => {
    const resp = await getAccountingItemMap({ ...params });
    if (resp) {
      return {
        data: resp.list,
        success: true,
        total: resp.totalCount,
        pageSize: resp.pageSize,
        totalPage: resp.totalPage,
      };
    } else {
      return [];
    }
  };

  //获取左侧列表
  const getPageLeftData = async () => {
    const resp = await getAccountingList('', currentTreeDataFilter.code);
    if (resp) {
      set_treeData(resp);
      set_treeDataDefault(resp);
      set_currentSelectedTreeNode(null);
    }
  };

  const delTableData = async (id: number) => {
    const resp = await delData(id);
    if (resp) {
      message.success('操作成功！');
      tableRef.current?.reload();
    }
  };

  const tableSelecterCommit = async (keys: Key[], rows: any[]) => {
    const arr = rows.map((a, index) => ({
      itemCode: a.itemCode,
      itemName: a.itemName,
      type: a.itemType,
    }));
    const result = {
      accountingCode: currentSelectedTreeNode.accountingCode,
      accountingName: currentSelectedTreeNode.accountingName,
      itemMaps: arr,
    };
    const resp = await addTableData(result);
    if (resp) {
      message.success('操作成功');
      set_tableSelecterVisible(false);
      tableRef.current?.reload();
    }
  };

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

  const batchDelHandle = async () => {
    const resp = await batchDelTableData(selectedRowKeys);
    if (resp) {
      message.success('操作成功！');
      set_selectedRowKeys([]);
      tableRef.current?.reload();
    }
  };

  const onSelect: TreeProps['onSelect'] = (selectedKeys, info: any) => {
    const { node } = info;
    if (!node.children || node.children.length == 0) {
      set_currentSelectedTreeNode(node);
    }
  };

  const onExpand = (newExpandedKeys: React.Key[]) => {
    // setExpandedKeys(newExpandedKeys);
    // setAutoExpandParent(false);
    set_expandedKeys(newExpandedKeys);
    set_autoExpandParent(false);
  };

  const dataList: any[] = [];

  const getParentKey = (key: React.Key, tree: any[]): React.Key => {
    let parentKey: React.Key;
    for (let i = 0; i < tree.length; i++) {
      const node = tree[i];
      if (node.children) {
        if (
          node.children.some(
            (item: { accountingCode: React.Key }) =>
              item.accountingCode === key,
          )
        ) {
          parentKey = node.accountingCode;
        } else if (getParentKey(key, node.children)) {
          parentKey = getParentKey(key, node.children);
        }
      }
    }
    return parentKey!;
  };

  const generateList = (data: any[]) => {
    for (let i = 0; i < data.length; i++) {
      const node = data[i];
      dataList.push(node);
      if (node.children) {
        generateList(node.children);
      }
    }
  };

  generateList(treeData as any);

  const onTreeSearchKeyChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { value } = e.target;

    const newExpandedKeys = dataList.map((item) => {
      if (item.accountingName.indexOf(value) > -1) {
        return getParentKey(item.accountingCode, treeData);
      }
      return null;
    });

    set_expandedKeys(newExpandedKeys as React.Key[]);
    set_searchValue(value);
    set_autoExpandParent(true);
  };

  //左侧树结构筛选
  const changeTreeDataFilter = (obj: any) => {
    set_currentTreeDataFilter(obj);
    set_treeFilterVisible(false);
  };

  useEffect(() => {
    if (currentSelectedTreeNode) {
      set_tableDataFilterParams({
        ...tableDataFilterParams,
        accountingCode: currentSelectedTreeNode.accountingCode,
      });
    }
  }, [currentSelectedTreeNode]);

  useEffect(() => {
    //初始化左侧树结构数据后

    if (treeData?.length > 0) {
      if (!currentSelectedTreeNode) {
        if (treeData[0].children && treeData[0].children.length > 0) {
          const [node, nodeParent] = getDeepestTreeData(
            treeData[0],
            'children',
          );
          set_currentSelectedTreeNode(node);
          set_expandedKeys([nodeParent.accountingCode]);
        } else {
          set_currentSelectedTreeNode(treeData[0]);
          set_expandedKeys([treeData[0].accountingCode]);
        }
      }
    }
  }, [treeData]);

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

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

  return (
    <KCIMPagecontainer title={false} className="ChargeItemMap">
      <TableSelecter
        onVisibleChange={(bool) => set_tableSelecterVisible(bool)}
        title="添加"
        rowKey={'itemCode'}
        defaultSelectedKeys={[]}
        record={_currentSelectedType}
        open={tableSelecterVisible}
        onFinish={(keys, rows) => tableSelecterCommit(keys, rows)}
      />

      {selectedRowKeys.length > 0 && (
        <div className="bottomBar">
          <span>
            已选择<a>{selectedRowKeys.length}</a>项
          </span>
          <a onClick={() => batchDelHandle()}>批量删除</a>
        </div>
      )}

      {treeFilterVisible && (
        <div className="selecterList">
          <div
            onClick={() => changeTreeDataFilter({ name: '全部', code: 0 })}
            className={currentTreeDataFilter.code == 0 ? 'list on' : 'list'}
          >
            全部
          </div>
          <div
            onClick={() => changeTreeDataFilter({ name: '已对照', code: 1 })}
            className={currentTreeDataFilter.code == 1 ? 'list on' : 'list'}
          >
            {'已对照'}
          </div>
          <div
            onClick={() => changeTreeDataFilter({ name: '未对照', code: 3 })}
            className={currentTreeDataFilter.code == 3 ? 'list on' : 'list'}
          >
            {'未对照'}
          </div>
        </div>
      )}

      <div className="left">
        <div className="toolbar">
          <Input
            placeholder={'会计科目名称'}
            allowClear
            autoComplete="off"
            suffix={<IconFont type="iconsousuo" style={{ color: '#99A6BF' }} />}
            value={leftDataSearchKeyVal}
            style={{ width: 156 }}
            onChange={onTreeSearchKeyChange}
          />
          <Tooltip placement="top" title={currentTreeDataFilter.name}>
            <div
              className={
                currentTreeDataFilter.code == 0
                  ? 'filter'
                  : currentTreeDataFilter.code == 1
                  ? 'filter blue'
                  : 'filter orange'
              }
              onClick={() => set_treeFilterVisible(true)}
            ></div>
          </Tooltip>
        </div>

        <div className="wrap">
          {treeData && treeData.length > 0 && currentSelectedTreeNode && (
            <DirectoryTree
              fieldNames={{ title: 'accountingName', key: 'accountingCode' }}
              rootStyle={{
                height: '100%',
                paddingBottom: 50,
                padding: '0 16px',
              }}
              onSelect={onSelect}
              onExpand={onExpand}
              expandedKeys={expandedKeys}
              autoExpandParent={autoExpandParent}
              selectedKeys={[currentSelectedTreeNode.accountingCode]}
              blockNode={true}
              icon={() => null}
              titleRender={(nodeData: any) => {
                const strTitle = nodeData.accountingName as string;
                const index = strTitle.indexOf(searchValue);
                const beforeStr = strTitle.substring(0, index);
                const afterStr = strTitle.slice(index + searchValue.length);
                const title =
                  index > -1 ? (
                    <span>
                      {beforeStr}
                      <span
                        className="site-tree-search-value"
                        style={{
                          color: '#3377ff',
                          overflow: 'hidden',
                          textOverflow: 'ellipsis',
                          whiteSpace: 'nowrap',
                        }}
                      >
                        {searchValue}
                      </span>
                      {afterStr}
                    </span>
                  ) : (
                    <span className="strTitle">{strTitle}</span>
                  );
                return (
                  <div
                    style={{
                      display: 'flex',
                      flexDirection: 'row',
                      width: '100%',
                      justifyContent: 'space-between',
                      alignItems: 'center',
                      height: 32,
                      borderRadius: '4px',
                      overflow: 'hidden',
                      color: '#17181A',
                      textOverflow: 'ellipsis',
                      whiteSpace: 'nowrap',
                    }}
                  >
                    {title}
                    {!nodeData.map && (
                      <span
                        className={
                          nodeData.unitType ? 'point lastChild' : 'point'
                        }
                      ></span>
                    )}
                  </div>
                );
              }}
              defaultSelectedKeys={[currentSelectedTreeNode.accountingCode]}
              treeData={treeData as unknown as DataNode[]}
              // treeData={treeDataNew}
              switcherIcon={(props: any) => {
                const { expanded } = props;
                return !expanded ? (
                  <img
                    style={{
                      width: 20,
                      height: 20,
                      position: 'relative',
                      top: 5,
                    }}
                    src={expandedIcon}
                  />
                ) : (
                  <img
                    style={{
                      width: 20,
                      height: 20,
                      position: 'relative',
                      top: 5,
                    }}
                    src={closeIcon}
                  />
                );
              }}
            />
          )}
        </div>
      </div>
      <div className="right">
        <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('itemName')}
                  />
                }
                onChange={(e) => {
                  set_tableDataSearchKeywords(e.target.value);
                  if (e.target.value.length == 0) {
                    set_tableDataFilterParams({
                      ...tableDataFilterParams,
                      itemName: '',
                    });
                  }
                }}
                onPressEnter={(e) => {
                  set_tableDataFilterParams({
                    ...tableDataFilterParams,
                    itemName: (e.target as HTMLInputElement).value,
                  });
                }}
              />
            </div>
          </div>
          <div className="btnGroup">
            <span
              className="add"
              onClick={() => set_tableSelecterVisible(true)}
            >
              添加
            </span>
          </div>
        </div>
        <div style={{ marginTop: 16 }}>
          {currentSelectedTreeNode && (
            <KCIMTable
              actionRef={tableRef}
              columns={column}
              scroll={{ y: 500 }}
              rowKey="id"
              params={tableDataFilterParams}
              request={(params) => getTableData(params)}
              tableAlertRender={false}
              rowSelection={{
                onChange(selectedRowKeys, selectedRows, info) {
                  set_selectedRowKeys(selectedRowKeys);
                },
              }}
            />
          )}
        </div>
      </div>
    </KCIMPagecontainer>
  );
};

export default ChargeItemMap;
function getParentKey(code: any, treeData: any[]) {
  throw new Error('Function not implemented.');
}
