<script setup>
import { getCurrentInstance, onMounted, ref } from 'vue';
import { onBeforeRouteLeave, useRouter } from 'vue-router';
import { showFailToast, showSuccessToast, showToast } from 'vant';

const { proxy } = getCurrentInstance()
/* 模拟生成UUID */
const guid = () => {
  const chars = '0123456789abcdefghijklmnopqrstuvwxyz'
  const length = chars.length
  const randomString = (len) => {
    const array = new Uint8Array(len)
    crypto.getRandomValues(array)
    return Array.from(array)
      .map(byte => chars[byte % length])
      .join('');
  }
  return `${randomString(8)}${randomString(8)}${randomString(8)}${randomString(8)}`;
}

const router = useRouter();
const formData = ref({});
const activityVisible = ref(false);
const equipmentVisible = ref(false);
onMounted(() => {
  const activityStr = sessionStorage.getItem('activityInfo');
  const equipmentStr = sessionStorage.getItem('equipmentInfo');
  const inspectionResult = sessionStorage.getItem('inspectionResult')
  console.log('inspectionResult', inspectionResult);

  if (activityStr) {
    formData.value = JSON.parse(activityStr);
    equipmentVisible.value = false
    activityVisible.value = true;
  }

  if (equipmentStr) {
    formData.value = JSON.parse(equipmentStr);
    activityVisible.value = false
    equipmentVisible.value = true;
  }

  if (inspectionResult) {
    if (formData.value.inspectionCycle !== '不定期') {
      formData.value.isChecked = '已排查';
    }
    sessionStorage.removeItem('inspectionResult');
  }
});

const returnInspectionCycle = (inspectionCycle) => {
  if (!inspectionCycle) return '';
  if (inspectionCycle === '不定期') return '不定期';
  return '每' + inspectionCycle + '一次';
};

const fieldValue = ref('')
const showPicker = ref(false);
const columns = [
  { text: '发现隐患', value: '发现隐患' },
  { text: '未发现隐患', value: '未发现隐患' }
];
const onConfirmActivities = async ({ selectedOptions }) => {
  fieldValue.value = selectedOptions[0].value;
  if (fieldValue.value === '发现隐患') {
    await handAdd()
  }
  if (fieldValue.value === '未发现隐患') {
    let url = '/sgsafe/ActivityRecords/save'
    if (activityVisible.value) {
      url = '/sgsafe/ActivityRecords/save'
    }
    if (equipmentVisible.value) {
      url = '/sgsafe/EquipmentRecords/save'
    }
    const param = {
      json: JSON.stringify({
        evaluationId: formData.value.evaluationId,
        inspectionResult: '未发现隐患'
      })
    }
    proxy.$axios.post(url, param).then(res => {
      if (res.data.code === 0) {
        showSuccessToast('新增排查记录成功！')
        if (formData.value.inspectionCycle !== '不定期') {
          formData.value.isChecked = '已排查';
        }
      } else {
        showFailToast('操作失败！' + res.data.msg)
      }
    })
  }
  showPicker.value = false
}

const form = ref({
  hdId: '',
  hdPicId: '',
  hdSelect: '即查即改',
  discoverer: '',
  discovererDesc: '',
  discovererDeptCode: '',
  discovererDept: ''
})
const handAdd = async () => {
  if (activityVisible.value) {
    sessionStorage.setItem('checklistInfo', JSON.stringify({
      evaluationId: formData.value.evaluationId,
      inspectionResult: '发现隐患',
      checklistType: 'activity'
    }))
  }
  if (equipmentVisible.value) {
    sessionStorage.setItem('checklistInfo', JSON.stringify({
      evaluationId: formData.value.evaluationId,
      inspectionResult: '发现隐患',
      checklistType: 'equipment'
    }))
  }

  //请求隐患编号
  if (form.value.hdSelect === '即查即改') {
    const url = 'sgsafe/Hiddendanger/getYhbhTemp';
    const param = {};
    await proxy.$axios.get(url, param).then(response => {
      if (response.data.code === 0) {
        form.value.hdId = response.data.data;
      } else {
        showToast({
          type: 'error',
          message: '操作失败！' + response.data.msg
        });
      }
    });
  }

  form.value.hdPicId = guid()
  form.value.discoverer = localStorage.getItem('userCode');
  form.value.discovererDesc = localStorage.getItem('userDesc');
  let tree = JSON.parse(localStorage.getItem('dept'));
  form.value.discovererDept = tree[0].deptName;
  form.value.discovererDeptCode = tree[0].deptCode;

  await router.push({
    path: '/yinhuan/registration_edit/index',
    query: {
      hdId: form.value.hdId,
      hdPicId: form.value.hdPicId,
      discoverer: form.value.discoverer,
      discovererDept: form.value.discovererDept,
      discovererDesc: form.value.discovererDesc,
      discovererDeptCode: form.value.discovererDeptCode
    }
  });
};

