import {memo, useCallback, useEffect, useRef, useState} from 'react';
import {ProCard, ProFormGroup, ProFormRadio, ProFormSelect, ProFormDigit} from "@ant-design/pro-components";
import {Button, Col} from "antd";
import {LogicPanel} from "../../../components/LogicPanel";
import {styled} from "styled-components";
import {useAppDispatch, useAppSelector} from "../../../../redux/configureStore";
import {selectConditions, selectModals} from "../../MainPage/slice/selectors";
import {getConditions, getModalInfo} from "../../MainPage/slice/thunks";
import {DATA_TYPE, FORM_TYPE} from "../constants";
import {CodeEditor} from "../../../components/CodeEditor";
import useI18NPrefix from "../../../hooks/useI18NPrefix";

export const DerivedIndexForm = memo(({
  onChange,
  onConditionSave,
  initialValues
}) => {
  const t = useI18NPrefix('global');
  const dispatch = useAppDispatch();
  const modals = useAppSelector(selectModals);
  const conditions = useAppSelector(selectConditions);
  const [tab, setTab] = useState('fieldsConfig');
  const [conditionType, setConditionType] = useState(true);
  const [dateDims, setDateDims] = useState([]);
  const [analyzeDims, setAnalyzeDims] = useState([]);
  const [metrics, setMetrics] = useState([]);
  const [filters, setFilters] = useState([]);
  const editorRef = useRef(null);

  useEffect(() => {
    const initialSelector = async (modelId)=>{
      await onModalSelect(modelId)
    }
    if (initialValues?.modelId){
      initialSelector(initialValues?.modelId)
    }
  }, []);

  const onModalSelect = useCallback(async (id) => {
    if (!id) return false

    let date = [], analyze = [], tempMetrics = [],tempFilter=[];

    dispatch(getConditions({}))

    await dispatch(getModalInfo({
      id,
      resolve(data) {
        (data?.dimensions||[]).forEach(
          ({expr, name, bizName, description, type, id}) => {
            const label = description || name|| bizName

            // 插入维度
            const dim = {label, value: id}
            if (type === "time") {
              date.push(dim)
            } else {
              analyze.push(dim)
            }

            // 插入业务限定过滤字段
            tempFilter.push({label, value: expr});
          }
        )

        if (data?.metrics){
          data.metrics
            .filter(item=>item.bizName!==initialValues?.bizName && FORM_TYPE.ATOMIC.value === item.type)
            .forEach(item=> {
              tempMetrics.push({label:item.name, value: item.expr})
              tempFilter.push({label:item.name, value: item.expr})
            })
        }
      }
    }))

    // 缓存维度列表
    setDateDims(date)
    setAnalyzeDims(analyze)
    setMetrics(tempMetrics)
    setFilters(tempFilter)
    onChange?.()
  }, [])


  const onEditorChange = (txt)=>{
    editorRef.current = txt
  }

  const onSaveCondition = (tab)=>{
    onConditionSave(tab,editorRef.current)
  }
  return (
    <>
      <ProFormSelect
        name="modelId"
        label={t("formItem.model")}
        rules={[{required: true}]}
        options={modals}
        onChange={onModalSelect}
      />
      <ProFormSelect
        name="formIndex"
        label={t("formItem.formIndex")}
        rules={[{required: true}]}
        options={metrics}
        initialValue={initialValues?.expr}
      />
      <ProFormRadio.Group
        name="conditionType"
        label={t("formItem.condition")}
        initialValue={true}
        style={{marginBottom: 0}}
        rules={[{required: true}]}
        fieldProps={{
          onChange: (e) => setConditionType(e.target.value)
        }}
        options={[
          {label: t("operation.formLibrary"), value: true},
          {label: t("operation.custom"), value: false}
        ]}
      />
      {
        conditionType
          ? <ProFormSelect
            name="conditionId"
            label={t("formItem.bizCondition")}
            rules={[{required: true}]}
            options={conditions.map(item=>({label: item.name, value: item.id}))}
          />
          : <Col offset={4} span={18} style={{marginBottom: 24, marginTop: -28}}>
            <CustomProCard
              tabs={{
                tabBarExtraContent:<Button type='link' onClick={()=>onSaveCondition(tab)}>{t("button.save")+t("formItem.bizCondition")}</Button>,
                activeKey: tab,
                items: [
                  {
                    label: t("operation.fieldsConfig"),
                    key: 'fieldsConfig',
                    children: <LogicPanel type={FORM_TYPE.DERIVED.value} options={filters}/>,
                  },
                  {
                    label: t("operation.customScript"),
                    key: 'customScript',
                    children: <CodeEditor onEditorChange={onEditorChange} width="100%" height="180"/>,
                  }
                ],
                onChange: (key) => {
                  setTab(key);
                },
              }}
            />
          </Col>
      }
      <ProFormGroup style={{marginLeft: 105}}>
        <ProFormSelect
          name="dataFormatType"
          label={t("formItem.dataFormat")}
          valueEnum={DATA_TYPE}
          width={480}
        />
        <ProFormDigit name="decimalPlaces" placeholder={t("placeholder.decimalPlaces")} initialValue={initialValues?.dataFormat?.decimalPlaces} min={1} max={10}/>
      </ProFormGroup>
      <ProFormSelect
        name="relateDimension"
        options={analyzeDims}
        label={t("formItem.dimension")}
        fieldProps={{
          mode: 'multiple'
        }}
      />
      <ProFormSelect
        name="dateDimId"
        label={t("formItem.dateDimension")}
        rules={[{required: true}]}
        options={dateDims}
      />
    </>
  )
})
const CustomProCard = styled(ProCard)`
  .ant-pro-card-body {
    padding: 0;
  }
`
