import {memo, useEffect, useMemo, useRef, useState} from 'react';
import {RadioCheckButton} from './RadioCheckButton.jsx'
import {EditableTags} from './EditableTags'
import {Popconfirm, Space, Spin, Typography} from "antd";
import {ProForm, ProFormDatePicker, ProFormDependency, ProFormSelect, ProFormText} from "@ant-design/pro-components";
import {TIME_COND, WHERE_COND} from "../pages/IndexDefine/constants";
import {DISPLAY_COND} from "../pages/MainPage/constants";
import {ChartsGraph} from "./ChartsGraph";
import useI18NPrefix from "../hooks/useI18NPrefix";
let timer;
const { Text } = Typography;
export const FilterPanel=memo(({
   options,
   dataSource,
   onChange,
   extra,
   delay=0,
   loading,
   requires,
   initCall
})=>{
  const t = useI18NPrefix('global');
  const [tags,setTags] = useState([]);
  const [display,setDisplay] = useState("table");
  const dataRef = useRef({tags});
  const formRef = useRef();

  // 初始化日期维度值
  const dateDimension = useMemo(()=>(options.dimension||[]).find(c=>c.semanticType==="DATE"),[options])

  useEffect(()=>{
    if (initCall){
      dataRef.current.dimension=[dateDimension]
      onChange && onChange({days:0,dimension:[dateDimension],tags:[]})
    }
  },[])

  const callDelay = (time)=>{
    if (requires){
      let quit = false;
      requires.forEach(require=>{
        if (!quit){
          const filter =  dataRef.current[require];
          if (!filter){
            quit = true
            return
          }
          if (Object.prototype.toString.call(filter) === '[object Object]'){
            if (Object.keys(filter).length === 0) {
              quit = true
              return
            }
          }
          if (Array.isArray(filter)){
            if (filter.length < 1){
              quit = true
              return
            }
          }
        }
      })
      if (quit){
        return false
      }
    }


    // 清除之前设置的计时器
    clearTimeout(timer);
    timer = setTimeout(() => {
      onChange && onChange(dataRef.current)
    }, time);
  }

  const onSelectTime=(time)=>{
    dataRef.current.days=time
    callDelay(delay)
  }

  const onSelectDimension=(index,map)=>{
    dataRef.current.dimension=map
    callDelay(delay)
  }

  const onSelectMetric=(index,map)=>{
    dataRef.current.metric=map
    callDelay(delay)
  }

  const onFilterClose=(tags)=>{
    dataRef.current.tags = tags
    setTags(tags)
    callDelay(delay)
  }

  const onAddFilter = (form)=> {
    const {dimension, condition, keyword,startDate,endDate} = form;
    const obj = JSON.parse(dimension);
    setTags(pre => {
      const news = pre.concat({
        id: Math.random(),
        ...form,
        ...obj,
        name:obj.label,
        label: (
          <Space size="middle">
            <Text strong>{`“${obj.label}”`}</Text>
            <Text type="success">{condition}</Text>
            {
              obj.semanticType !== "DATE"
                ? <Text strong>{`“${keyword}”`}</Text>
                : <>
                  <Text strong>{`“${startDate}”`}</Text>
                  <Text type="success">AND</Text>
                  <Text strong>{`“${endDate}”`}</Text>
                </>
            }
          </Space>
        )
      })
      dataRef.current.tags=news
      return news
    })

    callDelay(0)
  }

  const handelDisplayChange = (dp)=>{
    dataRef.current.display=dp
    setDisplay(dp)
  }

  const FilterForm = useMemo(() =>
      <ProForm
        formRef={formRef}
        style={{width:500}}
        labelCol={{span:6}}
        wrapperCol={{span:16}}
        layout='horizontal'
        submitter={false}
        onFinish={onAddFilter}
      >
        <ProFormSelect
          name="dimension"
          label={t("formItem.dimension")}
          placeholder={t("placeholder.dimension")}
          rules={[{ required: true }]}
          options={
            (options.dimension||[]).map(item=>({
              label: item.label,
              value: JSON.stringify(item)
            }))
          }
        />

        <ProFormDependency name={["dimension"]}>
          {({ dimension }) => {
            if (dimension){
              const obj = JSON.parse(dimension)
              return obj.semanticType!=="DATE"
                ? <>
                  <ProFormSelect
                    name="condition"
                    label={t("formItem.condition")}
                    placeholder={t("placeholder.dimension")}
                    rules={[{ required: true }]}
                    options={WHERE_COND}
                  />
                  <ProFormText
                    name="keyword"
                    label={t("formItem.keyword")}
                    rules={[{ required: true }]}
                  />
                </>
                : <>
                  <ProFormSelect
                    name="condition"
                    label={t("formItem.condition")}
                    placeholder={t("placeholder.dimension")}
                    rules={[{ required: true }]}
                    options={[{label: "之间", value: "BETWEEN"}]}
                  />
                  <ProFormDatePicker name="startDate" label={t("formItem.startDate")} rules={[{ required: true }]} width="100%"/>
                  <ProFormDatePicker name="endDate" label={t("formItem.stopDate")} rules={[{ required: true }]} width="100%"/>
                </>
            }
          }}
        </ProFormDependency>

      </ProForm>
    ,[options]
  )

  return (
    <>
      {/*日期范围*/}
      <RadioCheckButton title={t("formItem.dateRanges")} defaultCheck={0} options={TIME_COND} onSelect={onSelectTime}/>
      {/*查询指标*/}
      {options?.metric && <RadioCheckButton title={t("formItem.metric")} options={options.metric} mode="checkBox" onChange={onSelectMetric}/>}
      {/*分析维度*/}
      {options?.dimension && <RadioCheckButton title={t("formItem.dimension")} defaultCheck={[dateDimension?.value]} options={options.dimension} mode="checkBox" onChange={onSelectDimension}/>}
      {/*展示方式*/}
      <RadioCheckButton title={t("formItem.display")} options={DISPLAY_COND} onSelect={handelDisplayChange} defaultCheck={DISPLAY_COND[0].value}/>
      {/*筛选条件*/}
      <Popconfirm
        icon={false}
        placement="bottomLeft"
        title={t("operation.addKeyword")} //"新增筛选值"
        description={FilterForm}
        onConfirm={() => formRef.current?.submit()}
        okText={t("button.ok")}
        cancelText={t("button.cancel")}
        arrow={false}
      >
        <RadioCheckButton title={t("formItem.filters")} link={t("placeholder.filters")} />
      </Popconfirm>
      {/*筛选条件展示/删除栏*/}
      {tags.length>0 && <EditableTags options={tags} onClose={onFilterClose} closable={true}/>}
      {extra}
      <Spin tip="Loading..." spinning={loading}>
        <ChartsGraph
          type={display}
          dataSource={dataSource}
        />
      </Spin>

    </>
  );
})