<script setup lang="ts">
import { createCraft, delCraft, getCraftList as getCraftListApi, updateCraft } from 'apis/crafts'
import { getSolsList } from 'apis/solution'
import { ElMessageBox } from 'element-plus'
import { FtMessage } from 'libs/message'
import { socket } from 'libs/socket'
import { useHomeStore } from 'stores/homeStore'
import { onMounted, onUnmounted, ref } from 'vue'

const loading = ref(false)

const statisticNumber = ref(0)

const homeStore = useHomeStore()
onMounted(async () => {
  loading.value = true
  await getSolutionList()
  await getCraftList()
  loading.value = false
  socket.init(receiveMessage, 'pump_position')
})
/* onUnmounted(() => {
  socket.unregisterCallback(receiveMessage, 'pump_position')
}) */
const receiveMessage = (data: number) => {
  console.log(`接收到泵的转数${data}`)
  statisticNumber.value = statisticNumber.value + data
}

const form = ref<Craft.CraftItem>({})
const formRef = ref()

const rules = {
  solutionId: [
    { required: true, message: '请选择溶液', trigger: 'change' },
  ],
  concentration: [
    { required: true, message: '请输入溶液浓度', trigger: 'blur' },
  ],
  volume: [
    { required: true, message: '请输入加液量', trigger: 'blur' },
  ],
  revolutions: [
    { required: true, message: '请输入蠕动泵转速', trigger: 'blur' },
  ],
}

const solutionList = ref<Solution.SolutionItem[]>([])

const getSolutionList = async () => {
  solutionList.value = (await getSolsList()).list
}

const craftList = ref<Craft.CraftItem[]>([])

const getCraftList = async () => {
  craftList.value = (await getCraftListApi()).list
  form.value = {}
}

const save = async () => {
  const valid = await formRef.value.validate()
  if (!valid) {
    return
  }
  if (form.value.id) {
    await updateCraft(form.value)
  }
  else {
    await createCraft(form.value)
  }
  loading.value = true
  await getCraftList()
  loading.value = false
  FtMessage.success('保存成功')
}

const formatName = (data: Craft.CraftItem) => {
  const item = solutionList.value.find(item => item.id === data.solutionId)
  return `${item?.name}-${data.concentration}%-${data.volume}mL`
}

const nameClick = (item: Craft.CraftItem) => {
  const solution = solutionList.value.find(s => s.id === item.solutionId)
  form.value = {
    ...item,
  }
}

