import {memo, useCallback, useEffect, 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, getMetricList, getModalDetail, getModalInfo} from "../../MainPage/slice/thunks";
import {DATA_TYPE, INVOKE_TYPE} from "../constants";
import {CodeEditor} from "../../../components/CodeEditor";

export const DerivedIndexForm = memo(({
  modelId,
  onChange,
  onConditionSave
}) => {
  const dispatch = useAppDispatch();
  const [tab, setTab] = useState('tab1');
  const [conditionType, setConditionType] = useState(true);
  const modals = useAppSelector(selectModals);
  const conditions = useAppSelector(selectConditions);

  const [dateDims, setDateDims] = useState([]);
  const [analyzeDims, setAnalyzeDims] = useState([]);
  const [metrics, setMetrics] = useState([]);
  const [modalDetail, setModalDetail] = useState();

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

  const onModalSelect = useCallback(async (id) => {
    let date = [], analyze = [], tempMetrics = [];
    dispatch(getModalDetail({
      id,
      resolve(data){
        setModalDetail(data.modelDetail)
      }
    }))

    await dispatch(getModalInfo({
      id,
      resolve(data) {
        const {dimensions} = data;
        dimensions && dimensions.forEach(
          ({name, bizName, description, type, id}) => {
            const obj = {
              label: name === "id" ? bizName : description,
              value: id
            }
            if (type === "time") {
              date.push(obj)
            } else {
              analyze.push(obj)
            }
          })
      }
    }))

    dispatch(getConditions({}))

    await dispatch(getMetricList({
      id,
      resolve(data) {
        tempMetrics= data.map(item=>({label:item.name, value: item.id}))
      }
    }))
    // 缓存维度列表
    setDateDims(date)
    setAnalyzeDims(analyze)
    setMetrics(tempMetrics)
    onChange?.()
  }, [])
  return (
    <>
      <ProFormSelect
        name="modelId"
        label="模型选择"
        rules={[{required: true}]}
        options={modals}
        onChange={onModalSelect}
      />
      <ProFormSelect
        name="formIndex"
        label="来自指标"
        rules={[{required: true}]}
        options={metrics}
      />
      <ProFormRadio.Group
        name="conditionType"
        label="条件设置"
        initialValue={true}
        style={{marginBottom: 0}}
        rules={[{required: true}]}
        fieldProps={{
          onChange: (e) => setConditionType(e.target.value)
        }}
        options={[
          {label: '从业务限定库选择', value: true},
          {label: '自定义', value: false}
        ]}
      />
      {
        conditionType
          ? <ProFormSelect
            name="condition"
            label="业务限定"
            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={onConditionSave}>保存业务限定</Button>,
                activeKey: tab,
                items: [
                  {
                    label: `字段配置`,
                    key: 'tab1',
                    children: <LogicPanel options={modalDetail}/>,
                  },
                  {
                    label: `自定义脚本`,
                    key: 'tab2',
                    children: <CodeEditor onEditorChange={console.log} width="100%" height="180"/>,
                  }
                ],
                onChange: (key) => {
                  setTab(key);
                },
              }}
            />
          </Col>
      }
      <ProFormGroup style={{marginLeft: 105}}>
        <ProFormSelect
          name="dataFormatType"
          label="数据格式"
          valueEnum={DATA_TYPE}
          width={480}
        />
        <ProFormDigit name="decimalPlaces" placeholder="保留小数点位数" min={1} max={10}/>
      </ProFormGroup>
      <ProFormSelect
        name="relateDimension"
        options={analyzeDims}
        label="分析维度"
        fieldProps={{
          mode: 'multiple'
        }}
      />
      <ProFormSelect
        name="dateDimension"
        label="时间维度"
        rules={[{required: true}]}
        options={dateDims}
      />
      <ProFormRadio.Group
        name="inovkeMethod"
        label="调度方式"
        valueEnum={INVOKE_TYPE}
      />
    </>
  )
})
const CustomProCard = styled(ProCard)`
  .ant-pro-card-body {
    padding: 0;
  }
`
