<template>
  <ContentWrap>
    <!--    顶部标题-->
    <div class="topTitle">
      <span class="tab-title">执行计划：{{ route.query.sopName }}</span>
      <div class="set-btn" @click="goBack">
        <img src="../../../assets/images/返回.png" alt="" />
        返回
      </div>
    </div>
  </ContentWrap>

  <ContentWrap>
    <div class="tab-header">
      <span class="tab-title">通知设置</span>
    </div>
    <div class="noticeContent">
      <p
        >启用通知：
        <el-switch
          v-model="enableNotifications"
          size="small"
          :active-value="1"
          :inactive-value="0"
          @update:modelValue="(val) => handleNotificationsChange(enableNotifications, val)"
        />
      </p>
      <section class="noticebtn">
        <el-button
          type="primary"
          plain
          @click="openForm({ type: '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>
      </section>
      <el-table
        v-loading="loading"
        border
        :data="noticeList"
        @selection-change="handleSelectionChange"
        style="width: 100%"
      >
        <el-table-column type="selection" width="50" align="center" fixed />
        <el-table-column label="规则" prop="ruleLabel" align="center" width="200" />
        <el-table-column label="通知规则种类" prop="typeLabel" align="center" width="200" />
        <el-table-column label="通知时间" prop="notifyTimeDisplay" align="center" width="200" />
        <el-table-column label="通知角色与通知模板" align="center" min-width="500">
          <template #default="scope">
            <div v-html="scope.row.roleTemplateSummary" ></div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              link
              :icon="Edit"
              type="primary"
              @click="openForm({ type: 'update', rowId: row.id })"
              v-hasPermi="['iscs:sop:update']"
            >
              修改
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </ContentWrap>
</template>

<script setup lang="ts">
import { Edit } from '@element-plus/icons-vue'
import * as SopApi from '@/api/sop'
import * as NotificationRules from '@/api/sop/notificationRules'
import { getStrDictOptions } from '@/utils/dict'
import {deleteNotifyConfigList, getNotifyConfigPage} from "@/api/sop/notificationRules";

const router = useRouter()
const route = useRoute()
const message = useMessage() // 消息弹窗
const NotificationStatus = ref('')
const ids = ref<number[]>([]) // 选中的数据
const { t } = useI18n() // 国际化
const multiple = ref(true) // 非多个禁用
const noticeList=ref([])
const loading = ref(false) // 列表的加载中
const notifyParams=reactive({
  pageNo: 1,
  pageSize: -1,
  sopId:route.query.id
})
const enableNotifications = ref(0) // 默认显示启用的
const actionNoticeList=ref([])
// 添加初始化标志位
const isInitialized = ref(false)

// const filteredTableData = computed(() => {
//   return noticeList.value.filter(item => item.status == status.value)
// })

onMounted(async ()=>{
  // 数据加载完成后
  isInitialized.value = true
  await getNotifyData()
  await getActionNoticeData()
  const data=await SopApi.selectSopById(route.query.id)
  enableNotifications.value = data.enableNotifications
  console.log('noticeList:', noticeList.value)

})

// 返回
const goBack = () => {
  router.push('/sopm/sop')
}
// 接口获取最后一种数据下拉
const getActionNoticeData = async () => {
  try {
    const actionNoticesList = await NotificationRules.getSopWorkflowStepList(route.query.id)
    actionNoticeList.value = actionNoticesList

    // 将接口返回的数据添加到 dictMap.rule 中
    const dynamicOptions = actionNoticesList.map(item => ({
      label: item.stepTitleShort,
      value: Number(item.id) // 确保 value 是 number 类型
    }))

    dictMap.rule = dictMap.rule.concat(dynamicOptions)

    console.log(dictMap.rule, '更新后的dictMap.rule')
  } catch (err) {
    console.error('获取工作流程步骤失败', err)
  }
}


// 字典缓存映射（建议提前加载到内存里以避免多次调用）
const dictMap = {
  rule: getStrDictOptions(DICT_TYPE.JOB_NOTICE_RULES)
    .concat(getStrDictOptions(DICT_TYPE.ADVANCE_NOTICE_RULES))
    .concat(getStrDictOptions(DICT_TYPE.ACTION_NOTICE_RULES)),
  type: getStrDictOptions(DICT_TYPE.NOTICE_RULES_TYPE),
  notifyTimeType: getStrDictOptions(DICT_TYPE.NOTICE_TIME_TYPE)
}

