import {memo, useCallback, useMemo, useRef, useState} from 'react';

import {QuickStartStep} from "./QuickStartStep.jsx";
import {MeasureType, MODAL_TYPE, RadioType} from "../constants.js";
import {StepsForm} from "@ant-design/pro-components";
import {Button, message, Modal, Space, Tooltip} from "antd";
import {ModalConfigPanel} from "./ModalConfigPanel.jsx";
import {ConfigPreviewPanel} from "./ConfigPreviewPanel.jsx";
import {InfoCircleFilled} from "@ant-design/icons";
import {SqlStartStep} from "./SqlStartStep";
import {useWorkFlow} from "../../../hooks/useWorkFlow";
import {useAppDispatch, useAppSelector} from "../../../../redux/configureStore";
import {executeSql} from "../../MainPage/slice/thunks";
import useI18NPrefix from "../../../hooks/useI18NPrefix";
import {selectDimensions} from "../../MainPage/slice/selectors";
import {useModelConfig} from "../../../hooks/useModelConfig";


// TODO 修改关系
export const ModalDesign = memo(({
  open=false,
  onCancel,
  onFinish,
  initialValues,
  type
}) => {
  const dispatch = useAppDispatch();
  const t = useI18NPrefix('global');
  /** 维度预览信息*/
  const viewerColumns = [
    {
      title: t("columns.tableName"),
      dataIndex: 'tableName',
      key: 'tableName',
      width: 180,
    },
    {
      title: t("columns.field"),
      dataIndex: 'bizName',
      key: 'bizName',
      width: 130,
    },
    {
      title: t("columns.dataType"),
      dataIndex: 'dataType',
      key: 'dataType',
    },
    {
      title: t("columns.comment"),
      dataIndex: 'comment',
      key: 'fieldDesc',
      width: 130,
      render: (text,record) => (
        <span>
        <span>{text}</span>
          {
            record?.descriptions &&
            <span>
            <Tooltip title={record?.descriptions}>
              <InfoCircleFilled style={{marginLeft: 5, color: '#bfbfbf'}}/>
            </Tooltip>
          </span>
          }
      </span>
      ),
    },
    {
      title: t("columns.relation"),
      dataIndex: 'relation',
      key: 'relation',
      width: 48,
      render: (text) => <a>{text}</a>,
    },
  ];
  /** 表头信息*/
  const configColumns = [
    {
      title: t("columns.tableName"),
      dataIndex: 'tableName',
      readonly: true,
      width: '19%',
    },
    {
      title: t("columns.field"),
      dataIndex: 'fieldName',
      readonly: true,
      width: '12%',
    },
    {
      title: t("columns.bizName"),
      dataIndex: 'bizName',
      width: '15%',
      fieldProps: (form, {entity}) =>({disabled: entity.disabled,allowClear:false,}),
    },
    {
      title: t("columns.dataType"),
      dataIndex: 'dataType',
      readonly: true,
      width: '10%',
    },
    {
      title: t("columns.isKey"),
      dataIndex: 'isKey',
      valueType: 'switch',
      width: 80,
      fieldProps: (form, {entity}) =>({disabled: entity.disabled || entity.dataType && (!entity.dataType.includes('INT') && !entity.dataType.includes('VARCHAR'))}),
    },
    {
      title: t("columns.measure"),
      dataIndex: 'measure',
      valueType: 'switch',
      width: 80,
      fieldProps: (form, {entity}) =>({disabled: entity.disabled || entity.dataType && !MeasureType.includes(entity.dataType)}),
    },
    {
      title: t("columns.common"),
      dataIndex: 'common',
      valueType: 'switch',
      width: 90,
      fieldProps: (form, {entity}) =>({disabled: entity.disabled }),
    },
    {
      title: t("columns.dateDim"),
      dataIndex: 'datetime',
      valueType: 'switch',
      tooltip:t("placeholder.dateDimRule") ,
      width: 90,
      fieldProps: (form, {entity}) =>({disabled: entity.disabled || entity.dataType && !entity.dataType.includes('DATE')}),
    },
    {
      title: t("columns.comment"),
      dataIndex: 'comment',
      fieldProps: (form, {entity}) =>({disabled: entity.disabled,allowClear:false,}),
      width: '19%',
    },
  ];
  /**
   * 工作流钩子
   * */
  const {getFields , markFields , getNodesState, getEdgesState} = useWorkFlow();
  /**
   * 模型配置处理钩子
   * */
  const {toFields,initSqlModel,initQuickModel,sqlResultToTable,checkSelectAll,fieldsToTable} = useModelConfig();
  /** StepForm步骤*/
  const [current,setCurrent] = useState(0);
  /** 步骤一的Ref */
  const stepOneRef = useRef(null);
  /** 步骤一数据 */
  const stepOneData = useRef(null);
  /** sql缓存 */
  const sqlRef = useRef("");
  /** sql结果状态 */
  const [sqlStatus,setSqlStatus] = useState(false);
  /** sql表头 */
  const [sqlFields,setSqlFields] = useState(null);
  /** sql结果 */
  const [sqlResult,setSqlResult] = useState(null);
  /** ConfigTable的Ref钩子*/
  const configTableRef = useRef();
  /** 维度列表 */
  const dimensions = useAppSelector(selectDimensions);
  /** 步骤二的Table数据 */
  const configData = useMemo(()=> {
    const nodeFields = getFields(getNodesState);
    const modelDetail = initialValues?.modelDetail;
    const model = initialValues?.bizName;
    const bizList = [
      ...(modelDetail?.dimensions || []),
      ...(modelDetail?.identifiers || []),
      ...(modelDetail?.measures || [])
    ]
    const initFields = modelDetail?.fields || [];

    // 快速创建回显
    if (MODAL_TYPE.QUICK===type?.value){
      if (initialValues){
        return initQuickModel(model,nodeFields,dimensions,bizList)
      }else {
        return nodeFields
      }
    }

    // SQL创建
    if (MODAL_TYPE.SQL===type?.value){
      if (initialValues && !sqlFields){
        const SQL = modelDetail?.sqlQuery || "";
        const initInfo = initSqlModel(model,SQL,initFields,bizList)
        sqlRef.current=SQL;
        setSqlStatus(true);
        return initInfo.tableData
      }
      if(sqlFields){
        // 判断SELECT * 时，取接口里的字段进行填充
        const isSelectAll = checkSelectAll(sqlRef.current);
        if (isSelectAll){
          // 单表SELECT *
          const fieldFormat = toFields(sqlRef.current);
          const tableName = fieldFormat.length>0 && fieldFormat[0]?.table;
          return fieldsToTable(tableName,sqlFields);
        }else {
          // SQL字符串转字段数组
          const fieldFormat = toFields(sqlRef.current);
          const tablesInfo = sqlResultToTable(model,sqlFields,fieldFormat,initFields,bizList);
          if (tablesInfo){
            return tablesInfo
          }else {
            message.error("SQL解析有误！")
          }
        }

      }
    }
    // 默认取WorkFlow数据回显
    return nodeFields
  },[initialValues,getNodesState,sqlFields,dimensions]);

  /** 步骤三的预览数据 */
  const [viewerData,setViewerData] = useState([]);

  /** 提交最终数据 */
  const handelFinish = useCallback((values)=>{
    onFinish({
      ...values,
      domainId:initialValues?.domainId,
      nodes:configTableRef.current.getRowsData(),
      edges:getEdgesState,
      classify:viewerData,
      modelType:type.value,
      sqlStr:sqlRef.current
    })
    setCurrent(0)
  },[viewerData])


  /** 分类数据 */
  const secondStepFinish = useCallback(()=>{
    setViewerData(
      markFields(
        configTableRef.current.getRowsData(),
        RadioType
      )
    )
    setCurrent(pre=>pre+1)
  },[current])

  /** SQL编辑器回调 */
  const onEditorChange = useCallback((sql)=>{
    sqlRef.current = sql
  },[])

  /** 关闭设计*/
  const onCloseModal = useCallback((e)=>{
    onCancel(e)
    setCurrent(0)
    setViewerData([])
    setSqlFields(null)
    sqlRef.current = ""
  },[]);

  /** SQL执行回调 */
  const onExecuteSql = useCallback(async ()=>{
    const formValue = await stepOneRef?.current?.validateFieldsReturnFormatValue?.();
    let status = false;
    await dispatch(executeSql({
      params:{
        id: formValue.dbSource,
        sql:sqlRef.current,
        sqlVariables:[],
        limit:100
      },
      resolve(data){
        setSqlFields(data?.columns||[])
        setSqlResult(data?.resultList||[])
        message.success("执行成功")
        status=true
      }
    }))

    // 开启下一步
    setSqlStatus(status);
  },[])

  /**指标字段改变回调*/
  const onSetField = useCallback((field,value)=>{
    stepOneRef?.current?.setFieldValue(field,value);
  },[])

  /** 最后的描述*/
  const descriptions = useMemo(()=>(
    [
      {
        key: '1',
        label: t("formItem.model")+t("formItem.name"),
        children: stepOneData.current?.name,
      },
      {
        key: '2',
        label: t("title.establishingMode"),
        children: t(
          MODAL_TYPE.QUICK===type?.value
            ?"title.quickStart"
            :"title.SQLStart"
        ),
      },
      {
        key: '3',
        label: t("title.atomicNum"),
        children: '-',
      },
      {
        key: '4',
        label: t("title.derivedNum"),
        children: '-',
      },
      {
        key: '5',
        label: t("title.compositeNum"),
        children: '-',
      },
    ]
  ),[current]);

  return (
    <StepsForm
      current={current}
      onFinish={handelFinish}
      containerStyle={{width:'90%'}}
      stepsFormRender={(dom, submitter) =>
        <Modal
          title="模型设计"
          width={1412}
          onCancel={onCloseModal}
          open={open}
          footer={
            submitter.map(item=>{
              if (item.key==='pre'){
                return <Button key="pre" onClick={()=>setCurrent(pre=>pre-1)}>上一步</Button>
              }
              if (current===0 && MODAL_TYPE.SQL===type?.value){
                return <Space key="excute">
                  <Button onClick={onExecuteSql}>{t("button.executeSQL")}</Button>
                  {sqlStatus && item}
                </Space>
              }
              return item
            })
          }
          destroyOnClose={true}
          maskClosable={false}
        >
          {dom}
        </Modal>
      }
    >
      {/** 步骤一 */}
      <StepsForm.StepForm
        name="base"
        title={t("title.baseInfo")}
        labelCol={{span:6}}
        wrapperCol={{span:18}}
        layout='horizontal'
        formRef={stepOneRef}
        onFinish={(val)=> {
          stepOneData.current=val
          setCurrent(pre => pre + 1)
          return true
        }}
      >
        {MODAL_TYPE.QUICK===type?.value && <QuickStartStep initialValues={initialValues} onSetField={onSetField}/>}
        {MODAL_TYPE.SQL===type?.value && <SqlStartStep sql={sqlRef.current} columns={sqlFields} data={sqlResult} onSetField={onSetField} initialValues={initialValues} onEditorChange={onEditorChange}/>}
      </StepsForm.StepForm>

      {/** 步骤二 */}
      <StepsForm.StepForm
        name="configuration"
        title={t("title.modelConfig")}
        onFinish={secondStepFinish}
      >
        <ModalConfigPanel values={configData} columns={configColumns} ref={configTableRef}/>
      </StepsForm.StepForm>

      {/** 步骤三 */}
      <StepsForm.StepForm
        name="viewer"
        title={t("title.finishDesign")}
      >
        <ConfigPreviewPanel values={viewerData} descriptions={descriptions} columns={viewerColumns}/>
      </StepsForm.StepForm>
    </StepsForm>
  )
})
