import { toRaw } from 'vue'

/** 检查任务下发隐患工作流（对齐 Web sgexp） */
export const FLOW_ID_XF = 'copy_hazardImmediatelyCM'

export async function fetchTaskResultItems(axios, taskId, userId) {
  const param = {
    page: 1,
    rows: 5000,
    params: JSON.stringify({
      taskId,
      userId,
    }),
  }
  const response = await axios.get('sgsafe/CheckResultItem/query', param)
  if (response.data.code !== 0) {
    throw new Error(response.data.msg || '查询检查项失败')
  }
  return response.data.data.records || []
}

export function validateBatchXF(items) {
  const unfinished = items.filter((item) => !item.ifFlag || item.ifFlag === '')
  if (unfinished.length > 0) {
    return {
      ok: false,
      message: `还有 ${unfinished.length} 项未选择是否符合（请先在检查记录中填写并暂存），无法一键下发`,
    }
  }
  const notSavedNo = items.filter((item) => item.ifFlag === '否' && item.state === '未知')
  if (notSavedNo.length > 0) {
    return {
      ok: false,
      message: `有 ${notSavedNo.length} 条不符合项未暂存，请先保存后再一键下发`,
    }
  }
  const pending = items.filter((item) => item.ifFlag === '否' && item.state === '待下发')
  if (pending.length === 0) {
    return {
      ok: false,
      message: '没有待下发的不符合项',
    }
  }
  return { ok: true, pending }
}

export async function resolveHdConfirmVar(axios, hdConfirmUserCode) {
  const r = await axios.post('sgsafe/Hiddendanger/qqId', { params: hdConfirmUserCode })
  if (r.data.code === 0 && r.data.data) {
    return 'U_' + String(r.data.data).trim()
  }
  return ''
}

export async function dispatchSingleXF(
  axios,
  workflowSubmit,
  item,
  hdConfirmUserCode,
  hdConfirmUserDesc,
  hdConfirmVar,
) {
  const submitData = {
    ...item,
    hdConfirm: hdConfirmUserCode,
    hdConfirmDesc: hdConfirmUserDesc,
  }
  const response = await axios.post('sgsafe/CheckResultItem/saveXF', {
    json: JSON.stringify(submitData),
  })
  if (response.data.code !== 0) {
    throw new Error(response.data.msg || '下发失败')
  }
  const hiddendangerId = response.data.data?.hiddendangerId
  if (!hiddendangerId) {
    throw new Error('未获取到隐患id')
  }
  const variables = { id: hiddendangerId, hdConfirm: hdConfirmVar }
  const result = await workflowSubmit(
    FLOW_ID_XF,
    '隐患排查治理',
    '初始化提交',
    JSON.stringify(toRaw(variables)),
    undefined,
    undefined,
  )
  if (result.status !== 'success') {
    throw new Error(result.msg || '提交审批失败')
  }
  await axios.post('sgsafe/Hiddendanger/saveProcessInfo', {
    json: JSON.stringify({
      id: hiddendangerId,
      workId: result.workId,
      trackId: result.trackId,
    }),
  })
}
