<script setup lang="ts" name="ProcessConfig">
import { ref } from 'vue'
import draggable from 'vuedraggable'
import { ElMessage } from 'element-plus'
import type { ISchedule, IScheduleSet } from '../task-interface'
import ProcessNode from './processNode.vue'
import ProcessNodeAdd from './processNodeAdd.vue'
import chooseLab from './chooseLab.vue'
import type { ILabList } from './lab-interface'
import useUserStore from '@/store/modules/user'
import { allocate, setMeasureProcess, setMeasureProcessByFfy } from '@/api/business/schedule/task'
const props = defineProps({
  type: {
    type: String,
    default: 'distribute',
  }, // 类型，决定调用哪个接口
  // 是否为详情展示页面
  detail: {
    type: Boolean,
    default: false,
  },
  // 样品id
  sampleId: {
    type: String,
    required: true,
  },
  // 委托单id
  orderId: {
    type: String,
    required: true,
  },
  list: {
    type: Array,
    default: () => [],
  },
  isDept: { // 是否是部门检测
    type: Boolean,
    default: false,
  },
})
const emits = defineEmits(['saveOver'])
// 用户信息
const user = useUserStore()
// 默认流程节点
const defaultProcess: IScheduleSet = {
  measurePersonId: '', // 执行人
  measurePerson: '', // 执行人名称
  measureSegmentId: '', // 执行部门
  measureSegment: '', // 执行部门名称
  executiveItem: '', // 检定项目
  // alreadyCertifications: 0, // 已出具证书总数
  requireCertifications: 1, // 应出具证书总数
  measureStatus: '', // 检测状态： 待分配，待检测，检测中，检测完, 已退回/取消
  measureStatusName: '', // 检测状态： 待分配，待检测，检测中，检测完, 已退回/取消
  updateTime: '', // 流程更新时间
}
// 检定流程列表
const processList = ref<IScheduleSet[]>([
  { ...defaultProcess },
])

watch(() => props.list, (val) => {
  if (props.list.length > 0) {
    processList.value = props.list as ISchedule[]
  }
},
{ deep: true, immediate: true })

// 点击添加流程
const processAdd = () => {
  processList.value.push({ ...defaultProcess })
}
// 检查是否允许移动
const checkMove = (evt: any) => {
  // 目的位置元素evt.relatedContext.element
  // 当前拖动元素evt.draggedContext.element
  if (evt.relatedContext.element.measureState !== '0') {
    return false
  }
  return true
}

// 选择实验室弹窗
const chooseLabDialog = ref()
// 批量添加流程
const batchProcessAdd = () => {
  chooseLabDialog.value.initDialog(true)
}

// 批量添加实验室
const batchChooseOver = (labs: ILabList[]) => {
  for (const item of labs) {
    const processTemp: IScheduleSet = {
      measurePersonId: '', // 执行人
      measurePerson: '', // 执行人名称
      measureSegmentId: item.deptId, // 执行部门
      measureSegment: item.organizeName, // 执行部门名称
      executiveItem: '', // 检定项目
      measureSequence: '', // 监测顺序
      // alreadyCertifications: 0, // 已出具证书总数
      requireCertifications: 1, // 应出具证书总数
      measureStatus: '', // 检测状态： 待分配，待检测，检测中，检测完, 已退回/取消
      measureStatusName: '', // 检测状态： 待分配，待检测，检测中，检测完, 已退回/取消
      updateTime: '', // 流程更新时间
    }
    // 不能添加已经存在的实验室
    const index = processList.value.findIndex(e => e.measureSegmentId === item.deptId)
    if (index === -1) {
      processList.value.push(processTemp)
    }
    else {
      ElMessage.warning(`${item.organizeName}已添加过`)
    }
  }
}

// 保存流程
const saveProcess = () => {
  const form = {
    measureProcessList: processList.value,
    executiveList: processList.value,
    orderId: props.orderId,
    sampleId: props.sampleId,
  }
  const index = form.measureProcessList.findIndex(item => !item.measureSegmentId)
  if (index !== -1) {
    ElMessage.warning(`第${index + 1}个流程：检定环节不能为空`)
    return false
  }

  // 处理顺序
  for (const key in form.measureProcessList) {
    form.measureProcessList[key].measureSequence = (parseInt(key) + 1).toString()
  }
  if (props.isDept) { // 是部门检测
    // 只能操作此用户自己的实验室
    const index = processList.value.findIndex(item => item.measureSegmentId === user.deptId)
    if (index !== -1) {
      const params = {
        id: processList.value[index].id,
        measurePersonId: processList.value[index].measurePersonId, // 分配检定人员id（在本部门下的计量人员列表中选择）
        requireCertifications: processList.value[index].requireCertifications, // 应出具证书总数
      }
      allocate(params).then((res) => {
        ElMessage.success('保存成功')
        emits('saveOver')
      })
    }
    else {
      ElMessage.warning('未在列表中找到此用户的部门')
    }
  }
  else { // 任务分发
    if (props.type == 'distribute') {
      setMeasureProcess(form).then((res) => {
        ElMessage.success('保存成功')
        emits('saveOver')
      })
    }
    else {
      setMeasureProcessByFfy(form).then((res) => {
        ElMessage.success('保存成功')
        emits('saveOver')
      })
    }
  }
}
// 删除流程
const deleteProcess = (index: number) => {
  processList.value.splice(index, 1)
}

// --------暴露方法
defineExpose({ saveProcess, batchProcessAdd, deleteProcess })
</script>

<template>
  <div>
    <div class="process-container">
      <draggable v-model="processList" item-key="id" class="process-draggable" handle=".handle" :move="checkMove">
        <!-- eslint-disable-next-line vue/no-unused-vars -->
        <template #item="{ process, index }">
          <process-node v-model="processList[index]" :process-list="processList" :step="index + 1" :is-dept="props.isDept" :detail="props.detail" @delete="deleteProcess(index)" />
        </template>
        <template #footer>
          <process-node-add v-if="!props.isDept && !props.detail" @click="processAdd" />
        </template>
      </draggable>
    </div>
    <choose-lab ref="chooseLabDialog" @confirm-checkout="batchChooseOver" />
  </div>
</template>

<style lang="scss" scoped>
.process-container {
  .process-draggable {
    display: flex;
    flex-wrap: wrap;
  }
}
</style>
