<script lang="ts" setup>
import { createCraft, updateCraft } from '@/apis/crafts'
import { ElMessage } from 'element-plus'
import { ref } from 'vue'
import { StepCmdDescMap } from '../../views/craft/craft_constant'
import FtButton from '../common/FTButton/index.vue'
import FTDialog from '../common/FTDialog/index.vue'
import TransferLeft from './TransferLeft.vue'
import TransferRight from './TransferRight.vue'

const emit = defineEmits<{
  (e: 'ok'): void
}>()

const visible = ref(false)
const stepStructs = ref<CraftTypes.StepStruct[]>([])
const craftObj = ref<CraftTypes.Craft>({})
const loading = ref(false)
const saveRef = ref<CraftTypes.SaveRef | null>(null)
const tempStepStructs = ref<CraftTypes.StepStruct[]>([])
const oresId = 1
const stepCmds: CraftTypes.StepCmd[] = [
  // 'upTray',
  // 'downTray',
  'addLiquid',
  // 'moveToSol',
  // 'moveToHeat',
  'shaking',
  'startHeating',
  // 'stopHeating',
  'takePhoto',
  // 'delay',
]
const openDialog = () => {
  visible.value = true
}

const closeDialog = () => {
  stepStructs.value = []
  craftObj.value.name = ''
  visible.value = false
}

const editDialog = (craftInfo: CraftTypes.Craft) => {
  craftObj.value = { ...craftInfo }
  if (craftInfo && craftInfo.steps) {
    const step = JSON.parse(craftInfo.steps)
    /* eslint-disable no-debugger */
    if (step && step.length) {
      step.forEach((item: CraftTypes.StepStruct) => {
        if (item.method === 'addLiquid') {
          const list = item.params.tubeSolList
          if (list && list.length === 16 && item.params.tubeSolList) {
            item.params.tubeSolList = [{
              tubeNum: 0,
              addLiquidList: item.params.tubeSolList[0].addLiquidList,
            }]
          }
        }
      })
    }
    stepStructs.value = step
  }
  openDialog()
}

function onConfirm() {
  if (!craftObj.value.name) {
    ElMessage.warning('请输入工艺名称')
    return
  }
  const stepList = JSON.parse(JSON.stringify(stepStructs.value))
  for (const step of stepList) {
    if (step.method === 'addLiquid') {
      const list = step.params.tubeSolList
      if (list && list.length) {
        list.forEach((item: any) => {
          const tubeNum = item.tubeNum
          if (tubeNum === 0) {
            const tubeSolList: CraftTypes.TubeSolStruct[] = []
            for (let index = 0; index < 16; index++) {
              tubeSolList.push({
                tubeNum: index + 1,
                addLiquidList: item.addLiquidList,
              })
            }
            step.params.tubeSolList = tubeSolList
          }
        })
      }
    }
  }
  craftObj.value.steps = JSON.stringify(stepList)
  confirmCraftEdit(craftObj.value)
}

const confirmCraftEdit = (craft: CraftTypes.Craft) => {
  let req
  if (craft.id) {
    req = updateCraft(craft)
  }
  else {
    craft = { name: craft.name, steps: craft.steps, oresId }
    req = createCraft(craft)
  }
  loading.value = true
  saveRef.value && saveRef.value.setLoading(true)
  req.then(() => {
    saveRef.value && saveRef.value.setLoading(false)
    ElMessage.success('保存成功')
    emit('ok')
    closeDialog()
  }).catch((e) => {
    console.log('保存工艺失败---', e, tempStepStructs.value)
    saveRef.value && saveRef.value.setLoading(false)
  })
}

function addStep(step: CraftTypes.StepCmd) {
  let st: CraftTypes.StepStruct
  if (step === 'addLiquid') {
    st = {
      method: step,
      params: {
        tubeSolList: [{
          tubeNum: 0,
          addLiquidList: [{
            solId: 1,
            volume: 10,
          }],
        }],
      },
    }
  }
  else if (step === 'startHeating') {
    st = {
      method: step,
      params: {
        temperature: 100,
      },
    }
  }
  else if (step === 'delay') {
    st = {
      method: step,
      params: {
        second: 10,
      },
    }
  }
  else if (step === 'shaking') {
    st = {
      method: step,
      params: {
        second: 30,
      },
    }
  }
  else {
    st = {
      method: step,
    }
  }
  stepStructs.value = [...stepStructs.value, st]
  tempStepStructs.value = JSON.parse(JSON.stringify(stepStructs.value))
}

function onStepItemDel(order: number) {
  stepStructs.value = stepStructs.value.filter((s, i) => i !== order - 1)
}

function transferChange(stepData: CraftTypes.StepStruct, order: number) {
  console.log('order === ', stepStructs.value, stepData, order)
}

defineExpose({
  openDialog,
  closeDialog,
  editDialog,
})
</script>

<template>
  <FTDialog v-model="visible" title="添加工艺" style="width:70vw; height:70vh">
    <div>
      <div class="mt-5 mb-8 flex items-center">
        <label class="font-medium mr-4">工艺名称：</label>
        <el-input
          v-model.trim="craftObj.name"
          style="width: 200px"
          size="small"
          type="text"
          placeholder="请输入名称"
          class="flex-auto bg-[#f6f6f6] h-11 leading-10 rounded-sm px-4"
        />
      </div>
      <div class="craft-title">
        <div>
          工艺步骤
        </div>
        <div class="title-right">
          选择的步骤
        </div>
      </div>
      <div class="step-content">
        <div class="transfer-left">
          <TransferLeft v-for="cmd in stepCmds" :key="cmd" :title="StepCmdDescMap[cmd]" @click="addStep(cmd)" />
        </div>
        <div v-if="stepStructs && stepStructs.length" class="transfer-right">
          <TransferRight v-for="(step, idx) in stepStructs" :key="idx" :order="idx + 1" :step="step" type="add" @del="onStepItemDel" @transfer-change="transferChange" />
        </div>
        <div v-else>
          <el-empty description="description">
            <template #description>
              未选择工艺步骤
            </template>
          </el-empty>
        </div>
      </div>
    </div>
    <template #footer>
      <div class="footer">
        <FtButton @click="closeDialog">
          取消
        </FtButton>
        <FtButton ref="saveRef" :loading="loading" :click-handle="onConfirm">
          确定
        </FtButton>
      </div>
    </template>
  </FTDialog>
</template>

<style lang="scss" scoped>
.transfer-left{
 display: grid;
 grid-template-columns: 1fr 1fr;
 gap: 1.4rem;
 width: 12.5rem;
 place-items: center;
 height: 3rem;
}

.transfer-right{
 max-height: 40vh;
 overflow: auto;
}

.step-content{
 margin-top:1rem;
 display: grid;
 grid-template-columns: 1fr 1fr;
 height: 21rem;
}
.footer{
 display: flex;
 height: 5rem;
 justify-content: center;
 align-items: center;
}

.craft-title{
  display: grid;
  grid-template-columns: 1fr 1fr;
  div{
    font-size:12px;
    margin-top: 5px;
  }
  .title-right{
    display: flex;
    justify-content: center;
  }
}
</style>
