<script lang="ts" setup>
import { syncSendCmd } from 'apis/system'
import { ElMessage, ElMessageBox } from 'element-plus'
import { cloneDeep } from 'lodash'
import { onMounted, ref, watch } from 'vue'

import { FtMessage } from '@/libs/message'
import { FtMessageBox } from '@/libs/messageBox'
import { convertValuesToInt } from '@/libs/utils'
import { useFormulaStore } from '@/stores/formulaStore'

const formulaStore = useFormulaStore()
const currentFormula = ref<Formula.FormulaItem>(formulaStore.currentSelectedFormulaInfo)

// 移除列表的选中
const selectedIndexRest = async () => {
  formulaStore.updateSelectedIndex(null)
  console.log('子组件方法被调用')
}
const userData = localStorage.getItem('user')
const userInfo = userData ? JSON.parse(userData) : {}

// 暴露方法给父组件
defineExpose({
  selectedIndexRest,
})

onMounted(() => {
  initFormulaList()
})
watch(() => formulaStore.selectedIndex, () => {
  if (formulaStore.selectedIndex == null) {
    if (formulaStore.formulaList && formulaStore.formulaList.length > 0) {
      formulaStore.updateSelectedIndex(formulaStore.formulaList.length - 1)
      const currentIndex: number | null = formulaStore.selectedIndex
      const selectItem: Formula.FormulaItem = formulaStore.formulaList[currentIndex]
      const item = convertValuesToInt(selectItem) as Formula.FormulaItem
      formulaStore.updateSelectedFormulaData(item)
    }
    else {
      const formData = cloneDeep(formulaStore.resetFormulaInfo)
      formulaStore.updateSelectedFormulaData(convertValuesToInt(formData) as Formula.FormulaItem)
    }
  }
  else {
    const currentIndex: number = formulaStore.selectedIndex
    const selectItem: Formula.FormulaItem = formulaStore.formulaList[currentIndex]
    const item = convertValuesToInt(selectItem) as Formula.FormulaItem
    formulaStore.updateSelectedFormulaData(item)
  }
})
const initFormulaList = () => {
  formulaStore.initFormulaList()
}
const selectRecipe = (item: Formula.FormulaItem, index: number) => {
  formulaStore.updateSelectedIndex(index)
  formulaStore.updateSelectedIndex(index)
  item = convertValuesToInt(item) as Formula.FormulaItem
  formulaStore.updateSelectedFormulaData(item)
}

const onStartFormula = (item: Formula.FormulaItem) => {
  formulaStore.updateSelectedFormulaData(item)
  // 执行配方时做设备的状态检查
  FtMessageBox.warning('请确认是否使用此配方进行消毒？').then(() => {
    currentFormula.value = item
    if (item.formula_id) {
      const params = {
        className: 'DisinfectionCtrlServiceExt',
        fnName: 'startWithFormula',
        params: {
          formulaid: item.formula_id,
        },
      }
      syncSendCmd(params).then((res) => {
        if (res.ackcode === 0) {
          // 把选择执行的配方同步至运行参数
          formulaStore.updateSelectedFormulaDataByList(item)
          FtMessage.success('已开始消毒')
        }
      })
    }
  })
}

const deleteRecipe = (item: Formula.FormulaItem) => {
  ElMessageBox.confirm('请确认是否删除?', '删除', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    if (formulaStore.selectedFormulaInfo?.formula_id === item.formula_id) {
      ElMessage.warning('禁止修改正在执行的配方信息!')
      return
    }
    if (item.formula_id) {
      const delParams = {
        className: 'SettingMgrService',
        fnName: 'delFormula',
        params: {
          formula_id: item.formula_id,
        },
      }
      syncSendCmd(delParams).then(() => {
        FtMessage.success('操作成功')
        formulaStore.initFormulaList()
      })
    }
  })
}
</script>

<template>
  <div v-if="formulaStore.formulaList.length" class="recipe-management">
    <ul class="recipe-list">
      <li
        v-for="(item, index) in formulaStore.formulaList"
        :key="index"
        :class="{ selected: formulaStore.selectedIndex === index }"
        @click="selectRecipe(item, index)"
      >
        <span class="formula-name">{{ item.name }}</span>
        <div class="actions">
          <el-button class="view-button" @click.stop="onStartFormula(item)">
            执行配方
          </el-button>
          <el-button v-if="userInfo.roleType === 'admin'" class="delete-button" @click.stop="deleteRecipe(item)">
            删除
          </el-button>
        </div>
      </li>
    </ul>
  </div>
  <div v-else>
    <el-empty description="description">
      <template #description>
        <span style="color: #ababab">未配置配方</span>
      </template>
    </el-empty>
  </div>
</template>

<style scoped>
.recipe-management {
  border: 1px solid #ccc;
  padding: 10px;
  border-radius: 5px;
  overflow: auto;
  width: 30vw;
}

.recipe-list {
  list-style: none;
  padding: 0;
  margin: 0;
  .formula-name {
    font-size: 1.2rem;
    color: var(--el-text-color-regular);
    width: 10rem;
  }
}

.recipe-list li {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px;
  border-radius: 4px;
  margin-bottom: 8px;
  transition: all 0.2s;
  cursor: pointer;
}

.recipe-list li:hover {
  background-color: #f5f7fa;
}

.recipe-list li.selected {
  background-color: #e6f7ff;
  border-left: 5px solid #1890ff;
  padding: 9px;
}

.actions {
  display: flex;
  align-items: center;
}

.view-button,
.delete-button {
  font-size: 1rem;
  border: none;
  padding: 4px 8px;
  border-radius: 3px;
  cursor: pointer;
  margin-right: 5px;
  transition: all 0.3s;
}

.view-button {
  background-color: #e6f0ff;
  color: #1890ff;
}

.view-button:hover {
  background-color: #1890ff;
  color: white;
}

.delete-button {
  background-color: #ffe6e6;
  color: #ff4d4f;
}

.delete-button:hover {
  background-color: #ff4d4f;
  color: white;
}

.selected-icon {
  color: #0681f5;
  /* margin-left: 8px; */
}
</style>
