/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2022-07-12 11:14:21
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2025-03-07 16:00:03
 * @FilePath: /KC-MiddlePlatform/src/pages/platform/setting/indicatorMana/index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

import { ActionType, ProColumns } from '@ant-design/pro-table';
import React, { useEffect, useRef, useState } from 'react';
import { Button, Divider, Dropdown, Popconfirm } from 'antd';

import { DownOutlined } from '@ant-design/icons';
import { addIndicatorManaList, delIndicatorManaList, editIndicatorManaList, getIndicatorCateList_old, getIndicatorManaList_old, IndicatorManaItemType } from '@/service/indicator';
import TreeDirectory from './TreeDirectory';

import './style.less';
import { getIndicatorDictionary, IndicatorDictionaryDataType } from '@/service/dictionary';
import { useLocation } from 'umi';
import { KCIMLeftList } from '../../components/KCIMLeftList';
import KCTable from '@/components/kcTable';
import { KCInput } from '@/components/KCInput';
import DrawerForm from './ DrawerForm/drawer';

const IndicatorMana = () => {
  const [reloadTable, set_reloadTable] = useState(false);
  const [drawerVisible, set_drawerVisible] = useState(false);
  const [indicateType, set_indicateType] = useState<IndicatorDictionaryDataType[]>([]);
  const [currentEditRowData, set_currentEditRowData] = useState<any | undefined>(undefined);
  const [indicatorCateTreeData, set_indicatorCateTreeData] = useState<any[]>([]);
  const [defaultExpandedRowKeys, set_defaultExpandedRowKeys] = useState<string[]>([]);
  const [tableData, set_tableData] = useState<any[]>([]);
  const [cateId, set_cateId] = useState<string>();

  const [tableDataFilterParams, set_tableDataFilterParams] = useState<{
    current: number;
    pageSize: number;
    name?: string;
    indicatorType?: string;
    outsideIndexes?: string[];
  }>({
    current: 1,
    pageSize: 10
  });
  const [tableDataSearchKeywords, set_tableDataSearchKeywords] = useState<string>('');
  const [currentSelectedLeft, set_currentSelectedLeft] = useState<any>(undefined);

  const [drawerActype, set_drawerActype] = useState<'ADD' | 'EDIT'>('ADD');

  const indicatorTableRef = useRef<ActionType>();

  const columns: ProColumns<any>[] = [
    {
      title: '指标名称',
      dataIndex: 'name',
      hideInSearch: false,
      ellipsis: true,
    },
    // {
    //   title: '指标编码',
    //   dataIndex: 'code',
    //   ellipsis: true,
    //   render: (text, record) => {
    //     if (record) {
    //       const { indicatorBoolean, code } = record;
    //       return indicatorBoolean ? code : ''
    //     } else {
    //       return ''
    //     }

    //   }
    // },
    {
      title: '指标类别',
      dataIndex: 'indicatorType',
      hideInSearch: true,
      ellipsis: true,
      hideInTable: true,
      valueType: 'select',
      request: async () => {
        const resp = await getIndicatorDictionary();
        if (resp) {
          const data = resp.filter((t) => t.code == 'IndicatorType');
          if (data.length > 0) {
            return data[0].children.map((t) => ({ label: t.name, value: t.code }));
          }
        }
        return [];
      },
      render: (text, record) => {
        if (record) {
          const { indicatorBoolean, indicatorTypeList } = record;
          return indicatorBoolean && indicatorTypeList ? indicatorTypeList.map((t: any) => t.name).join('/') : '';
        } else {
          return '';
        }
      },
    },
    {
      title: '外部指标',
      dataIndex: 'outsideIndexes',
      hideInSearch: true,
      ellipsis: true,
      hideInTable: true,
      valueType: 'cascader',
      fieldProps: {
        fieldNames: { label: 'name', value: 'code' },
        placeholder: '请选择',
      },

      request: async () => {
        const resp = await getIndicatorDictionary();
        if (resp) {
          const data = resp.filter((t) => t.code == 'IndicatorExternal');
          if (data.length > 0) {
            return data[0].children;
          }
        }
        return [];
      },
      render: (text, record) => {
        if (record) {
          const { indicatorBoolean, indicatorExternalList } = record;
          return indicatorBoolean ? (indicatorExternalList ? indicatorExternalList.map((t: any) => t.name).join('/') : '-') : '';
        } else {
          return '';
        }
      },
    },
    {
      title: '指标编码',
      dataIndex: 'code',
      width: 80,
      hideInSearch: true,
      ellipsis: true,
    },
    {
      title: '指标定义',
      dataIndex: 'targetDefinition',
      hideInSearch: true,
      ellipsis: true,
    },

    {
      title: '操作',
      width: 90,
      key: 'option',
      valueType: 'option',
      render: (text, record) => {
        const items = [
          {
            key: '1',
            label: (
              <a key="linka" href={record.indicatorPath} target="_blank">
                数据展示
              </a>
            ),
          },
          {
            key: '3',
            label: (
              <Popconfirm title="是否确定删除?" onConfirm={() => delHandle(record)} okText="确定" cancelText="取消" key="link2">
                <a>删除</a>
              </Popconfirm>
            ),
          },
        ];

        if (record && record.indicatorBoolean) {
          return [
            <a key="link3" onClick={() => actionHandle('EDIT', record)}>
              管理
            </a>,
            <Dropdown menu={{ items }}>
              <a>
                <DownOutlined />
              </a>
            </Dropdown>,
          ];
        }

        return [];
      },
    },
  ];

  const getIndicatorDir = async () => {
    const resp = await getIndicatorDictionary();
    if (resp) {
      set_indicateType(resp);
    }
  };

  const getData = async (params: any) => {
    const { current = 1, pageSize = 10, name, indicatorType, outsideIndexes } = params;
    if (cateId) {
      const resp = await getIndicatorManaList_old({
        current,
        pageSize,
        menuCode: cateId as string,
        indicatorName: name,
        indicatorType: indicatorType,
        outsideIndexes: outsideIndexes && outsideIndexes.length > 0 ? outsideIndexes[outsideIndexes.length - 1] : '',
      });

      if (resp && resp[0] && resp[0].children) {
        const getName: any = (obj: any) => {
          let isArr = Array.isArray(obj);
          let reslut = [];
          if (isArr) {
            obj.forEach((item: any) => {
              reslut.push(...getName(item));
            });
          } else {
            reslut.push(obj.menuId);

            if (obj.children) {
              reslut.push(...getName(obj.children));
            }
          }
          return reslut;
        };

        set_tableData(resp[0].children as unknown as []);

        set_defaultExpandedRowKeys(getName(resp[0].children));

        return {
          data: resp[0].children as unknown as [],
          success: true,
          total: 1,
        };
      } else {
        return {
          data: [],
          success: true,
          total: 0,
        };
      }
    }

    return {
      data: [],
      success: false,
      total: 0,
    };
  };

  const getIndicatorCateTree = async () => {
    // console.log(location.search);
    let menuId = '';
    if (location.search.length > 0) {
      const searchArr = location.search.split('=');
      // console.log({ searchArr });
      if (searchArr[1]) {
        const resp = await getIndicatorCateList_old({ menuCode: searchArr[1] });
        if (resp) {
          set_indicatorCateTreeData(resp);
        }
      }
    }
  };

  const actionHandle = async (key: 'EDIT' | 'DEL', record: IndicatorDictionaryDataType) => {
    set_currentEditRowData(record);
    if (key == 'EDIT') {
      set_drawerActype('EDIT');
      set_drawerVisible(true);
    }
  };

  const addHandle = () => {
    set_drawerActype('ADD');
    set_currentEditRowData(undefined);
    set_drawerVisible(true);
  };

  const delHandle = async (record: IndicatorDictionaryDataType) => {
    const resp = await delIndicatorManaList({ id: record.id });
    if (resp) {
      indicatorTableRef.current?.reload();
    }
  };

  const onVisibleChangeHandle = (bool: boolean) => {
    if (!bool) {
      set_drawerVisible(false);
    }
    if (bool) {
      set_drawerVisible(true);
    }
  };

  const drawerFormCommitHanndle = async (data: any) => {
    // const formData = Object.assign({}, data[0].baseInfoformRef, data[1].manaInfoformRef, data[2].showSetInfoformRef, data[3].adminInfoformRef);
    //const _formData = {...data[0].baseInfoformRef,...data[1].manaInfoformRef,...data[2].showSetInfoformRef,...data[3].adminInfoformRef}

    let formData: any;
    data.forEach((element: any) => {
      if (element.baseInfoformRef) {
        formData = { ...formData, ...element.baseInfoformRef };
      }
      if (element.manaInfoformRef) {
        formData = { ...formData, ...element.manaInfoformRef };
      }
      if (element.showSetInfoformRef) {
        formData = { ...formData, ...element.showSetInfoformRef };
      }
      if (element.adminInfoformRef) {
        formData = { ...formData, ...element.adminInfoformRef };
      }
    });

    if (drawerActype == 'ADD') {
      const resp = await addIndicatorManaList({
        ...formData,
        caseBreakdown: formData.caseBreakdown ? formData.caseBreakdown.join('/') : '',
        dataDownload: formData.dataDownload ? formData.dataDownload.join('/') : '',
        drillLevel: formData.drillLevel ? formData.drillLevel.join('/') : '',
        dataSum: formData.dataSum ? formData.dataSum.join('/') : '',
        chartType: formData.chartType ? formData.chartType.join('/') : '',

        indicatorMenuList: formData.indicatorMenuList ? formData.indicatorMenuList : [],
        indicatorTypeList: formData.indicatorTypeList ? formData.indicatorTypeList : [],
        indicatorExternalList: formData.indicatorExternalList ? formData.indicatorExternalList : [],
        divisionId: `${formData.divisionId}`,
      });

      if (resp) {
        set_drawerVisible(false);
        indicatorTableRef.current?.reload();
      }
    }

    if (drawerActype == 'EDIT') {
      const resp = await editIndicatorManaList({
        ...currentEditRowData,
        ...formData,
        caseBreakdown: formData.caseBreakdown ? formData.caseBreakdown.join('/') : '',
        dataDownload: formData.dataDownload ? formData.dataDownload.join('/') : '',
        drillLevel: formData.drillLevel ? formData.drillLevel.join('/') : '',
        dataSum: formData.dataSum ? formData.dataSum.join('/') : '',
        chartType: formData.chartType ? formData.chartType.join('/') : '',
      });
      if (resp) {
        set_drawerVisible(false);
        indicatorTableRef.current?.reload();
      }
    }
  };

  const onSelectChangehandle = (currentSelected: any) => {
    set_currentSelectedLeft(currentSelected);
    currentSelected && set_cateId(currentSelected.code);
  };

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

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

  useEffect(() => {
    if (tableData) {
      const keys = tableData.map((t: any) => (t ? t.code : ''));
    }
  }, [tableData]);

  useEffect(() => {
    console.log({ cateId });
    indicatorTableRef.current?.reload();
  }, [cateId]);

  useEffect(() => {
    getIndicatorCateTree();
  }, [location.search]);

  useEffect(() => {
    getIndicatorDir();
    getIndicatorCateTree();
  }, []);

  return (
    <div className="IndicatorMana">
      <DrawerForm actType={drawerActype} visible={drawerVisible} onVisibleChange={onVisibleChangeHandle} onFinish={(data) => drawerFormCommitHanndle(data)} record={currentEditRowData} />
      <div className="content">
        <div className="left">
          {/* <TreeDirectory data={indicatorCateTreeData} onSelectChange={(info) => onSelectChangehandle(info)} /> */}
          <KCIMLeftList
            searchKey={'name'}
            listType="tree"
            dataSource={indicatorCateTreeData}
            fieldNames={{ title: 'name', key: 'code' }}
            contentH={'100%'}
            onChange={(info) => onSelectChangehandle(info)}
          />
        </div>
        <div className="right">
          <div className="tableTitle">{currentSelectedLeft && currentSelectedLeft.name}</div>
          <div className="toolBar">
            <div className="filter">
              <div className="filterItem">
                <KCInput
                  placeholder={'指标名称'}
                  style={{ width: 240 }}
                  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">
              <span className="add" onClick={addHandle}>
                新增
              </span>
            </div>
          </div>
          {cateId && (
            <KCTable
              columns={columns}
              scroll={{ y: `calc(100vh - 250px)` }}
              reload={reloadTable}
              rowKey="id"
              newVer
              params={tableDataFilterParams}
              request={(params) => getData(params)}
              onChange={handleTableChange}
            />
          )}
        </div>
      </div>
    </div>
  );
};

export default IndicatorMana;
