import {memo, forwardRef, useRef, useCallback, useEffect} from 'react';
import {Button, Card, Drawer, message} from "antd";
import {
  ProForm,
  ProFormDatePicker, ProFormGroup,
  ProFormText,
  ProFormRadio, ProFormDependency, ProFormTreeSelect
} from "@ant-design/pro-components";
import {AtomicIndexForm} from "./AtomicIndexForm";
import {FORM_TYPE, INDEX_TYPE, LOGIC_TYPE, SENSITIVE} from "../constants";
import {DerivedIndexForm} from "./DerivedIndexForm";
import {CompositeIndexForm} from "./CompositeIndexForm";
import {useAppDispatch, useAppSelector} from "../../../../redux/configureStore";
import {selectDomains} from "../../MainPage/slice/selectors";
import {createCondition, getConditions, getModals} from "../../MainPage/slice/thunks";

const formLayoutType = "horizontal";
const pickerWidth = 390;

const component = forwardRef(({
  onFinish,
  initialValues,
  open,
  handleCancel,
}, ref) => {
  console.log(initialValues)
  const dispatch = useAppDispatch()
  const domains = useAppSelector(selectDomains);
  const formRef = useRef(null);

  useEffect(() => {
    const {domainId} = initialValues;
    if (domainId){
      dispatch(getModals(domainId));
    }
  }, [initialValues]);

  /** 主题域选择回调 */
  const handelDomainSelect =useCallback((value)=>{
    dispatch(getModals(value));
    formRef.current?.resetFields(['modelId'])
  },[])

  /** 切换模型时清空子数据 */
  const onFieldChange = useCallback(()=>{
    formRef.current?.resetFields([
      'measure',
      'dateDimension',
      'relateDimension',
      'formIndex',
      "attributes"
    ])
  },[])

  /** 业务限定保存 */
  const onConditionSave=useCallback(()=>{
    const formatValue = formRef.current?.getFieldsFormatValue();
    // 组织数据
    const {attributes,name,domainId,modelId} = formatValue;
    if (!domainId) {
      message.error("请先选择主题")
      return false
    }
    if (!modelId) {
      message.error("请先选择模型")
      return false
    }
    let defaultConfig = "";
    if (attributes){
      for (let i = attributes.length - 1; i >= 0; i--) {
        const {value,logic,fields,condition} = attributes[i];
        const cdt = condition?condition:""
        if (LOGIC_TYPE[logic]==="包含" || LOGIC_TYPE[logic]==="不包含"){
          defaultConfig +=` ${cdt} ${fields} ${logic} '%${value}%'`
          continue
        }
        if (LOGIC_TYPE[logic]==="为空"||LOGIC_TYPE[logic]==="不为空"){
          defaultConfig +=` ${cdt} ${fields} ${logic}`
          continue
        }
        defaultConfig +=` ${cdt} ${fields} ${logic} ${value} `
      }
    }
    const params = {
      status:1,
      defaultConfig,
      name,
      modelId,
      domainId
    }
    console.log(params)
    dispatch(createCondition({
      params,
      resolve(){
        message.success("保存成功")
        dispatch(getConditions({}))
      }
    }))
  },[])

  return (
    <Drawer
      title="创建指标"
      width={1230}
      styles={{body:{padding:'0'}}}
      open={open}
      maskClosable={false}
      destroyOnClose
      onClose={handleCancel}
      footer={[
        <Button key="previewer" style={{marginLeft:'40%'}} onClick={handleCancel}>
          预览
        </Button>,
        <Button key="upload" style={{marginLeft:15}} onClick={handleCancel}>
          发布
        </Button>,
        <Button key="submit" style={{marginLeft:15}} type="primary" onClick={()=>{formRef?.current?.submit()}}>
          保存
        </Button>
      ]}
    >
      <ProForm
        formRef={formRef}
        layout={formLayoutType}
        initialValues={initialValues}
        onFinish={onFinish}
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 18 }}
        submitter={false}
      >
        {/** 指标通用字段 */}
        <Card type="inner" title="基础信息" bordered={false}>
          <ProFormRadio.Group
            name="type"
            label="指标类型"
            disabled={initialValues.id}
            rules={[{ required: true }]}
            valueEnum={INDEX_TYPE}
          />
          <ProFormRadio.Group
            name="sensitiveLevel"
            label="敏感度"
            rules={[{ required: true }]}
            valueEnum={SENSITIVE}
          />
          <ProFormText
            name="name"
            label="指标名称"
            rules={[{ required: true }]}
          />
          <ProFormText
            name="description"
            label="指标描述"
          />
          <ProFormText
            name="bizName"
            label="指标编码"
            rules={[{ required: true }]}
          />
          <ProFormTreeSelect
            name="domainId"
            label="主题域"
            rules={[{ required: true }]}
            request={async ()=>domains}
            fieldProps={{
              onSelect:handelDomainSelect
            }}
          />
          <ProFormText
            name="alias"
            label="业务口径"
            rules={[{ required: true }]}
          />
          <ProFormText
            name="director"
            label="业务负责人"
            rules={[{ required: true }]}
          />
          <ProFormGroup style={{marginLeft:115}}>
            <ProFormDatePicker name="startDate" label="生效日期" rules={[{ required: true }]} width={pickerWidth}/>
            <ProFormDatePicker name="stopDate" label="失效日期" width={pickerWidth}/>
          </ProFormGroup>
        </Card>
        <Card bordered={false} type="inner" title="指标定义" style={{boxShadow:'none'}}>
          <ProFormDependency name={["type"]}>
            {({ type }) => {
              switch (type) {
                case FORM_TYPE.ATOMIC.value:
                  return <AtomicIndexForm modelId={initialValues?.modelId} onChange={onFieldChange}/>
                case FORM_TYPE.DERIVED.value:
                  return <DerivedIndexForm modelId={initialValues?.modelId} onChange={onFieldChange} onConditionSave={onConditionSave}/>
                case FORM_TYPE.COMPOSITE.value:
                  return <DerivedIndexForm modelId={initialValues?.modelId} onChange={onFieldChange}/> //<CompositeIndexForm/>
                default : return null
              }
            }}
          </ProFormDependency>
        </Card>
      </ProForm>
    </Drawer>
  )
})
export const IndexCreator = memo(component);