/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2022-07-12 11:14:21
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2025-04-25 17:40:50
 * @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 { Dropdown, Empty, Input, Popconfirm, Tabs, Modal, Form, message } from 'antd';
import { ModalForm, ProFormInstance, ProFormText, ProFormTextArea } from '@ant-design/pro-form';

import DrawerForm from './DrawerForm/drawer';
import { createFromIconfontCN, DownOutlined } from '@ant-design/icons';
import {
  addIndicatorManaList,
  applyOnlineReportMap,
  delIndicatorManaList,
  editIndicatorManaList,
  getIndicatorCateList,
  getIndicatorDetailReq,
  getIndicatorManaList,
  IndicatorManaItemType,
  saveIndicatorBindItems,
} from '@/service/indicator';

import './style.less';
import { getIndicatorDictionary, IndicatorDictionaryDataType } from '@/service/dictionary';
import { useHistory, useLocation, useModel, useParams } from 'umi';
import { KCIMLeftList } from '../../components/KCIMLeftList';
import KCTable from '@/components/kcTable';
import { KCInput } from '@/components/KCInput';
import generateTableData from '../dataFilling/fillingMana/generateTableData';
import { DATAFILL_PERIODTYPE } from '../dataFilling/fillingMana';
import FrameComponent from './frameContainer';

