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

export const AtomicIndexForm = memo(({
  initialValues,
  onChange,
  onExprChange
}) => {
  const t = useI18NPrefix('global');
  const dispatch = useAppDispatch();
  const modals = useAppSelector(selectModals);
  const [measureList,setMeasureList]=useState([]);
  const [fields,setFields] = useState([]);
  const [dateDims,setDateDims]=useState([]);
  const [analyzeDims,setAnalyzeDims]=useState([]);
  const [measureMode,setMeasureMode]=useState(true);
  const computedEditorRef = useRef();

  useEffect(() => {
    if (initialValues?.modelId){
      const ss = onModalSelect(initialValues?.modelId)
      setMeasureMode(initialValues.metricDefineType==='MEASURE')
    }
  }, [initialValues]);

  const onModalSelect =useCallback((id)=>{
    if (!id) return false
    computedEditorRef?.current?.clear();

    dispatch(getModalInfo({
      id,
      resolve(data){
        const getDimensions = data?.dimensions||[];
        const date = getDimensions.filter(item=>item.type === "time").map(item=>({label:item.description || item.name|| item.bizName, value: item.id}))
        const analyze =getDimensions.filter(item=>item.type !== "time").map(item=>({label:item.description || item.name, value: item.id}))
        setDateDims(date)
        setAnalyzeDims(analyze)
      }
    }))

    dispatch(getModalDetail({
      id,
      resolve(data){
        const {modelDetail} = data;
        if (modelDetail?.measures) {
          const fieldList = (modelDetail?.fields||[])
            .map(item=>({
              id: item.bizName,
              label:item.comment,
              value:item.fieldName,
              name:item.comment,
              bizName:item.fieldName
            }))
          setFields(fieldList)

          const measuresList = (modelDetail?.measures||[])
            .map(item=>({
              id: item.bizName,
              label:item.alias||item.name,
              value:item.bizName,
              name:item.alias||item.name,
              bizName:item.name||item.bizName
            }))
          setMeasureList(measuresList)
        }
      }
    }))
    // 缓存维度列表
    onChange?.()
  },[])

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

  const onMeasureModeChange = ()=>{
    setMeasureMode(pre=>!pre);
    computedEditorRef?.current?.clear();
  }

  return (
    <>
      <ProFormSelect
        name="modelId"
        label={t("formItem.model")}
        rules={[{ required: true }]}
        options={modals}
        onChange={onModalSelect}
      />
      {
        measureMode
          ? (
            <ProFormGroup style={{marginLeft: 40}}>
              <ProFormSelect
                name="measure"
                label={t("formItem.measure")}
                rules={[{required: true}]}
                options={measureList}
                width={885}
              />
              <Button type="link" style={{marginLeft: 65}} onClick={onMeasureModeChange}>自定义</Button>
            </ProFormGroup>
          )
          : (
            <Row>
              <Col span={4}>
                <CardLabel children={t("formItem.fields") + ":"} className="required"/>
              </Col>
              <Col span={18}>
                <ComputedEditor
                  value={initialValues.expr}
                  onChange={onComputedEditorChange}
                  fields={fields}
                  ref={computedEditorRef}
                />
              </Col>
              <Col span={2}>
                <Button type="link" onClick={onMeasureModeChange}>选择度量</Button>
              </Col>
            </Row>
          )
      }
      <ProFormSelect
        name="dateDimId"
        label={t("formItem.dateDimension")}
        rules={[{ required: true }]}
        options={dateDims}
      />
      <ProFormSelect
        name="relateDimension"
        options={analyzeDims}
        label={t("formItem.dimension")}
        fieldProps={{
          mode: 'multiple'
        }}
      />
      <ProFormSelect
        name="operations"
        label={t("formItem.calculations")}
        valueEnum={CALC_TYPE}
      />
      <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>
    </>
  )
})
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: "*";
    }
  }
`