import { Steps, Button, Space, Form, Drawer, message } from 'antd'
import StepOne from './StepOne'
import StepTwo from './StepTwo'
import StepThree from './StepThree'
import StepFour from './StepFour'
import React, { useState, useEffect } from 'react'
import DataTableStruct from './DataTableStruct'
import styled from 'styled-components'
import { MenuFoldOutlined, MenuUnfoldOutlined } from '@ant-design/icons'
import { getDataSourceList, getTableSchema } from '../services'
import { useForm } from 'antd/es/form/Form'

const { Step } = Steps

const SyncTask = styled.div`
  padding: 20px;
  .check__btn {
    position: absolute;
    right: 0;
    top: 20%;
    border-radius: 0;
  }
`

export default function SyncTaskAdd() {
  // 步骤三ref
  const stepThreeRef = React.createRef()

  // 步骤数
  const [currentStep, setCurrentStep] = useState(0)

  // 初始化数据源列表数据 constructor
  const [dataSourceList, setDataSourceList] = useState([])

  // 构建loading状态
  const [building, setBuilding] = useState(false)

  // 提交loading状态
  const [submiting, setSubmiting] = useState(false)

  // 完成状态
  const [isfinishBuild, setIsFinishBuild] = useState(false)

  // 提取源表单表结构
  const [drawDataStruct, setDrawDataStruct] = useState([])
  const updateDrawDataStruct = async (ds_id, table_name) => {await updateTableStruct(ds_id, table_name, setDrawDataStruct)}

  // 加载源表单表结构
  const [loadDataStruct, setLoadDataStruct] = useState([])
  const updateLoadDataStruct = async (id, table_name) => {await updateTableStruct(id, table_name, setLoadDataStruct)}

  // 更新表结构
  const updateTableStruct = async (id, table_name, setFunc) => {
    const { data } = await getTableSchema({id, table_name})
    if (data.code === 200) {
      const tableList = data.data.map(item => {
        const splitData = item.split(':')
        return {
          key: splitData[0],
          id: splitData[0],
          field: splitData[1],
          type: splitData[2]
        }
      })
      setFunc(tableList)
    } else {
      message.error('表结构数据加载失败')
    }
  }

  // 配置提取源表单
  const [drawDataForm] = Form.useForm()

  // 配置加载源表单
  const [loadDataForm] = Form.useForm()

  // 规则表单
  const [ruleForm] = Form.useForm()

  // 同步参数表单
  const [syncDataForm] = Form.useForm()

  // 当前表单
  const [currentForm, setCurrentForm] = useState(drawDataForm)

  // 上一步/下一步
  const changeStep = num => {
    if (num === -1) {
      setIsFinishBuild(false)
    }
    setCurrentStep(currentStep + num)
  }

  // 监听步骤设置当前表单
  useEffect(() => {
    switch (currentStep) {
      case 0:
        setCurrentForm(drawDataForm)
        break
      case 1:
        setCurrentForm(loadDataForm)
        break
      case 2:
        setCurrentForm(ruleForm)
        break;
      case 3:
        setCurrentForm(syncDataForm)
        break
      default:
        break
    }
  }, [currentStep])

  // 右侧表结构可视
  const [visible, setVisible] = useState(false)

  // 展示
  const showDrawer = () => {
    setVisible(true)
  }

  // 关闭
  const onClose = () => {
    setVisible(false)
  }

  // 获取列表数据
  const fetchDataSourceList = async () => {
    const { data } = await getDataSourceList()
    if (data.code === 200) {
      const list = data.data.items.map(item => {
        return {
          key: item.id,
          datasource_name: item.datasource_name,
          datasource: item.datasource,
        }
      })
      setDataSourceList(list)
    }
  }

  useEffect(() => {
    fetchDataSourceList()
  }, [])

  // 下一步
  const nextStep = () => {
    if (currentStep === 2) {
      console.log(stepThreeRef.current)
    }
    currentForm
      .validateFields()
      .then(() => {
        changeStep(1)
      })
      .catch(err => {
        message.error('请检查表单数据是否完整')
      })
  }

  // 完成构建
  const finishBuild = async () => {
    setBuilding(true)
    setTimeout(() => {
      message.success('构建成功')
      setBuilding(false)
      setIsFinishBuild(true)
    }, 2000)
  }

  // 构建表单
  const build = () => {
    finishBuild()
  }

  // 完成提交
  const finishSubmit = async () => {
    setSubmiting(true)
    setTimeout(() => {
      message.success('提交成功')
      setSubmiting(false)
    }, 2000)
  }

  // 提交表单
  const submit = () => {
    currentForm
      .validateFields()
      .then(() => {
        console.log('submit')
        finishSubmit()
      })
      .catch(err => {
        message.error('请检查表单数据是否完整')
      })
  }

  return (
    <SyncTask>
      {/* 步骤条 */}
      <Steps current={currentStep} labelPlacement="vertical" size="small">
        <Step title="步骤1: 配置提取源" />
        <Step title="步骤2: 配置加载源" />
        <Step title="步骤3: 配置转换规则" />
        <Step title="步骤4: 设置同步参数" />
      </Steps>

      {/* 表单项 */}
      {/* 配置提取源 */}
      {currentStep === 0 && <StepOne drawDataForm={drawDataForm} dataSourceList={dataSourceList} updateTableStruct={updateDrawDataStruct}/>}
      {/* 配置加载源 */}
      {currentStep === 1 && <StepTwo loadDataForm={loadDataForm} dataSourceList={dataSourceList} updateTableStruct={updateLoadDataStruct}/>}

      {/* 配置转换规则 */}
      {currentStep === 2 &&
        <StepThree
          onRef={stepThreeRef}
          drawDataForm={drawDataForm}
          loadDataForm={loadDataForm}
          ruleForm={ruleForm}
        />
      }

      {/* 设置同步参数 */}
      {currentStep === 3 && <StepFour syncDataForm={syncDataForm} />}

      {/* 按扭操作 */}
      {/* 表结构预览 */}
      {(currentStep === 0 || currentStep === 1 ) && 
        <>
          <Button
            type="primary"
            onClick={showDrawer}
            className="check__btn"
            size="large"
            icon={<MenuFoldOutlined />}>
            表结构预览
          </Button>
          <Drawer
            title="表结构预览"
            placement="right"
            onClose={onClose}
            visible={visible}
            width={600}
            mask={false}
            destroyOnClose={true}
            closeIcon={<MenuUnfoldOutlined style={{ color: '#1881DA' }} />}
          >
            <DataTableStruct formData={currentForm}  tableData={currentStep === 0 ? drawDataStruct : loadDataStruct}/>
          </Drawer>
        </>
      }

      {/* 按扭操作 */}
      <Space style={{ margin: '20px' }}>
        <Button
          onClick={() => {
            changeStep(-1)
          }}
          disabled={currentStep === 0 || building}
        >
          上一步
        </Button>
        {currentStep === 3 ? (
          <Button
            type="primary"
            onClick={isfinishBuild ? submit : build}
            loading={isfinishBuild ? submiting : building}>
            {isfinishBuild ? '提交' : '构建'}
          </Button>
        ) : (
          <Button type="primary" onClick={nextStep}>
            下一步
          </Button>
        )}
      </Space>
    </SyncTask>
  )
}