// 辅助方法：通过字典值查找 label
const getDictLabel = (dict, value) => {
  const match = dict.find(item => item.value == value)
  return match ? match.label : value
}

// 表格数据显示处理
const getNotifyData = async () => {
  try {
    const { list = [] } = await NotificationRules.getNotifyConfigPage(notifyParams)

    const processedList = list.map(item => {
      const notifyTimeTypeLabel = getDictLabel(dictMap.notifyTimeType, item.notifyTimeType)
      let notifyTimeDisplay = notifyTimeTypeLabel

      if (item.notifyTimeType == 0 || item.notifyTimeType == 2) {
        // 转换为分钟展示
        const minutes = Math.floor(item.notifyTime / 60)
        notifyTimeDisplay += `（${minutes}分钟）`
      }

      // ✅ 通知角色与模板显示拼接（status === 1 且一行一个）
      // const detailDisplay = (item.notifyConfigDetailRespVOList || [])
      //   .filter(d => d.status == 1)
      //   .map(d => {
      //     let role = d.roleName
      //     if (d.isClient == 1) {
      //       role += '（当事人）'
      //     }
      //     return `${role}：${d.notifyTemplateName || '-'}`
      //   })
      //   .join('<br/>')  // ✅ 多行显示，用 <br/> 拼接

      const detailDisplay = (item.notifyConfigDetailRespVOList || [])
        .filter(d => d.status == 1) // 过滤当事人
        .map(d => {
          // const role = `${d.roleName || '未知角色'}（当事人）`; // 这里就直接拼接了
          // return `${role}：${d.notifyTemplateName || '-'}`;
          let role;
          if (d.isClient == 1) {
            role = `${d.roleName || '未知角色'}（当事人）`;
          } else {
            role = `${d.roleName || '未知角色'}`;
          }
          return `${role}：${d.notifyTemplateName || '-'}`;
        })
        .join('<br/>');

      return {
        ...item,
        ruleLabel: getDictLabel(dictMap.rule, item.rule),
        typeLabel: getDictLabel(dictMap.type, item.type),
        notifyTimeDisplay,
        roleTemplateSummary: detailDisplay
      }
    })

    noticeList.value = processedList
    // 把字符串形式的 rule 转换为数字
    // noticeList.value.rule = Number(noticeList.value.rule)
    console.log('规则数据:', processedList)
  } catch (err) {
    console.error('获取通知规则失败', err)
  }
}

// 是否开启通知
const handleNotificationsChange = async (enableNotifications, val) => {
  if (!isInitialized.value) return

  const originalValue = enableNotifications.value

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

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

    // 强制刷新 UI
    await nextTick()

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

/** 添加/修改/查看操作 */
const openForm = ({type, id, rowId, workstationId,}: { type: string
  id?: number
  rowId?: number
  workstationId?: number
}) => {
  if (type == 'create') {
    router.push({
      name: 'NotificationUpdate',
      query: {
        id: route.query.id,
        workstationId: route.query.workstationId,
        type: 'create',
      },
    })
  } else if (type == 'update') {
    router.push({
      name: 'NotificationUpdate',
      query: {
        type: 'update',
        rowId,
        id: route.query.id,
        workstationId: route.query.workstationId,
      },
    })
  }
}


const handleDelete = async () => {
  const deleteIds =ids.value
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await NotificationRules.deleteNotifyConfigList(deleteIds)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getNotifyData()
  } catch {}
  console.log('删除功能')
}

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

<style scoped lang="scss">
.topTitle {
  width: 100%;
  line-height: 40px;
}

.set-btn {
  width: 60px;
  height: 30px;
  border: 1px solid black;
  border-radius: 6px;
  text-align: center;
  line-height: 30px;
  float: right;
  cursor: pointer;
  margin: 10px 0;

  img {
    width: 14px;
    height: 14px;
  }
}

.tab-header {
  background-color: #f5f7fa;
  border-bottom: 1px solid #dcdfe6;
  padding: 12px 20px;
  border-radius: 4px 4px 0 0;
}

.noticeContent {
  width: 100%;
  height: 100%;
  padding: 10px 30px;
  //background: blue;
  .noticebtn {
    width: 100%;
    line-height: 60px;
    margin: 10px 0;
    //background: green;
  }
}
</style>
