<template>
  <!-- 搜索工作栏 -->
  <ContentWrap>
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="sop名称" prop="sopName">
        <el-input
          v-model="queryParams.sopName"
          placeholder="请输入sop名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="sop类型" prop="sopType">
        <el-select
          v-model="queryParams.sopType"
          placeholder="请选择sop类型"
          clearable
          class="!w-240px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.SOP_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" />
          重置
        </el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['iscs:sop:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" />
          新增
        </el-button>
        <el-button
          type="danger"
          plain
          :disabled="multiple"
          @click="handleDelete()"
          v-hasPermi="['iscs:sop:delete']"
        >
          <Icon icon="ep:delete" class="mr-5px" />
          批量删除
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="sopList"
      @selection-change="handleSelectionChange"
      style="width: 100%"
    >
      <el-table-column type="selection" width="50" align="center" fixed />
      <el-table-column label="ID" prop="id" align="center" width="60" fixed />
      <el-table-column label="sop名称" prop="sopName" width="300" />
      <el-table-column label="sop类型" prop="sopTypeName" width="100" />
      <el-table-column
        label="所属区域"
        prop="workstationName"
        :show-overflow-tooltip="true"
        width="100"
      />
      <el-table-column label="设备/工艺" prop="machineryName" align="center" width="200" />
      <el-table-column label="是否生效" align="center" width="120">
        <template #default="scope">
          <el-switch
            :model-value="scope.row.sopStatus"
            active-value="1"
            inactive-value="0"
            @update:modelValue="(val) => handleStatusChange(scope.row, val)"
          />
        </template>
      </el-table-column>
      <el-table-column label="启用通知" align="center" width="100">
        <template #default="scope">
          <el-switch
            :model-value="scope.row.enableNotifications"
            :active-value="1"
            :inactive-value="0"
            @update:modelValue="(val) => handleNotificationsChange(scope.row, val)"
          />
        </template>
      </el-table-column>
      <el-table-column label="启用执行计划" align="center" width="120">
        <template #default="scope">
          <el-switch
            :model-value="scope.row.enableExecutionPlan"
            :active-value="1"
            :inactive-value="0"
            @update:modelValue="(val) => handleExecutionPlanChange(scope.row, val)"
          />
        </template>
      </el-table-column>
      <el-table-column label="下次作业开始时间" prop="nextExecutDate" width="150" />
      <el-table-column label="操作" align="center" width="550" fixed="right">
        <template #default="{ row }">
          <el-button
            link
            :icon="Promotion"
            type="danger"
            @click="executeImmediately(row.id)"
            v-hasPermi="['iscs:sop:update']"
          >
            立即执行
          </el-button>
          <el-button
            link
            :icon="Bell"
            type="primary"
            @click="openForm('NotificationRules', row.id, row.sopName, row.workstationId)"
            v-hasPermi="['iscs:sop:update']"
          >
            通知规则
          </el-button>
          <el-button
            link
            :icon="DocumentChecked"
            type="primary"
            @click="openForm('executPlan', row.id, row.sopName)"
            v-hasPermi="['iscs:sop:update']"
          >
            执行计划
          </el-button>
          <el-button
            link
            :icon="RefreshLeft"
            type="primary"
            @click="openForm('historicalJob', row.id, row.sopName)"
            v-hasPermi="['iscs:sop:update']"
          >
            历史作业
          </el-button>
          <el-button
            link
            :icon="Edit"
            type="primary"
            @click="openForm('update', row.id)"
            v-hasPermi="['iscs:sop:update']"
          >
            修改
          </el-button>
          <el-button
            link
            type="danger"
            :icon="Delete"
            @click="handleDelete(row.id)"
            v-hasPermi="['iscs:sop:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <Pagination
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNo"
      :total="total"
      @pagination="getList"
    />
  </ContentWrap>
  <!--  弹框-->
  <!-- Notifications 通知规则弹框-->
  <el-dialog v-model="notificationsDialogVisible" title="通知规则" width="500">
    <!-- 没有设置通知规则且开关是关闭状态-->
    <span v-if="notificationsTempVal == 1 && row.enableNotifications !== 1">
      请首先设置通知规则后，才能启用，点击确定前往设置。
    </span>
    <!-- 设置了通知规则开关是关闭状态  -->
    <span v-if="notificationsTempVal == 0 && row.enableNotifications !== 1">
      您确定要启用通知吗？
    </span>
    <!--  设置了通知规则开关是开启状态  -->
    <span v-if="notificationsTempVal == 0 && row.enableNotifications == 1">
      您确定要禁用通知吗？
    </span>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleDialogConfirm()">确定</el-button>
        <el-button @click="notificationsDialogVisible = false"> 取消</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- enableExecutionPlan 执行计划弹框-->
  <el-dialog v-model="ExecutionPlanDialogVisible" title="执行计划" width="500">
    <!--    没有创建过执行计划并且开关是关闭状态-->
    <span v-if="executePlanNum == false && row.enableExecutionPlan !== 1">
      请首先设置一个 SOP执行计划，才能启用，点击确定前往设置
    </span>
    <!--    创建过执行计划并且开关是关闭状态-->
    <div v-if="executePlanNum == true && row.enableExecutionPlan == 1">
      <p style="margin-left: 9px">您确定要禁用执行计划吗？</p>
      <!-- 且存在未完成的作业记录，-->
      <section v-if="unFinishedJob == true" style="margin: 10px">
        <p>如果需要同时取消尚未执行的作业，请勾选"取消作业"后，再点击确定。</p>
        <el-checkbox
          v-model="isDeleteJob"
          label="取消作业"
          :true-value="1"
          :false-value="0"
          style="margin: 8px 0"
        />
      </section>
    </div>
    <!--   创建过执行计划，并且开关是关闭状态-->
    <span v-if="executePlanNum == true && row.enableExecutionPlan !== 1">
      您确定要开启执行计划吗？
    </span>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleExecuteDialogConfirme()"> 确定</el-button>
        <el-button @click="ExecutionPlanDialogVisible = false">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import * as SopApi from '@/api/sop'
import { DICT_TYPE, getIntDictOptions, getStrDictOptions } from '@/utils/dict'
import * as NotificationRules from '@/api/sop/notificationRules'
import {
  Promotion,
  DocumentChecked,
  Delete,
  Edit,
  Bell,
  RefreshLeft
} from '@element-plus/icons-vue'
import { updateSopEnableExecutionPlan, updateSopEnableNotification } from '@/api/sop'
import { getNotifyConfigPage, selectNotifyConfigById } from '@/api/sop/notificationRules'
import * as ExecutePlan from '@/api/sop/executePlan'
import { getNotStartJobBySopId } from '@/api/sop/executePlan'
import * as TechnologyApi from '@/api/dv/technology'
import { handleTree } from '@/utils/tree'
import * as JobApi from '@/api/job/index'
import * as MarsDeptApi from '@/api/system/marsdept'

// 添加初始化标志位
const isInitialized = ref(false)
const router = useRouter()

defineOptions({ name: 'SopManagement' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const loading = ref(true) // 列表的加载中
const sopList = ref([]) // 列表的数据
const total = ref(0) // 总条数
const ids = ref<number[]>([]) // 选中的数据
const multiple = ref(true) // 非多个禁用
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  sopName: undefined,
  sopType: undefined
})
const queryFormRef = ref() // 搜索的表单
const notificationsDialogVisible = ref(false) // 通知规则弹框
const ExecutionPlanDialogVisible = ref(false) //执行计划弹框
const row = ref({}) // 当前操作的行数据
const notificationsTempVal = ref(0) // 临时保存用户点击后的值
const detailData = ref([])
const executePlanNum = ref(false) //有没有执行计划
const unFinishedJob = ref(false) //是否有未执行的作业记录
const isDeleteJob = ref(0)

// 是否生效
const handleStatusChange = async (row, val) => {
  if (!isInitialized.value) return

  const originalValue = row.sopStatus

  try {
    const data = {
      ...row,
      sopStatus: val
    }

    await SopApi.updateSopStatus(data)
    ElMessage.success(val == 1 ? '已生效' : '已取消生效')

    // 成功后更新值（防止 UI 不更新）
    row.sopStatus = val
  } catch (err) {
    // 接口失败，回滚原始值
    row.sopStatus = originalValue

    // 强制刷新 UI
    await nextTick()

    // 提示错误
    // ElMessage.error('状态更新失败，请重试')
  }
}
// 是否开启通知
const handleNotificationsChange = async (r, val) => {
  if (!isMounted.value) return // 页面初始化时触发的 change，忽略
  row.value = r
  const detailQuery = { sopId: row.value.id }
  detailData.value = await NotificationRules.getNotifyConfigPage(detailQuery)
  notificationsDialogVisible.value = true
  if (detailData.value.list.length == 0) {
    notificationsTempVal.value = 1 //没有创建过通知
  } else {
    notificationsTempVal.value = 0
  }
}

// 通知规则弹框确认按钮
const handleDialogConfirm = async () => {
  // console.log(row.value,'那搭配；')
  if (notificationsTempVal.value == 1 && row.value.enableNotifications !== 1) {
    // 启用通知 -> 跳转去设置页面
    notificationsDialogVisible.value = false
    router.push({
      name: 'NotificationRules',
      query: {
        id: row.value.id,
        sopName: row.value.sopName,
        workstationId: row.value.workstationId,
        type: 'notificationRules'
      }
    })
  } else if (notificationsTempVal.value == 0 && row.value.enableNotifications !== 1) {
    // 启用通知 -> 调接口更新
    try {
      await SopApi.updateSopEnableNotification({
        id: row.value.id,
        enableNotifications: 1
      })
      ElMessage.success('通知已启用')
      row.value.enableNotifications = 1 // 更新本地数据
      getList()
    } catch (err) {
      ElMessage.error('启用失败')
    } finally {
      notificationsDialogVisible.value = false
    }
  } else if (notificationsTempVal.value == 0 && row.value.enableNotifications == 1) {
    // 禁用通知 -> 调接口更新
    try {
      await SopApi.updateSopEnableNotification({
        id: row.value.id,
        enableNotifications: 0
      })
      ElMessage.success('通知已禁用')
      row.value.enableNotifications = 0 // 更新本地数据
      getList()
    } catch (err) {
      ElMessage.error('禁用失败')
    } finally {
      notificationsDialogVisible.value = false
    }
  }
}

// 是否打开执行计划
const handleExecutionPlanChange = async (r, val) => {
  if (!isMounted.value) return // 页面初始化时触发的 change，忽略

  row.value = r
  ExecutionPlanDialogVisible.value = true
  // 判断有没有创建执行记录
  const excuteList = await ExecutePlan.selectSopExecutionPlanBySopId(row.value.id)
  console.log(excuteList, '属是素数')
  if (excuteList == null) {
    // sop没有计划时赋值为0
    executePlanNum.value = false
  } else {
    executePlanNum.value = true
  }
  // 判断有没有未执行的作业记录
  const isNotFinishJob = await ExecutePlan.getNotStartJobBySopId(row.value.id)
  console.log(isNotFinishJob, '是否有未执行的作业记录')
  // 没有创建记录
  unFinishedJob.value = isNotFinishJob.length > 0
}

// 执行计划弹框确认按钮
const handleExecuteDialogConfirme = async () => {
  const hasPlan = executePlanNum.value === true
  const isEnabled = row.value.enableExecutionPlan == 1

  console.log(isDeleteJob.value, '值拿到的正确吗')

  // 没有计划且是关闭状态 ➜ 跳转
  if (!hasPlan && !isEnabled) {
    ExecutionPlanDialogVisible.value = false
    router.push({
      name: 'ExecutePlan',
      query: {
        id: row.value.id,
        sopName: row.value.sopName,
        type: 'executPlan'
      }
    })
    return
  }

  // 有计划并处于开启状态 ➜ 禁用计划
  if (hasPlan && isEnabled) {
    try {
      await SopApi.updateSopEnableExecutionPlan({
        id: row.value.id,
        enableExecutionPlan: 0,
        deleteNotStartJob: isDeleteJob.value
      })
      ElMessage.success('计划已禁用')
      row.value.enableExecutionPlan = 0
      getList()
    } catch (err) {
      ElMessage.error('禁用失败')
    } finally {
      ExecutionPlanDialogVisible.value = false
    }
    return
  }

  // 有计划但处于关闭状态 ➜ 开启计划
  if (hasPlan && !isEnabled) {
    try {
      await SopApi.updateSopEnableExecutionPlan({
        id: row.value.id,
        enableExecutionPlan: 1
      })
      ElMessage.success('计划已开启')
      row.value.enableExecutionPlan = 1
      getList()
    } catch (err) {
      ElMessage.error('开启失败')
    } finally {
      ExecutionPlanDialogVisible.value = false
    }
    return
  }

  // 其它异常状态
  ElMessage.warning('当前状态异常，请刷新重试')
  ExecutionPlanDialogVisible.value = false
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: any[]) => {
  ids.value = selection.map((item) => item.id)
  multiple.value = !selection.length
}

/** 查询模式列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await SopApi.getSopPage(queryParams)
    sopList.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.pageNo = 1
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改/查看操作 */
const openForm = (type: string, id?: number, sopName?: string, workstationId?: number) => {
  if (type == 'create') {
    router.push({
      name: 'CreateSop',
      query: { id: id, type: 'create' }
    })
  } else if (type == 'update') {
    router.push({
      name: 'UpdateSop',
      query: { id: id, type: 'update' }
    })
  } else if (type == 'executPlan') {
    // 执行计划
    router.push({
      name: 'ExecutePlan',
      query: {
        id: id,
        sopName: sopName,
        type: 'executPlan'
      }
    })
  } else if (type == 'NotificationRules') {
    //   通知规则
    router.push({
      name: 'NotificationRules',
      query: {
        id: id,
        sopName: sopName,
        workstationId: workstationId,
        type: 'notificationRules'
      }
    })
  } else if (type == 'historicalJob') {
    //   通知规则
    router.push({
      name: 'HistoricalSopJob',
      query: {
        id: id,
        sopName: sopName,
        workstationId: workstationId,
        type: 'HistoricalSopJob'
      }
    })
  }
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  const sopId = id || ids.value
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await SopApi.deleteSopList(sopId)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

// sop立即执行
// 创建查找映射
const workstationMap = new Map()
const machineryMap = new Map()
const sopJobData = reactive({
  machineryId: null,
  modeId: null,
  workstationId: null,
  ticketName: null,
  sopId: null,
  ticketType: null
})
const executeImmediately = async (id: any) => {
  const data = await SopApi.selectSopById(id)
  sopJobData.machineryId = data.machineryId
  sopJobData.modeId = data.modeId
  sopJobData.workstationId = data.workstationId
  sopJobData.sopId = id
  sopJobData.ticketType = data.sopType
  console.log(sopJobData, 'sopJobData')
  await generateJobName()
  const Jobdata = await JobApi.insertJobTicketBySop(sopJobData)
  if(Jobdata){
    ElMessage.success('作业创建并执行成功，可在作业管理列表页查看')
  }
  console.log(Jobdata,'新增是否成功')
}
// 构建岗位查找映射
const buildWorkstationMap = (list) => {
  const buildMap = (items) => {
    for (const item of items) {
      workstationMap.set(item.id, item.workstationName)
      if (item.children && item.children.length > 0) {
        buildMap(item.children)
      }
    }
  }
  buildMap(list)
}

// 构建工艺查找映射
const buildMachineryMap = (list) => {
  const buildMap = (items) => {
    for (const item of items) {
      machineryMap.set(item.id, item.machineryName || item.name)
      if (item.children && item.children.length > 0) {
        buildMap(item.children)
      }
    }
  }
  buildMap(list)
}
// 生成 Job 名称
const generateJobName = async () => {
  const workstationName = workstationMap.get(sopJobData.workstationId)
  const machineryName = machineryMap.get(sopJobData.machineryId)
  const typeName = getJobTypeName(sopJobData.ticketType)
  const currentDate = new Date().toISOString().split('T')[0]

  if (!workstationName || !machineryName || !typeName) {
    console.warn('字段未准备好:', { workstationName, machineryName, typeName })
    return
  }

  const name = `${workstationName}-${machineryName}-${typeName}-${currentDate}`
  console.log('最终 name:', name)
  const nameNew = await JobApi.autoGenerateName(name)
  sopJobData.ticketName = nameNew
}

const getjobData = async () => {
  // 获取岗位数据
  const deptRes = await MarsDeptApi.listMarsDept({ pageNo: 1, pageSize: -1 })
  buildWorkstationMap(deptRes.list)
  // 获取设备/工艺数据
  const techRes = await TechnologyApi.listTechnology({ pageNo: 1, pageSize: -1 })
  const data = techRes.list.filter((item) => item.machineryType == '工艺')
  buildMachineryMap(data)
}

// 获取 Job 类型名称
const getJobTypeName = (ticketType) => {
  const JobTypeOptions = getStrDictOptions(DICT_TYPE.TICKET_TYPE)
  const typeOption = JobTypeOptions.find((option) => option.value === ticketType)
  return typeOption ? typeOption.label : '未知类型'
}
/** 初始化 **/
const isMounted = ref(false)
onMounted(async () => {
  await getList()
  // 数据加载完成后
  isInitialized.value = true
  // 设置change函数初始化结束 才会触发change函数
  isMounted.value = true
  getjobData()
})
</script>
<style scoped></style>
