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

export const CompositeIndexForm = memo(({
  initialValues,
  onChange
}) => {
  const t = useI18NPrefix('global');
  const computedEditorRef = useRef();
  const dispatch = useAppDispatch();
  const modals = useAppSelector(selectModals);
  const metricsRef = useRef([]);
  const [metrics,setMetrics]=useState([]);
  const [analyzes,setAnalyzes]=useState([]);
  const [dateDims, setDateDims] = useState([]);

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

  const onModalSelect = useCallback(async (modelId) => {
    if (!modelId) return false
    computedEditorRef?.current?.clear();
    await dispatch(getModalInfo({
      id:modelId,
      resolve(data) {
        const {dimensions,metrics}=data;
        const analyze = dimensions.filter(({type})=>type!=="time").map(({name, bizName, description, id})=>({
          label: description|| name|| bizName,
          value: id
        }))
        const date = dimensions.filter(({type})=>type==="time").map(({name, bizName, description, id})=>({
          label: description|| name|| bizName,
          value: id
        }))

        setMetrics(
          metrics.filter(item=>item.bizName!==initialValues?.bizName)
        );
        setAnalyzes(analyze);
        setDateDims(date);
        metricsRef.current=metrics;
      }
    }))

    // onChange?.(computedEditorRef.current?.formatValue(initialValues.expr,'change'))
  }, [])

  const onComputedEditorChange = useCallback((expression)=>{
    if (expression){
      onChange?.(computedEditorRef.current?.formatValue(expression,'change'))
    }
  },[])

  return (
    <>
      <ProFormSelect
        name="modelId"
        label={t("formItem.model")}
        rules={[{required: true}]}
        options={modals}
        onChange={onModalSelect}
      />
      <Row>
        <Col span={4}>
          <CardLabel children={t("formItem.formIndex")+":"} className="required"/>
        </Col>
        <Col span={18}>
          <ComputedEditor
            value={initialValues.expr}
            onChange={onComputedEditorChange}
            fields={metrics}
            ref={computedEditorRef}
          />
        </Col>
      </Row>
      <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={analyzes}
        label={t("formItem.dimension")}
        fieldProps={{
          mode: 'multiple'
        }}
      />
      <ProFormSelect
        name="dateDimId"
        label={t("formItem.dateDimension")}
        rules={[{required: true}]}
        options={dateDims}
      />
    </>
  )
})
const CardLabel = styled.label`
  position: absolute;
  right: 10px;
  top: 20px;
  &.required {
    // 添加必填红色*的样式
    &::before {
      display: inline-block;
      margin-inline-end: 4px;
      color: #ff4d4f;
      font-size: 14px;
      font-family: SimSun, sans-serif;
      line-height: 1;
      content: "*";
    }
  }
`