<script setup>
import { getCurrentInstance, onMounted, ref , computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';

const {
  proxy
} = getCurrentInstance()

let title = '考试任务'

/* 返回上一级页面 */
const router = useRouter()
const onClickLeft = () => {
  router.go(-1)
}

const currentYear = ref()
currentYear.value = new Date().getFullYear()

/* 获取用户部门信息 */
const jsonArray = localStorage.getItem('dept')
const deptInformation = ref([])
try {
  deptInformation.value = jsonArray ? JSON.parse(jsonArray) : [];
} catch (error) {
  deptInformation.value = [];
}
const deptName = deptInformation.value[0].deptName
const deptCode = deptInformation.value[0].deptCode

const guid = () =>  {
  function S4() {
    return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
  }
  return (S4()+S4()+S4()+S4()+S4()+S4()+S4()+S4())
}
const formJieguo = ref({
  resultWhether:'',
  resultDetail:'',
  resultWhy:'',
  resultFile:'',
  itemsId:'',
  resultFileId:'',
  resType:''
})
const route = useRoute()
let planInfo = {}
const  userName1=localStorage.getItem('userName');
if (route.query.mark) {
  planInfo = JSON.parse(route.query.mark)
}
console.log(planInfo);

const result=ref('')
const fromVue=ref({})

const resDetail=ref('')
const ruleIds = ref([]);
const getRuleId = () => {
  var url = '/sgsafe/ExamHead/getCheckRuleId'
  var param = {}
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      ruleIds.value = response.data.data
    } else {
      console.log("1111111");
    }
  })
  console.log('ruleIds', ruleIds)
}
getRuleId()

const selectedRuleName = computed(() => {
  const rule = ruleIds.value.find(item => item.id === fromVue.value.testRole);
  return rule ? rule.name : '';
});
const distestType=ref(false)
if (planInfo==1) {
  console.log(planInfo);
  title = '修改考试任务'
  fromVue.value= JSON.parse(route.query.data)
  console.log(fromVue.value);
  distestType.value=true
}
 const  whether=ref(false)

const planLevelList1=ref([])


/* 下拉框 */
const showActionSheet = ref(false)
const showActionSheet1 = ref(false)
const planLevelList = [
  { name: '相同试题', value: '相同试题' },
  { name: '不同试题', value: '不同试题' }

];
const isdisabled=ref(true)
const isdisabled2=ref(true)
const onSelect = (item) => {
fromVue.value.testRole = item.id
  showActionSheet.value=false
}
const onSelect2 = (item) => {
  fromVue.value.testType = item.value
  showActionSheet2.value=false
}
const displayFileName = ref('')
const onSelect1 = (item) => {
  console.log(item);
  formJieguo.value.resultFile = item.value
  result.value=formJieguo.value.resultFile
  displayFileName.value = item.name
  console.log(result.value);
  showActionSheet1.value = false
}

const baocun3 = (ruleFormRef) => {
  console.log(formJieguo.value)
  ruleFormRef.validate((valid, fields) => {
    if (valid) {

      var url = '/sgsafe/ItemsResult/save';
      var param = {
        json: JSON.stringify(formJieguo.value)
      };
      proxy.$axios.post(url, param).then(response => {
        if (response.data.code == '0') {
          getTableData1()
          ElMessage({
            message: '保存成功',
            type: 'success',
          })
          if (ruleFormRef.value) {
            ruleFormRef.value.resetFields();
          }
          dialogVisibletemplate.value=false
        } else {
          ElMessage.error('操作失败！' + response.data.msg)
        }

      })
    }
  })
}

/* 组织树选择 */
const showBottom = ref(false)
import OrganizationalWithLeaf from '@/components/OrganizationalWithLeaf.vue';
import { showFailToast, showLoadingToast, showSuccessToast } from 'vant';
const handleTableDataUserDeptUpdate = async (nodeData) => {
  formJieguo.value.drillDept = nodeData.deptCode + '-' + nodeData.deptName
  showBottom.value = false
}

