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, getModalDetail, 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,
  onSetField,
  onExprChange
}) => {
  const isCondition = !!initialValues?.ext?.filters;
  const measures = initialValues?.metricDefineByMeasureParams?.measures[0];
  const initTab = initialValues?.ext?.filters?.length<1 && measures?.constraint ?'customScript':'fieldsConfig';

  const t = useI18NPrefix('global');
  const dispatch = useAppDispatch();
  const modals = useAppSelector(selectModals);
  const conditions = useAppSelector(selectConditions);
  const [tab, setTab] = useState(initTab);
  const [conditionType, setConditionType] = useState(!isCondition);
  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)
      onExprChange?.({expr:measures?.constraint})
    }
  }, []);

  useEffect(() => {
    if (initialValues?.metricDefineByMeasureParams?.measures){
      const newMetric = metrics.map(item=>JSON.parse(item.value));
      const findMetric = newMetric.find(item=>item.bizName===measures?.bizName);
      if (findMetric){
        onSetField("formIndex",JSON.stringify(findMetric))
      }
    }
  }, [metrics]);

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

    dispatch(getConditions({}))

    dispatch(getModalDetail({
      id,
      resolve(data){
        if (data?.modelDetail){
          const {fields} = data.modelDetail
          const fieldsOptions = fields.map(({comment,fieldName})=>({
            label: comment ,
            value: fieldName,
          }))
          setFilters(fieldsOptions)
        }
      }
    }))

    dispatch(getModalInfo({
      id,
      resolve(data) {
        const getDimensions = data?.dimensions||[];
        const getMetrics = data?.metrics || [];
        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}));
        const tempMetrics = getMetrics
          .filter(item=>item.bizName!==initialValues?.bizName && FORM_TYPE.ATOMIC.value === item.type)
          .map(item=>({label:item.name, value: JSON.stringify({id: item.id,bizName:item.bizName,operations:item?.operations,expr:item.expr})}));
        setDateDims(date);
        setAnalyzeDims(analyze);
        setMetrics(tempMetrics);
      }
    }))

    // 缓存维度列表
    onChange?.();
  }, [])


  const onEditorChange = (expr)=>{
    editorRef.current = expr;
    onExprChange?.({expr})
  }

  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}
      />
      <ProFormRadio.Group
        name="conditionType"
        label={t("formItem.condition")}
        initialValue={conditionType}
        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}]}
            initialValue={initialValues?.bizConditionResp?.id}
            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 value={initialValues?.ext?.filters} type={FORM_TYPE.DERIVED.value} options={filters}/>,
                  },
                  {
                    label: t("operation.customScript"),
                    key: 'customScript',
                    children: <CodeEditor ref={editorRef} value={measures?.constraint} 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;
  }
`
