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 {getModalInfoList} 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 [metricFormData, setMetricFormData] = useState([]);
  useEffect(() => {
    const initialSelector = async (modelId)=>{
      await onModalSelect(modelId)
    }
    if (initialValues?.modelId){
      initialSelector(initialValues?.modelId)
    }
  }, []);

  const onModalSelect = useCallback(async (modelId) => {
    if(Array.isArray(modelId)){
      modelId = modelId.join(','); 
    }
    if (!modelId) return false
    // computedEditorRef?.current?.clear();
    await dispatch(getModalInfoList({
      id:modelId,
      resolve(data) {
        let dimensions = [];
        let metrics = [];

        if (Array.isArray(data)) {
          data.forEach(item => {
            if (!item) {
              return;
            }
            if (Array.isArray(item.dimensions)) {
              dimensions.push(...item.dimensions);
            }
            if (Array.isArray(item.metrics)) {
              metrics.push(...item.metrics);
            }
          });
        } else if (data) {
          dimensions = Array.isArray(data.dimensions) ? data.dimensions : [];
          metrics = Array.isArray(data.metrics) ? data.metrics : [];
        }
        const analyze = dimensions.filter(({type})=>type!=="time").map(({name, bizName, description, id, modelId})=>({
          label: description|| name|| bizName,
          value: id,
          modelId,
        }))
        const date = dimensions.filter(({type})=>type==="time").map(({name, bizName, description, id, modelId})=>({
          label: description|| name|| bizName,
          value: id,
          modelId,
        }))
        setMetrics(
          metrics.filter(item=>item.bizName!==initialValues?.bizName).map((v) => {
            return {
              ...v,
              analyzeArr: analyze.filter(a => a.modelId == v.modelId),
              dateArr: date.filter(a => a.modelId == v.modelId),
            }
          })
        );
        metricsRef.current=metrics;
      }
    }))
    // onChange?.(computedEditorRef.current?.formatValue(initialValues.expr,'change'))
  }, [])

  const onComputedEditorChange = useCallback((expression)=>{
    if (expression){
      console.log(expression);
      const data = computedEditorRef.current?.formatValue(expression,'change');
      setMetricFormData(data?.metrics)
      onChange?.(data)
    }
  },[])
  const getInitMetrics = useCallback((arr)=>{
    if (arr.length){
      setMetricFormData(arr)
    }
  },[])
  return (
    <>
      <ProFormSelect
        name="modelId"
        label={t("formItem.model")}
        rules={[{required: true}]}
        options={modals}
        onChange={onModalSelect}
        fieldProps={{
          mode: 'multiple'
        }}
      />
      <Row>
        <Col span={4}>
          <CardLabel children={t("formItem.formIndex")+":"} className="required"/>
        </Col>
        <Col span={18}>
          <ComputedEditor
            value={initialValues.expr}
            onChange={onComputedEditorChange}
            fields={metrics}
            getInitMetrics={getInitMetrics}
            ref={computedEditorRef}
          />
        </Col>
      </Row>
      <Row gutter={10} style={{border: '1px solid #ccc',marginBottom: '16px', borderRight: 'none'}}>
      {metricFormData.map((item, index) => {
        return <>
        <Col 
          span={Math.floor(24 / (metricFormData.length))}
          style={{borderRight: '1px solid #ccc'}}
          key={index}
          >
            <div style={{padding: '12px'}}>{item.name}</div>
            <ProFormSelect
              name={['dimensionIds',index]}
              options={item?.analyzeArr}
              label={t("formItem.dimension")}
              fieldProps={{
                mode: 'multiple'
              }}
            />
            <ProFormSelect
              name={['dateDimId',index]}
              label={t("formItem.dateDimension")}
              rules={[{required: true}]}
              options={item?.dateArr}
            />
          </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>
    </>
  )
})
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: "*";
    }
  }
`