const defaultYear = new Date().getFullYear();
let table_columns: any[] = [];
let total_tableDataSource: any[] = [];

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

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 [cateId, set_cateId] = useState<string>();
  const [tableColumns, set_tableColumns] = useState<ProColumns[]>([]);
  const [tableDataFilterParams, set_tableDataFilterParams] = useState<TableRequestParamsType>({
    current: 1,
    pageSize: 10,
    name: '',
  });
  const [tableDataSearchKeywords, set_tableDataSearchKeywords] = useState<string>('');
  const [currentSelectedLeft, set_currentSelectedLeft] = useState<any>(undefined);
  const [actionType, set_actionType] = useState<'NORMAL' | 'DETAIL' | undefined>('NORMAL');
  const [drawerActype, set_drawerActype] = useState<'ADD' | 'EDIT' | 'DATAMANA' | undefined>(undefined);
  const [tableDataSource, set_tableDataSource] = useState<any[]>([]);
  const [currentYear, set_currentYear] = useState(defaultYear);
  const [currentEditRow, set_currentEditRow] = useState<any>(undefined);
  const detailTableRef = useRef<ActionType>();

  const [currentBigTab, set_currentBigTab] = useState('2');
  const indicatorTableRef = useRef<ActionType>();
  const history: any = useHistory();
  const [currentTab, set_currentTab] = useState('1');
  const { indicatorType: indicatorUrlType }: { id: string; indicatorType: string } = history.location.query;

  const [reportModalVisible, setReportModalVisible] = useState(false);
  const reportForm = useRef<ProFormInstance>();

  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="link"
                onClick={() => {
                  set_currentEditRow(record);
                  set_actionType('DETAIL');
                }}
              >
                相关数据
              </a>
            ),
          },
          {
            key: '2',
            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 IconFont = createFromIconfontCN({
    scriptUrl: '',
  });

  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({
        menuCode: cateId as string,
        menuType: indicatorUrlType,
        indicatorName: name,
        indicatorType: indicatorType,
        outsideIndexes: outsideIndexes && outsideIndexes.length > 0 ? outsideIndexes[outsideIndexes.length - 1] : '',
        current,
        pageSize
      });

      if (resp && resp[0]) {
        return {
          data: resp[0].children as unknown as [],
          success: true,
          total: resp[0].total || resp[0].children?.length || 0
        };
      } else {
        return {
          data: [],
          success: true,
          total: 0
        };
      }
    }

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

  const getIndicatorCateTree = async () => {
    if (indicatorUrlType) {
      const resp = await getIndicatorCateList({ menuType: indicatorUrlType });
      if (resp) {
        set_indicatorCateTreeData(resp);
      } else {
        set_indicatorCateTreeData([]);
        indicatorTableRef.current?.reload();
      }
    }
  };

  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) => {
    if (drawerActype == 'DATAMANA') {
      const resp = await saveIndicatorBindItems(data);
      if (resp) {
        set_drawerVisible(false);
        getIndicatorDetail();
      }
    }

    if (drawerActype != 'DATAMANA') {
      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 tableDataSearchHandle = (paramName: string) => {
    set_tableDataFilterParams({
      ...tableDataFilterParams,
      current: 1,
      [`${paramName}`]: tableDataSearchKeywords
    });
  }

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

  const detailTableDataSearchHandle = (paramName: string) => {
    const result = total_tableDataSource.filter((a: any) => a[`${paramName}`].indexOf(tableDataSearchKeywords) != -1);
    set_tableDataSource(result);
  };

  const tabChangeHandle = (key: string) => {
    set_currentTab(key);
  };

  const getIndicatorDetail = async () => {
    if (currentEditRow) {
      set_tableColumns([]);
      set_tableDataSource([]);
      const resp = await getIndicatorDetailReq({ indicatorCode: currentEditRow.code, dataYear: `${currentYear}`, periodType: currentTab });
      if (resp) {
        const { itemTitles, itemDatas } = resp;
        const { columns, dataSource } = generateTableData(itemTitles, itemDatas);
        table_columns = columns;
        total_tableDataSource = dataSource;
        set_tableColumns(columns);
        set_tableDataSource(dataSource);
      }
    }
  };

  const dataManaBtnHandle = () => {
    set_drawerActype('DATAMANA');
    set_currentEditRowData({ ...currentEditRow });
    set_drawerVisible(true);
  };

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

  useEffect(() => {
    if (!currentEditRow) {
      set_actionType('NORMAL');
    }
  }, [currentEditRow]);

  useEffect(() => {
    if (actionType == 'DETAIL' && currentBigTab === '2') {
      getIndicatorDetail();
    }
  }, [actionType, currentBigTab]);

  useEffect(() => {
    getIndicatorDetail();
  }, [currentTab, currentYear]);

  useEffect(() => {
    set_cateId(undefined);
    set_actionType(undefined);
    set_drawerActype(undefined);
    set_currentBigTab('1');
    set_currentEditRow(undefined);
    set_tableColumns([]);
    set_tableDataSource([]);
    set_currentEditRowData(undefined);

    getIndicatorCateTree();
  }, [location.search]);

  useEffect(() => {
    if (!drawerVisible) {
      set_drawerActype(undefined);
      set_currentEditRowData(undefined);
    }
  }, [drawerVisible]);

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

  // // 当弹窗可见性变化时，处理表单回显
  // useEffect(() => {
  //   console.log('Modal visibility changed:', reportModalVisible); // 日志 1: 检查可见性变化
  //   if (reportModalVisible && currentEditRow) {
  //     console.log('Attempting to set form values. currentEditRow:', currentEditRow); // 日志 2: 检查 currentEditRow 内容
  //     const valuesToSet = {
  //       reportId: currentEditRow.onlineReportCode,
  //       remark: currentEditRow.onlineRemark
  //     };
  //     console.log('Values to set:', valuesToSet); // 日志 3: 检查要设置的值
  //     try {
  //       reportForm?.current?.setFieldsValue(valuesToSet);
  //       console.log('setFieldsValue called successfully.'); // 日志 4: 确认调用成功
  //     } catch (e) {
  //       console.error('Error calling setFieldsValue:', e); // 日志 5: 检查调用是否出错
  //     }
  //   } else if (reportModalVisible) {
  //       console.log('Modal is visible, but currentEditRow is missing or empty:', currentEditRow); // 日志 6: 检查 currentEditRow 是否为空
  //   }
  //   // ModalForm 的 destroyOnClose 会处理关闭时的重置
  // }, [reportModalVisible, currentEditRow, reportForm]); // 依赖项

  // 打开报告管理弹窗
  const openReportModal = () => {
    setReportModalVisible(true);
  };

  // 处理报告表单提交
  const handleReportSubmit = async (values: any) => {
    try {
      const resp = await applyOnlineReportMap({
        code: currentEditRow.code,
        onlineReportCode: values.reportId,
        onlineRemark: values.remark
      });
      if (resp) {
        message.success('提交成功');
        set_currentEditRow((prevRow: any) => ({
          ...prevRow,
          onlineRemark:values.remark,
          onlineReportCode: values.reportId
        }));
        return true; // 提交成功后关闭弹窗
      }
    } catch (error) {
      console.error('表单验证或提交失败:', error);
      message.error('提交失败'); // 添加错误提示
      return false; // 提交失败，保持弹窗打开
    }
    // 如果 API 调用失败 (resp 为 false)，显式返回 false
    message.error('提交失败');
    return false;
  };

  return (
    <div className="IndicatorMana">
      <DrawerForm actType={drawerActype} visible={drawerVisible} onVisibleChange={onVisibleChangeHandle} onFinish={(data) => drawerFormCommitHanndle(data)} record={currentEditRowData} />

      {/* 报告管理弹窗 */}
      <ModalForm
        title="报告管理"
        visible={reportModalVisible}
        onVisibleChange={setReportModalVisible}
        onFinish={handleReportSubmit}
        width={500}
        initialValues={currentEditRow&&{reportId: currentEditRow.onlineReportCode,
          remark: currentEditRow.onlineRemark}}
        formRef={reportForm}
        modalProps={{ 
          destroyOnClose: true,
          bodyStyle: {
            maxHeight: '72vh',
            overflowY: 'auto',
            overflowX: 'hidden'
          }
        }}
      >
        <ProFormText
          name="reportId"
          label="关联报告ID"
          placeholder="请输入"
          rules={[{ required: true, message: '请输入关联报告ID' }]}
        />
        <ProFormTextArea
          name="remark"
          label="备注说明"
          placeholder="请输入"
          fieldProps={{
            rows: 4,
          }}
        />
      </ModalForm>

      {actionType == 'DETAIL' && (
        <div className="FillingMana-detail">
          <div className="FillingMana-detail-header">
            <div className="FillingMana-detail-header-title">
              <div className="backBtn" onClick={() => set_currentEditRow(undefined)}>
                <IconFont style={{ fontSize: 15 }} type={'iconfanhui'} />
              </div>
              <span>{currentEditRow?.name}</span>
            </div>
            <div className="FillingMana-detail-header-title-sub">
              <span>指标编码：{currentEditRow?.code}</span>
              <span>指标定义：{currentEditRow?.targetDefinition}</span>
            </div>
          </div>
          <div className="bigTab" title={`${currentBigTab == '1'}`}>
            <div className={currentBigTab === '1' ? 'tab on' : 'tab'} onClick={() => set_currentBigTab('1')}>
              线上数据
            </div>
            <div className={currentBigTab === '2' ? 'tab on' : 'tab'} onClick={() => set_currentBigTab('2')}>
              填报数据
            </div>
          </div>

          {currentBigTab === '1' && (
            <div className="currentBigTab1content">
              {/* <img src={require('../../../../../public/images/empty_bigger.png')} alt="" />
              <div className="detail-noAuthRecord-title">暂无内容</div> */}
              <div className='currentBigTab1content_header'>
                <span>{currentEditRow?.onlineRemark}</span>
                <div className='btn' onClick={openReportModal}>
                  <IconFont type='iconpeizhi' /> 报告管理
                </div>
              </div>
              {(currentEditRow&&currentEditRow.onlineReportCode)&&<FrameComponent link={`/platform/setting/embeddedDashboard/${currentEditRow.onlineReportCode}?noTopbar=true&noMenu=true`} />}
            </div>
          )}

          {currentBigTab === '2' && (
            <div className="FillingMana-detail-content">
              <div className="tabBar">
                <Tabs defaultActiveKey={currentTab} onChange={tabChangeHandle} items={DATAFILL_PERIODTYPE.map((a) => ({ label: a.label, key: `${a.value}` }))} />
                <div className="dataManaBtn" onClick={() => dataManaBtnHandle()}>
                  <IconFont type={'iconpeizhi'} style={{ position: 'relative', top: 1, paddingRight: 4 }} />
                  数据管理
                </div>
              </div>

              <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={() => detailTableDataSearchHandle('fillItemName')} />}
                      onChange={(e) => {
                        set_tableDataSearchKeywords(e.target.value);
                        if (e.target.value.length == 0) {
                          set_tableDataSource(total_tableDataSource);
                        }
                      }}
                      onPressEnter={(e: any) => {
                        const result = total_tableDataSource.filter((a: any) => a.fillItemName.indexOf(e.target.value) != -1);
                        set_tableDataSource(result);
                      }}
                    />
                  </div>
                </div>
                <div className="btnGroup">
                  <div className="changeBtn">
                    <div className="actBtn" onClick={() => set_currentYear(currentYear - 1)}>
                      <IconFont type={'iconshuangzuo'} />
                    </div>
                    <span style={{ padding: '0 8px' }}>{currentYear}</span>
                    <div className="actBtn" onClick={() => set_currentYear(currentYear + 1)}>
                      <IconFont type={'iconshuangyou'} />
                    </div>
                  </div>
                </div>
              </div>
              <KCTable newVer actionRef={detailTableRef} columns={[...tableColumns]} scroll={{ y: 'calc(100vh - 232px)' }} rowKey="id" dataSource={tableDataSource} pagination={false} />
            </div>
          )}
        </div>
      )}
      {actionType != 'DETAIL' && (
        <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
                newVer
                rowKey="menuId"
                columns={columns}
                params={tableDataFilterParams}
                actionRef={indicatorTableRef}
                scroll={{ y: `calc(100vh - 228px)` }}
                expandable={{
                  expandedRowKeys: defaultExpandedRowKeys,
                  onExpand: (expanded, record) => {
                    // console.log({expanded, record});
                    let _expandedKeys = [...defaultExpandedRowKeys];
                    if (expanded) {
                      _expandedKeys.push(record.menuId);
                    } else {
                      const index = _expandedKeys.findIndex((t) => t == `${record.menuId}`);
                      if (index != -1) {
                        _expandedKeys.splice(index, 1);
                      }
                    }
                    set_defaultExpandedRowKeys([..._expandedKeys]);
                  },
                }}
                reload={reloadTable}
                pagination={false}
                options={false}
                request={(params) => getData(params)}
                onChange={handleTableChange}
              />
            )}
          </div>
        </div>
      )}
    </div>
  );
};

export default IndicatorMana;