const addEmergencyDrillPlan = async () => {
  const loadingToast = showLoadingToast({
    duration: 0,
    message: '加载中',
    forbidClick: true
  })

  var url = '/sgsafe/EduCheckMaster/save';
  fromVue.value.addDeptCode=deptCode
  const params = {
    json: JSON.stringify(fromVue.value)
  }
  proxy.$axios.post(url,params).then(res=>{
    if (res.data.code === 0) {
      loadingToast.close()
      showSuccessToast('保存成功')
      onClickLeft()

    } else {
      loadingToast.close()
      showFailToast('操作失败!' + res.data.msg)
    }
  })
}
const showDatePicker = ref(false)
const onDatePicker = (value) => {
  const dateArr = value.selectedValues
  fromVue.value.checkTime = dateArr[0] + '-' + dateArr[1] + '-' + dateArr[2]
  showDatePicker.value = false
}
const currentDate = ref([2025, 7, 25])

onMounted(() => {
  const today = new Date()
  const year = today.getFullYear()
  const month = today.getMonth() + 1 // 月份从 0 开始
  const day = today.getDate()
  currentDate.value = [year, month, day]
  //selectedDateText.value = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`
})
const showActionSheet2=ref(false)
/* 文件上传 */
import AttachmentS3 from '@/components/AttachmentS3.vue';

const onSubmit = (values) => {
  addEmergencyDrillPlan()
}


</script>

<template>

  <div class="page-container">
    <van-sticky class="header">
      <van-nav-bar
        :title="title"
        left-text="返回"
        left-arrow
        @click-left="onClickLeft" >
      </van-nav-bar>
    </van-sticky>
    <div class="scroll-container">
      <van-form @submit="onSubmit">
        <van-field
          readonly
          v-model="selectedRuleName"
          label="试卷规则"
          name="testRole"
          required
          placeholder="请选择试卷规则"
          :rules="[{required: true, message: '请选择试卷规则'}]"
          @click="showActionSheet = true"
        />
        <van-field
          v-model="fromVue.checkTime"
          readonly
          label="检查时间"
          name="checkTime"
          placeholder="请选择检查时间"
          @click="showDatePicker = true"
        />

        <van-field
          v-model="fromVue.testType"
          readonly
          label="试题类型"
          name="testType"
          :disabled="distestType"
          required
          placeholder="请输入履职内容"
          :rules="[{required: true, message: '请输入履职内容'}]"
          @click="showActionSheet2 = true"
        />
        <van-field
          v-model="fromVue.checkName"
          label="检查名称"
          name="checkName"
          required
          placeholder="请输入履职内容"
          :rules="[{required: true, message: '请输入履职内容'}]"
        />
        <div style="margin: 16px;">
          <van-button round block type="primary" native-type="submit">
            提交
          </van-button>
        </div>
      </van-form>

      <van-action-sheet
        v-model:show="showActionSheet"
        :actions="ruleIds"
        @select="onSelect"
      />
      <van-action-sheet
        v-model:show="showActionSheet2"
        :actions="planLevelList"
        @select="onSelect2"
      />

      <van-action-sheet
        v-model:show="showActionSheet1"
        :actions="planLevelList1"
        field-names="{ text: 'fileName', value: 'fileId' }"
        @select="onSelect1"
      />

      <van-popup v-model:show="showBottom" position="bottom" :style="{ height: '30%' }">
        <OrganizationalWithLeaf @update:selected-node="handleTableDataUserDeptUpdate" />
      </van-popup>
      <van-popup v-model:show="showDatePicker" position="bottom">
        <van-date-picker
          v-model="currentDate"
          @confirm="onDatePicker"
          @cancel="showDatePicker = false" />
      </van-popup>
    </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;
}

.header, .footer {
  /* 固定高度区域 */
  flex-shrink: 0; /* 防止被压缩 */
  background: #f5f5f5;
  padding: 12px;
}
.row-container {
  display: flex;
  justify-content: space-between; /* 关键：左右分布 */
  align-items: center;             /* 垂直居中 */

}

.cell-period-text {
  font-size: 14px;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;

}

.mini-btn {
  height: 22px;
  font-size: 12px;
  padding: 0 8px;
  min-width: 60px;                 /* 可选：保持按钮最小宽度一致 */
}
</style>