// 控制哪个面板是展开的
const activeNames = ref(['risk', 'steps', 'controlMeasures']);

onBeforeRouteLeave((to, from, next) => {
  if (to.path === '/yinhuan/riskChecklist') {
    sessionStorage.removeItem('activityInfo');
    sessionStorage.removeItem('equipmentInfo');
  }
  next();
});



</script>

<template>

  <div class="page-container">
    <van-sticky>
      <van-nav-bar title="风险隐患排查详情">
      </van-nav-bar>
    </van-sticky>
    <div class="scroll-container">
      <div v-if="activityVisible" class="hierarchical-data-view">
        <van-collapse v-model="activeNames">
          <van-collapse-item title="风险点" name="risk">
            <van-cell title="编号" :value="formData.numbering" class="indent-level-1" />
            <van-cell title="类型" :value="formData.activityType" class="indent-level-1" />
            <van-cell title="名称" :value="formData.activityName" class="indent-level-1" />
          </van-collapse-item>
        </van-collapse>

        <van-collapse v-model="activeNames">
          <van-collapse-item title="作业步骤" name="steps">
            <van-cell title="序号" :value="formData.serialNumber" class="indent-level-1" />
            <van-cell title="名称" :value="formData.jobSteps" class="indent-level-1" />
          </van-collapse-item>
        </van-collapse>

        <van-cell-group>
          <van-cell title="危险源或潜在事件" :value="formData.hazardSources" />
        </van-cell-group>

        <van-cell-group>
          <van-cell title="评价级别" :value="formData.evaluationLevel" />
        </van-cell-group>

        <van-cell-group>
          <van-cell title="风险分级" :value="formData.riskGrading" />
        </van-cell-group>

        <van-cell-group>
          <van-cell title="可能发生的事故类型及后果" :value="formData.possibleAccidentType" />
        </van-cell-group>

        <van-collapse v-model="activeNames">
          <van-collapse-item title="管控措施" name="controlMeasures">
            <van-cell title="工程技术措施" :value="formData.engineeringAndTechnical" class="indent-level-1" />
            <van-cell title="管理措施" :value="formData.management" class="indent-level-1" />
            <van-cell title="培训教育措施" :value="formData.trainingAndEducation" class="indent-level-1" />
            <van-cell title="个体防护措施" :value="formData.personalProtective" class="indent-level-1" />
            <van-cell title="应急处置措施" :value="formData.emergencyResponse" class="indent-level-1" />
          </van-collapse-item>
        </van-collapse>

        <van-cell-group>
          <van-cell title="管控层级" :value="formData.controlLevel" />
        </van-cell-group>

        <van-cell-group>
          <van-cell title="责任单位" :value="formData.responsibleUnitName" />
        </van-cell-group>

        <van-cell-group>
          <van-cell title="责任人" :value="formData.responsiblePersonName" />
        </van-cell-group>

        <van-cell-group>
          <van-cell title="排查周期">
            <template #value>
              {{ returnInspectionCycle(formData.inspectionCycle) }}
            </template>
          </van-cell>
        </van-cell-group>

        <van-cell-group v-if="formData.isChecked === '未排查' || formData.inspectionCycle === '不定期' ">
          <van-field
            v-model="fieldValue"
            is-link
            readonly
            label="排查登记"
            placeholder="选择排查"
            @click="showPicker = true"
          />
        </van-cell-group>

        <van-popup v-model:show="showPicker" round position="bottom">
          <van-picker
            :columns="columns"
            @cancel="showPicker = false"
            @confirm="onConfirmActivities"
          />
        </van-popup>

        <van-cell-group v-if="formData.inspectionCycle !== '不定期'">
          <van-cell title="排查结果">
            <template #value>
              <van-tag v-if="formData.isChecked === '已排查'" type="success">已排查</van-tag>
              <van-tag v-else type="danger">未排查</van-tag>
            </template>
          </van-cell>
        </van-cell-group>
      </div>

      <div v-if="equipmentVisible" class="hierarchical-data-view">
        <van-collapse v-model="activeNames">
          <van-collapse-item title="风险点" name="risk">
            <van-cell title="类型" :value="formData.riskPointsType" class="indent-level-1" />
            <van-cell title="名称" :value="formData.riskPointsName" class="indent-level-1" />
          </van-collapse-item>
        </van-collapse>

        <van-collapse v-model="activeNames">
          <van-collapse-item title="检查项目" name="steps">
            <van-cell title="序号" :value="formData.serialNumber" class="indent-level-1" />
            <van-cell title="名称" :value="formData.inspectItem" class="indent-level-1" />
          </van-collapse-item>
        </van-collapse>

        <van-cell-group>
          <van-cell title="标准" :value="formData.standard" />
        </van-cell-group>

        <van-cell-group>
          <van-cell title="评价级别" :value="formData.evaluationLevel" />
        </van-cell-group>

        <van-cell-group>
          <van-cell title="风险分级" :value="formData.riskGrading" />
        </van-cell-group>

        <van-cell-group>
          <van-cell title="不符合标准情况及后果" :value="formData.consequences" />
        </van-cell-group>

        <van-collapse v-model="activeNames">
          <van-collapse-item title="管控措施" name="controlMeasures">
            <van-cell title="工程技术措施" :value="formData.engineeringAndTechnical" class="indent-level-1" />
            <van-cell title="管理措施" :value="formData.management" class="indent-level-1" />
            <van-cell title="培训教育措施" :value="formData.trainingAndEducation" class="indent-level-1" />
            <van-cell title="个体防护措施" :value="formData.personalProtective" class="indent-level-1" />
            <van-cell title="应急处置措施" :value="formData.emergencyResponse" class="indent-level-1" />
          </van-collapse-item>
        </van-collapse>

        <van-cell-group>
          <van-cell title="管控层级" :value="formData.controlLevel" />
        </van-cell-group>

        <van-cell-group>
          <van-cell title="责任单位" :value="formData.responsibleUnitName" />
        </van-cell-group>

        <van-cell-group>
          <van-cell title="责任人" :value="formData.responsiblePersonName" />
        </van-cell-group>

        <van-cell-group>
          <van-cell title="排查周期">
            <template #value>
              {{ returnInspectionCycle(formData.inspectionCycle) }}
            </template>
          </van-cell>
        </van-cell-group>

        <van-cell-group v-if="formData.isChecked === '未排查' || formData.inspectionCycle === '不定期' ">
          <van-field
            v-model="fieldValue"
            is-link
            readonly
            label="排查登记"
            placeholder="选择排查"
            @click="showPicker = true"
          />
        </van-cell-group>

        <van-popup v-model:show="showPicker" round position="bottom">
          <van-picker
            :columns="columns"
            @cancel="showPicker = false"
            @confirm="onConfirmActivities"
          />
        </van-popup>

        <van-cell-group v-if="formData.inspectionCycle !== '不定期'">
          <van-cell title="排查结果">
            <template #value>
              <van-tag v-if="formData.isChecked === '已排查'" type="success">已排查</van-tag>
              <van-tag v-else type="danger">未排查</van-tag>
            </template>
          </van-cell>
        </van-cell-group>
      </div>
    </div>
  </div>
</template>

<style scoped>
.page-container {
  height: 100vh; /* 关键：外层容器高度设为视口高度 */
  display: flex;
  flex-direction: column;
}

/*  overflow-y: auto; !* 启用垂直滚动 *!*/


.scroll-container {
  flex: 1;
  overflow: auto;
  -webkit-overflow-scrolling: touch; /* iOS 平滑滚动 */
}

/* 可选：隐藏滚动条（视觉优化） */
.scroll-container::-webkit-scrollbar {
  display: none;
}

.hierarchical-data-view {
  padding: 12px;
}

/* 为子层级添加缩进 */
.indent-level-1 {
  margin-left: 20px; /* 根据实际视觉效果调整缩进量 */
}

/* 可选：为 CellGroups 或 Collapse 添加一些底部外边距，增加空间感 */
.van-cell-group, .van-collapse {
  margin-bottom: 10px;
}

</style>
