/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2023-03-03 11:30:33
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2025-02-18 15:10:01
 * @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, ProFormDependency, ProFormInstance, 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, { Key, useEffect, useRef, 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';
import { getPubDicData } from '@/service/public';
import { getCurrentHospAllDepartments, getCurrentHospAllEmps } from '@/service/hospList';

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

export default function PubDicTypeMana() {
  const [tableDataFilterParams, set_tableDataFilterParams] = useState<TableRequestParamsType>({
    current: 1,
    pageSize: 10,
    name: ''
  });
  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 [defaultSelectedKeys, set_defaultSelectedKeys] = useState<Key[]>([]);

  const columns: ProColumns[] = [
    {
      title: '参数等级',
      dataIndex: 'levelName',
    },
    {
      title: '作用对象',
      dataIndex: 'targetName',
    },
    {
      title: '参数值',
      dataIndex: 'value',
    },
    {
      title: '启用',
      dataIndex: 'status',
      hideInTable: currentSelectedTreeNode?.status != 1,
      renderText(val, record, index, action) {
        return <Switch size="small" checked={val ? true : false} onChange={(bool) => chnageDicOpenStatHandle(bool, record)} />;
      },
    },
    {
      title: '操作',
      key: 'option',
      width: 120,
      hideInTable: currentSelectedTreeNode?.status != 1,
      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({ id: record.id, status: bool ? '1' : '0' });
    if (resp) {
      set_reload(true);
    }
  };

  const getTableData = async (params: any) => {
    const resp = await getData({ ...params, parameterCode: 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.id);
    if (resp) {
      set_reload(true);
      // message.success('操作成功!');
    }
  };

  const updateTable = async (formVal: any, type: 'EDIT' | 'ADD') => {
    if (type == 'ADD') {
      const resp = await addData({
        code: currentSelectedTreeNode.code,
        level: formVal.level,
        systemId: currentSelectedTreeNode.systemId,
        targetCode: formVal.target.value,
        targetName: formVal.target.label,
        value: formVal.value,
      });
      if (resp) {
        set_reload(true);
      }
    }
    if (type == 'EDIT') {
      const { id, status } = currentEdit;
      const resp = await editData({
        id: id,
        value: formVal.value,
        level: formVal.level,
        status: status,
        systemId: currentSelectedTreeNode.systemId,
        targetCode: formVal.target.value,
        targetName: formVal.target.label,
      });
      if (resp) {
        set_reload(true);
      }
    }
  };

  const UpDataActBtn = ({ record, type }: { record: any; type: 'EDIT' | 'ADD' }) => {
    const formRef = useRef<ProFormInstance>();
    return (
      <ModalForm
        title={`${type == 'EDIT' ? '编辑' : '新增'}参数(${currentSelectedTreeNode && currentSelectedTreeNode.name})`}
        width={352}
        formRef={formRef}
        initialValues={type == 'EDIT' ? { ...record, level: `${record.level}`, target: { label: record.targetName, value: record.targetCode } } : {}}
        trigger={
          type == 'EDIT' ? (
            <a
              key="edit"
              onClick={(e) => {
                e.stopPropagation();
                set_currentEdit(record);
              }}
            >
              编辑
            </a>
          ) : (
            <span className="add">新增</span>
          )
        }
        onFinish={(val) => {
          return updateTable(val, type);
        }}
      >
        <ProFormSelect
          name="level"
          label="参数等级："
          placeholder="请选择院区"
          request={async () => {
            const resp = await getPubDicData('PARAMS_LEVEL');
            if (resp) {
              const data: any = resp.dataVoList?.map((a: any) => ({
                label: a.name,
                value: a.code,
              }));

              return data;
            }
            return [];
          }}
          fieldProps={{
            size: 'small',
            onChange(value, option) {
              formRef.current?.setFieldValue('target', undefined);
            },
          }}
          rules={[{ required: true, message: '参数等级不能为空!' }]}
        />

        <ProFormDependency name={['level']}>
          {({ level }) => {
            return (
              <ProFormSelect
                name="target"
                label="作用对象："
                placeholder="请选择"
                params={level}
                rules={[{ required: true, message: '作用对象不能为空!' }]}
                request={async () => {
                  if (level == '1') {
                    const currentSelectedHop = localStorage.getItem('currentSelectedSubHop');
                    if (currentSelectedHop) {
                      const { id, name } = JSON.parse(currentSelectedHop);
                      return [
                        {
                          value: id,
                          label: name,
                        },
                      ];
                    }
                  }
                  if (level == '2') {
                    const resp = await getCurrentHospAllDepartments();
                    if (resp) {
                      const data: any = resp.map((a: any) => ({
                        label: a.name,
                        value: a.id,
                      }));

                      return data;
                    }
                  }
                  if (level == '3') {
                    const resp = await getCurrentHospAllEmps();
                    if (resp) {
                      const data: any = resp.map((a: any) => ({
                        label: a.name,
                        value: a.id,
                      }));

                      return data;
                    }
                  }
                  return [];
                }}
                fieldProps={{
                  size: 'small',
                  labelInValue: true,
                }}
              />
            );
          }}
        </ProFormDependency>

        <ProFormTextArea name="value" label="参数值：" placeholder="请输入" rules={[{ required: true, message: '参数值不能为空!' }]} />
      </ModalForm>
    );
  };

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

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

  const getTreeReqFunc = async (name?: string) => {
    const resp = await getTreeData();
    if (resp) {
      const treeData = resp.map((a: any) => ({
        ...a,
        name: a.systemName,
        id: Math.random(),
        children: a.parameters,
      }));
      set_treeData(treeData);
    }
  };

  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: { id: React.Key }) => item.id === key)) {
          parentKey = node.id;
        } 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 { id, name } = node;
      dataList.push({ id, 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.id, 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.id]);
        set_defaultSelectedKeys(node.id);
        console.log({ node, treeData });
      }
    }
  }, [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: 'id' }}
            rootStyle={{ height: '100%', paddingBottom: 50, overflowY: 'scroll', overflowX: 'hidden' }}
            onSelect={onSelect}
            onExpand={onExpand}
            expandedKeys={expandedKeys}
            autoExpandParent={autoExpandParent}
            selectedKeys={currentSelectedTreeNode ? [currentSelectedTreeNode.id] : []}
            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 title =
                index > -1 ? (
                  <span>
                    {beforeStr}
                    <span className="site-tree-search-value" style={{ color: 'red', 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: 'flex-start',
                    alignItems: 'center',
                    height: 32,
                    borderRadius: '4px',
                    overflow: 'hidden',
                    color: '#17181A',
                    textOverflow: 'ellipsis',
                    whiteSpace: 'nowrap',
                  }}
                >
                  {title}
                </div>
              );
            }}
            defaultSelectedKeys={defaultSelectedKeys}
            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="rightTitle">{currentSelectedTreeNode && currentSelectedTreeNode.name}</div>
        <div className="descr">{`默认值：${currentSelectedTreeNode ? currentSelectedTreeNode.value : ''}  丨  参数描述：${currentSelectedTreeNode ? currentSelectedTreeNode.description : ''}`}</div>
        <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,
                      name: ''
                    });
                  }
                }}
                onSearch={() => tableDataSearchHandle('name')}
              />
            </div>
          </div>
          <div className="btnGroup">{currentSelectedTreeNode?.status == 1 && <UpDataActBtn record type="ADD" />}</div>
        </div>
        <div style={{ marginTop: 16 }}>
          <KCTable
            columns={columns}
            scroll={{ y: `calc(100vh - 250px)` }}
            reload={reload}
            rowKey="id"
            newVer
            params={tableDataFilterParams}
            request={(params) => getTableData(params)}
            onChange={handleTableChange}
          />
        </div>
      </div>
    </div>
  );
}
