/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2025-02-18 15:10:34
 * @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 { KCInput } from '@/components/KCInput';
import KCTable from '@/components/kcTable';

import { ModalForm, ProFormSelect, ProFormText, ProFormTextArea } from '@ant-design/pro-form';
import { ProColumns } from '@ant-design/pro-table';
import { Input, message, Modal, Popconfirm, Switch, TreeProps } from 'antd';
import React, { useEffect, useState } from 'react';
import { addData, delData, dicOpenStatHandle, editData, getData, getTreeData } from './service';

import './style.less';

import { createFromIconfontCN } from '@ant-design/icons';
import { DataNode } from 'antd/lib/tree';

import expandedIcon from '../../../../../public/images/treenode_open.png';
import closeIcon from '../../../../../public/images/treenode_collapse.png';
import DirectoryTree from 'antd/es/tree/DirectoryTree';
import { getDeepestTreeData } from '@/utils';

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

export default function PubDicTypeMana() {
  const [tableDataFilterParams, set_tableDataFilterParams] = useState<{
    current: number;
    pageSize: number;
    name?: string;
  }>({
    current: 1,
    pageSize: 10
  });
  const [tableDataSearchKeywords, set_tableDataSearchKeywords] = useState<string>('');
  const [reload, set_reload] = useState(false);
  const [currentEdit, set_currentEdit] = useState<any>(undefined);

  const [treeData, set_treeData] = useState<any[]>([]);
  const [currentSelectedTreeNode, set_currentSelectedTreeNode] = useState<any | undefined>();
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  const [searchValue, setSearchValue] = useState('');
  const [autoExpandParent, setAutoExpandParent] = useState(true);

  const columns: ProColumns[] = [
    {
      title: '类型名称',
      dataIndex: 'dictName',
    },
    {
      title: '类型代码',
      dataIndex: 'dictType',
    },
    {
      title: '标题',
      dataIndex: 'topic',
    },
    {
      title: '说明',
      dataIndex: 'remark',
    },
    {
      title: '开放',
      dataIndex: 'status',
      renderText(val, record, index, action) {
        return <Switch size="small" checked={val == '0' ? true : false} onChange={(bool) => chnageDicOpenStatHandle(bool, record)} />;
      },
    },
    {
      title: '操作',
      key: 'option',
      width: 120,
      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 chnageDicOpenStatHandle = async (bool: boolean, record: any) => {
    const resp = await dicOpenStatHandle({ dictId: record.dictId, status: bool ? '0' : '1' });
    if (resp) {
      message.success('开放成功！');
      set_reload(true);
    }
  };

  const getTableData = async (params: any) => {
    const resp = await getData({ ...params, systemId: params.systemId ? params.systemId : currentSelectedTreeNode.code });
    set_reload(false);
    if (resp) {
      return {
        data: resp.list,
        success: true,
        total: resp.totalCount,
      };
    }
    return [];
  };

  const delTableData = async (record: any) => {
    const resp = await delData(record.dictId);
    if (resp) {
      set_reload(true);
      // message.success('操作成功!');
    }
  };

  const updateTable = async (formVal: any, type: 'EDIT' | 'ADD') => {
    if (type == 'ADD') {
      const resp = await addData({
        dictName: formVal.dictName,
        dictType: formVal.dictType,
        remark: formVal.remark,
        topic: formVal.topic ? formVal.topic : null,
        systemId: currentSelectedTreeNode.code,
      });
      if (resp) {
        set_reload(true);
      }
    }
    if (type == 'EDIT') {
      const { dictId } = currentEdit;
      const resp = await editData({
        dictId,
        dictName: formVal.dictName,
        dictType: formVal.dictType,
        remark: formVal.remark,
        topic: formVal.topic ? formVal.topic : null,
        systemId: currentSelectedTreeNode.code,
      });
      if (resp) {
        set_reload(true);
      }
    }
  };

  const UpDataActBtn = ({ record, type }: { record: any; type: 'EDIT' | 'ADD' }) => {
    return (
      <ModalForm
        title={`${type == 'EDIT' ? '编辑' : '新增'}公用字典类型`}
        width={352}
        initialValues={type == 'EDIT' ? { ...record } : {}}
        trigger={
          type == 'EDIT' ? (
            <a key="edit" onClick={() => set_currentEdit(record)}>
              编辑
            </a>
          ) : (
            <span className="add">新增</span>
          )
        }
        onFinish={(val) => {
          return updateTable(val, type);
        }}
      >
        {/* <ProFormSelect
                    name="hospId"
                    label="院区："
                    disabled={type == 'EDIT'}
                    placeholder="请选择院区"
                    request={async () => {
                        const resp = await getAllHosp({ pageSize: 200, current: 1 });
                        if (resp) {
                            const data: any = resp.list?.map((a) => ({
                                label: a.hospName,
                                value: a.id
                            }));

                            return data;
                        }
                        return []

                    }}

                    fieldProps={{

                    }}
                /> */}
        <ProFormText name="dictName" label="类型名称：" placeholder="请输入" rules={[{ required: true, message: '类型名称不能为空!' }]} />
        <ProFormText name="dictType" label="类型代码：" placeholder="请输入" rules={[{ required: true, message: '类型代码不能为空!' }]} />
        <ProFormTextArea name="topic" label="标题（|线分割）：" placeholder="请输入" />
        <ProFormTextArea name="remark" label="说明：" placeholder="请输入" />
      </ModalForm>
    );
  };

  const handleTableChange = (pagination: any) => {
    set_tableDataFilterParams({
      ...tableDataFilterParams,
      current: pagination.current,
      pageSize: pagination.pageSize
    });
  }

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

  const getTreeReqFunc = async (name?: string) => {
    const resp = await getTreeData();
    set_treeData(resp);
  };

  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: { code: React.Key }) => item.code === key)) {
          parentKey = node.code;
        } 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];
      const { code, name } = node;
      dataList.push({ code, name: name });
      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.name.indexOf(value) > -1) {
        return getParentKey(item.code, treeData);
      }
      return null;
    });

    const b = newExpandedKeys.filter((item, i, self) => item && self.indexOf(item) === i);
    setExpandedKeys(newExpandedKeys as React.Key[]);
    setSearchValue(value);
    setAutoExpandParent(true);
  };

  const onSelect: TreeProps['onSelect'] = (selectedKeys, info) => {
    //console.log('selected', selectedKeys, info);
    const { node } = info;
    if (!node.children) {
      set_currentSelectedTreeNode(node);
    }
  };

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

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

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

    if (treeData?.length > 0) {
      if (treeData[0].children && treeData[0].children.length > 0) {
        const [node, nodeParent] = getDeepestTreeData(treeData[0], 'children');

        set_currentSelectedTreeNode(node);
        setExpandedKeys([nodeParent.code]);
      }
    }
  }, [treeData]);

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

  return (
    <div className="PubDicTypeMana">
      <div className="left">
        <div className="search">
          <Input className="searchInput" placeholder="请输入" size="small" allowClear style={{ marginBottom: 16 }} onChange={onTreeSearchKeyChange} suffix={<SearchIcon type="iconsousuo" />} />
        </div>
        {treeData && treeData.length > 0 && (
          <DirectoryTree
            fieldNames={{ title: 'name', key: 'code' }}
            rootStyle={{ height: '100%', paddingBottom: 50, overflowY: 'scroll', overflowX: 'hidden' }}
            onSelect={onSelect}
            onExpand={onExpand}
            expandedKeys={expandedKeys}
            autoExpandParent={autoExpandParent}
            selectedKeys={currentSelectedTreeNode ? [currentSelectedTreeNode.code] : []}
            blockNode={true}
            icon={() => null}
            titleRender={(nodeData: any) => {
              const strTitle = nodeData.name as string;
              const index = strTitle.indexOf(searchValue);
              const beforeStr = strTitle.substring(0, index);
              const afterStr = strTitle.slice(index + searchValue.length);

              const copyFunc = async () => {
                try {
                  await navigator.clipboard.writeText(nodeData.systemId);
                  message.success('复制成功！');
                } catch (err) {
                  console.error('Failed to copy text: ', err);
                }
              };
              const title =
                index > -1 ? (
                  <span>
                    {beforeStr}
                    <span className="site-tree-search-value" style={{ color: 'red', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                      {searchValue}
                    </span>
                    {afterStr}
                    <a className="copy" onClick={() => copyFunc()}>
                      <img style={{ width: 14, height: 14 }} src={require('../../../../../public/images/copy.png')} alt="" />
                    </a>
                  </span>
                ) : (
                  <span className="strTitle">
                    {strTitle}
                    <a className="copy" onClick={() => copyFunc()}>
                      <img style={{ width: 14, height: 14 }} src={require('../../../../../public/images/copy.png')} alt="" />
                    </a>
                  </span>
                );
              return (
                <div
                  style={{
                    display: 'flex',
                    flexDirection: 'row',
                    width: '100%',
                    justifyContent: 'flex-start',
                    alignItems: 'center',
                    height: 32,
                    borderRadius: '4px',
                    overflow: 'hidden',
                    color: '#17181A',
                    textOverflow: 'ellipsis',
                    whiteSpace: 'nowrap',
                  }}
                >
                  {title}
                </div>
              );
            }}
            defaultSelectedKeys={[treeData[0].children[0].code]}
            treeData={treeData as unknown as DataNode[]}
            // treeData={treeDataNew}
            switcherIcon={(props: any) => {
              const { expanded } = props;
              //return <button className='site-table-row-expand-icon site-table-row-expand-icon-expanded'></button>
              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 className="right">
        <div className="toolBar">
          <div className="filter">
            <div className="filterItem">
              <span className="label">检索：</span>
              <KCInput
                placeholder={'请输入类型名称'}
                style={{ width: 160 }}
                search
                allowClear
                onChange={(e) => {
                  set_tableDataSearchKeywords(e.target.value);
                  if (e.target.value.length == 0) {
                    set_tableDataFilterParams({
                      ...tableDataFilterParams,
                      current: 1,
                      typeName: '',
                    });
                  }
                }}
                onSearch={() => tableDataSearchHandle('typeName')}
              />
            </div>
          </div>
          <div className="btnGroup">
            <UpDataActBtn record type="ADD" />
          </div>
        </div>
        <div style={{ marginTop: 16 }}>
          {currentSelectedTreeNode && (
            <KCTable
              columns={columns}
              scroll={{ y: `calc(100vh - 250px)` }}
              reload={reload}
              rowKey="id"
              newVer
              params={tableDataFilterParams}
              request={(params) => getTableData(params)}
              onChange={handleTableChange}
            />
          )}
        </div>
      </div>
    </div>
  );
}