const delHandle = async (id: number | undefined) => {
  if (!id) {
    return
  }
  await ElMessageBox.confirm('确定删除吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
  await delCraft(`${id}`)
  loading.value = true
  await getCraftList()
  loading.value = false
  FtMessage.success('删除成功')
}
let currentCommandId = ''
// 正转 反转
const pumpRotate = async (direction: string) => {
  const valid = await formRef.value.validate()
  if (!valid) {
    return
  }
  currentCommandId = Date.now().toString()

  const params = {
    commandId: currentCommandId,
    command: 'pump_rotate_start',
    params: {
      direction,
      position: form.value.revolutions,
      solutionId: form.value.solutionId,
      concentration: form.value.concentration,
    },
  }
  await homeStore.sendControl(params)
}
// 停止
const pumpStop = async () => {
  const valid = await formRef.value.validate()
  if (!valid) {
    return
  }
  currentCommandId = Date.now().toString()
  const params = {
    commandId: currentCommandId,
    command: 'pump_rotate_stop',
    params: {
      solutionId: form.value.solutionId,
      concentration: form.value.concentration,
    },
  }
  await homeStore.sendControl(params)
}
// 预充
const pumpPreFill = async () => {
  const valid = await formRef.value.validate()
  if (!valid) {
    return
  }
  currentCommandId = Date.now().toString()
  const params = {
    commandId: currentCommandId,
    command: 'solution_pre_fill_start',
    params: {
      solutionId: form.value.solutionId,
      concentration: form.value.concentration,
    },
  }
  await homeStore.sendControl(params)
}
// 加液
const pumpAddSolution = async () => {
  const valid = await formRef.value.validate()
  if (!valid) {
    return
  }
  currentCommandId = Date.now().toString()
  const params = {
    commandId: currentCommandId,
    command: 'solution_add_start',
    params: {
      solutionId: form.value.solutionId,
      concentration: form.value.concentration,
      position: form.value.revolutions,
    },
  }
  await homeStore.sendControl(params)
}
</script>

<template lang="pug">
  div(class="craft-box")
    el-card(v-loading="loading")
      div(class="button-box")
        ft-button(type="primary" @click="() => form = {}")
          | 添加配方
        ft-button(type="danger" :disabled="!form.id" :click-handle="() => delHandle(form.id)")
          | 删除配方
      div(class="list-box")
        p(v-for="item in craftList" :key="item.id" class="name" :class="{ 'active-name': item.id === form.id }" @click="() => nameClick(item)")
          | {{ formatName(item) }}
    el-card(v-loading="loading")
      template(#header)
        span(v-show="form.id") 编辑配方
        span(v-show="!form.id") 新增配方
      el-form(ref="formRef" size="large" :model="form" :rules="rules" label-width="auto")
        el-form-item(label="溶液名称" prop="solutionId")
          el-select(v-model="form.solutionId" placeholder="请选择溶液")
            el-option(v-for="item in solutionList" :key="item.id" :label="item.name" :value="item.id")
        el-form-item(label="溶液浓度" prop="concentration")
          ft-input(v-model="form.concentration" placeholder="请输入溶液浓度" layoutName="number")
            template(#append)
              span %
        el-form-item(label="加液量" prop="volume")
          ft-input(v-model="form.volume" placeholder="请输入加液量" layoutName="number")
            template(#append)
              span mL
        el-form-item(label="蠕动泵转数" prop="revolutions")
          ft-input(v-model="form.revolutions" placeholder="请输入蠕动泵转数" layoutName="number")
            template(#append)
              span r
      div.statistic-box
            ft-button(type="default" size="small" :click-handle="()=>statisticNumber=0")
              | 重置
            span 蠕动泵体积及转数统计
            el-statistic(:value="statisticNumber")
            ft-button(type="default" size="small" :click-handle="()=>form.revolutions=statisticNumber")
              | 设置
      div.form-button-box
        div
          ft-button(type="primary" size="large" :click-handle="()=>pumpRotate('FORWARD')")
            | 加液
          ft-button(type="danger" size="large" :click-handle="()=>pumpStop()")
            | 停止
        div
          ft-button(type="primary" size="large" :click-handle="()=>pumpPreFill()")
            | 预充
          ft-button(type="primary" size="large" :click-handle="save")
            | 保存
</template>

<style scoped lang="stylus">
.craft-box
  background transparent !important
  box-shadow none !important
  display grid
  grid-template-columns 1fr 2.5fr
  grid-gap 20px
  .el-card
    display flex
    flex-direction column
    border-radius 10px
    :deep(.el-card__body)
      display flex
      flex-direction column
      justify-content space-between
      height 100%
      padding 0
      overflow hidden
      .button-box
        display flex
        justify-content center
        padding 20px 0
      .list-box
        flex 1
        padding 0 0 10px
        overflow auto
        border-top 1px solid #EBEEF5
        .name
          padding 10px 20px
          cursor pointer
          border-bottom 1px solid #EBEEF5
          border-left 3px solid transparent
          transition all 0.5s
        .active-name
          border-left 3px solid #409EFF
          background rgba(64, 158, 255, 0.2)
      .el-form
        padding 20px 150px
      .statistic-box
        display flex
        justify-content center
        align-items center
        .el-statistic
          margin 0 30px
      .form-button-box
        display flex
        justify-content space-evenly
        margin-bottom 30px
        .ft-button
          width 90px

:deep(.el-input-group__append)
  width 50px
</style>
