<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" fixed />
      <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="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)"
            @click="openForm('executPlan', scope.row.id,scope.row.sopName)"
          />
        </template>
      </el-table-column>
      <el-table-column label="下次作业开始时间" prop="nextExecutDate" width="150" />
      <!--      <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="sop内容" prop="sopContent"  />-->
      <!--      <el-table-column label="sop状态" prop="sopStatus"  align="center" />-->
      <!--      <el-table-column label="sop权重序号" prop="sopIndex" />-->
      <!--      <el-table-column label="备注" prop="remark"  align="center" />-->
      <el-table-column label="操作" align="center" width="550" fixed="right">
        <template #default="{ row }">
          <el-button
            link
            :icon="Promotion"
            type="danger"
            @click="openForm('update', row.id)"
            v-hasPermi="['iscs:sop:update']"
          >
            立即执行
          </el-button>
          <el-button
            link
            :icon="Bell"
            type="primary"
            @click="openForm('update', row.id)"
            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('update', row.id)"
            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>
</template>

<script lang="ts" setup>
import * as SopApi from '@/api/sop'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import {Promotion, DocumentChecked,Delete, Edit, Bell,RefreshLeft } from '@element-plus/icons-vue'
import {updateSopEnableExecutionPlan, updateSopEnableNotification} from "@/api/sop";
// 添加初始化标志位
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 handleNotificationsChange = async (row, val) => {
  if (!isInitialized.value) return

  const originalValue = row.enableNotifications

  try {
    // const data = {
    //   ...row,
    //   enableNotifications: val
    // }
    const data = {
      id: row.id,
      enableNotifications: val
    }
    console.log(data,'是什么数据')
    await SopApi.updateSopEnableNotification(data)
    ElMessage.success(val == 1 ? '已开启' : '已关闭')

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

    // 强制刷新 UI
    await nextTick()

    // 提示错误
    // ElMessage.error('状态更新失败，请重试')
  }
}
// 是否打开执行计划
const handleExecutionPlanChange = async (row, val) => {
  if (!isInitialized.value) return

  const originalValue = row.enableExecutionPlan

  try {
    const data = {
     id:row.id,
      enableExecutionPlan: val
    }

    await SopApi.updateSopEnableExecutionPlan(data)
    ElMessage.success(val == 1 ? '已开启' : '已关闭')

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

    // 强制刷新 UI
    await nextTick()

    // 提示错误
    // ElMessage.error('状态更新失败，请重试')
  }
}

/** 多选框选中数据 */

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) => {
  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'
      }
    })
  }
}

/** 删除按钮操作 */
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 {}
}

/** 初始化 **/
onMounted(async () => {
  await getList()
  // 数据加载完成后
  isInitialized.value = true
})
</script>
<style scoped></style>
