/*
 * @Author: code4eat awesomedema@gmail.com
 * @Date: 2022-07-12 11:14:21
 * @LastEditors: code4eat awesomedema@gmail.com
 * @LastEditTime: 2022-07-20 10:44:16
 * @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 KCTable from '@/components/kcTable';
import { ActionType, ProColumns } from '@ant-design/pro-table';
import React, { useEffect, useRef, useState } from 'react'
import { Button, Drawer, Popconfirm } from 'antd'
import Divider from '@ant-design/pro-card/lib/components/Divider';
import DrawerForm from './DrawerForm/drawer';
import ProForm from '@ant-design/pro-form/lib/layouts/ProForm';
import { addIndicatorManaList, delIndicatorManaList, editIndicatorManaList, getIndicatorCateList, getIndicatorManaList, IndicatorManaItemType } from '@/service/indicator';
import TreeDirectory from './TreeDirectory';

import './style.less';
import { getIndicatorDictionary, IndicatorDictionaryDataType } from '@/service/dictionary';
import { useLocation } from 'umi';


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 [drawerActype, set_drawerActype] = useState<'ADD' | 'EDIT'>('ADD');

  const indicatorTableRef = useRef<ActionType>();


  const columns: ProColumns<any>[] = [
    {
      title: '指标名称',
      dataIndex: 'name',
      hideInSearch: false,
      width: '30%',
      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',
      hideInSearch:true,
      width: '10%',
      ellipsis: true,

    },
    {
      title: '指标定义',
      dataIndex: 'targetDefinition',
      hideInSearch:true,
      width: '30%',
      ellipsis: true,

    },

    {
      title: '操作',
      width: 200,
      key: 'option',
      valueType: 'option',
      render: (text, record) => {


        if (record && record.indicatorBoolean) {
          return (
            [
              <a key="linka" href={record.indicatorPath} target='_blank'>
                数据展示
              </a>,
              <a key="link3" onClick={() => actionHandle('EDIT', record)}>
                管理信息
              </a>,
              <Popconfirm
                title="是否确定删除?"
                onConfirm={() => delHandle(record)}
                okText="确定"
                cancelText="取消"
                key="link2"
              >
                <a>删除</a>
              </Popconfirm>,
            ]
          )
        }

        return []
      }
      ,
    },
  ];


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

  const getData = async (params: any) => {
    const { current = 1, name, indicatorType, outsideIndexes } = params;

    console.log({params});
    if(cateId){
      const resp = await getIndicatorManaList({
        current:1,
        pageSize:0,
        menuCode: cateId as string,
        indicatorName: name,
        indicatorType: indicatorType,
        outsideIndexes: outsideIndexes && outsideIndexes.length > 0 ? outsideIndexes[outsideIndexes.length - 1] : ''
      });
  
      if (resp&&resp[0]) {
  
        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({ 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) => {
    // console.log({ currentSelected });
    set_cateId(currentSelected.code);
  }

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


  useEffect(() => {
    // console.log({ cateId });
    // set_reloadTable(true);
    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)} />
        </div>
        <div className='right'>
          {
            cateId && (
              <KCTable
                className='indicatorTable'
                rowKey="menuId"
                headerTitle="指标管理"
                columns={columns}
                actionRef={indicatorTableRef}
                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}
                search={{
                  span: 8
                }}
                tableStyle={{ height: 600, overflow: 'scroll' }}
                pagination={{pageSize:100}}
                toolBarRender={() => [
                  // <Button key="1" onClick={addHandle}>
                  //   上传
                  // </Button>,
                  // <Button key="2" onClick={addHandle}>
                  //   下载
                  // </Button>,
                  <Button key="3" type="primary" onClick={addHandle}>
                    新增
                  </Button>,
                ]}
                request={(params) => getData(params)}
              />
            )
          }
        </div>
      </div>

    </div>
  )
}

export default IndicatorMana