import {ProCard} from '@ant-design/pro-components';
import {CheckCardList} from '../../components/CheckCardList';
import {FilterPanel} from '../../components/FilterPanel';
import {useCallback, useEffect, useMemo, useRef, useState} from 'react';
import {useAppDispatch, useAppSelector} from "../../../redux/configureStore";
import {selectDataSet} from "../MainPage/slice/selectors";
import {getAllDataset, queryDataSet} from "../MainPage/slice/thunks";
import {TYPE_ENUM} from "../../constants";
import moment from "moment";
import useI18NPrefix from "../../hooks/useI18NPrefix";


export const DataSetPage =()=>{
  const t = useI18NPrefix('global');
  const dispatch = useAppDispatch();
  const dataset = useAppSelector(selectDataSet);
  const [queryData,setQueryData] = useState({});
  const [loading, setLoading] = useState(false);
  const [options,setOptions]=useState({});
  const recordRef = useRef(null);
  useEffect(() => {
    dispatch(getAllDataset({}))
  }, []);

  const cardList = useMemo(
    ()=>
      dataset && dataset.map(value=>({
        value,
        title: value.name,
      }))
    ,[dataset]
  );

  const onCardSelect = (value)=>{
    recordRef.current = value
    const {dimensionList,metricList} = value
    const dimension = (dimensionList||[])
      // .filter(v=>v?.type!==DIM_TYPE_ENUM.DATETIME)
      .map(v=>({
        label:v.description||v.name,
        value:v.id,
        bizName:v.bizName,
        semanticType:v.semanticType,
        type:TYPE_ENUM.DIMENSION
      }))
    const metric = (metricList||[]).map(v=>({
      label:v.description||v.name,
      value:v.id,
      bizName:v.bizName,
      type:TYPE_ENUM.METRIC
    }))
    setOptions({dimension,metric})
  }

  /** 查询数据集结果 */
  const onFilterChange =async ({days, dimension,metric, tags})=>{
    const groups = (dimension||[]).filter(item=>item.semanticType!=='DATE').map(item=>item.bizName)
    let dateInfo = {
      dateMode: "BETWEEN",
      startDate: moment().subtract(days ? days : 0, 'days').format('YYYY-MM-DD'),
      endDate: moment().format('YYYY-MM-DD'),
      dateList: [],
      unit: 0,
      period: 'day',
      detectWord: "",
      isInherited: false,
      groupByDate: groups.length<dimension?.length
    }
    let dimensionFilters = [];
    (tags||[]).forEach(tag=>{
      const dimensionObj = JSON.parse(tag.dimension);
      if (dimensionObj.semanticType!=="DATE"){
        dimensionFilters.push({
          id: tag.value,
          relation: "FILTER",
          bizName: dimensionObj.bizName,
          name: tag.bizName,
          operator: tag.condition,
          value: tag.keyword,
          semanticType: dimensionObj.semanticType,
          children: []
        })
      }else {
        dateInfo = {
          dateMode: "BETWEEN",
          startDate: tag.startDate,
          endDate: tag.endDate,
          dateList: [],
          unit: 0,
          period: 'day',
          detectWord: "",
          isInherited: false,
          groupByDate: true
        }
      }
    })
    const params = {
      limit: 10000,
      sql: "",
      queryType: "DETAIL",
      dataSetId: recordRef?.current?.id,
      dataSetName: recordRef?.current?.name,
      dateInfo,
      dimensionFilters,
      needAuth: false,
      groups,
      aggregators:(metric||[]).map(item=>({
        column: item.bizName,
        func: "SUM",
        nameCh: "",
        args: [],
        alias: item.label
      })),
      orders: [],
      params: [],
      cacheInfo: {
        cache: false
      },
      metricFilters: [],
    }
    setLoading(true)
    await dispatch(queryDataSet({
      params,
      resolve(data) {
        setQueryData(data)
      }
    }))
    setLoading(false)
  }

  const onSearch = useCallback((e)=>{},[]);

  return (
    <ProCard gutter={8} ghost >
      <ProCard bordered headerBordered colSpan="20%" title={t("title.dataset")} style={{height:'85vh'}}>
        <CheckCardList
          value={recordRef.current}
          options={cardList}
          onSelect={onCardSelect}
          onSearch={onSearch}
        />
      </ProCard>
      <ProCard bordered headerBordered title={recordRef?.current?.name||t("title.queryResult")} style={{height:'85vh'}}>
        <FilterPanel
          delay={1000}
          options={options}
          onChange={onFilterChange}
          loading={loading}
          dataSource={queryData}
          requires={['metric']}
        />
      </ProCard>
    </ProCard>
  )
}
