<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.data) {
  planInfo = JSON.parse(route.query.data)
}
const getFieData = () => {
  var url = '/sgsafe/ResponFile/queryFileName'
  var param = {
    params: userName1
  }
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      const rawData = response.data.data;
      planLevelList1.value = rawData.map(file => ({
        name: file.fileName,
        value: file.fileId
      }));

     if(formJieguo.value.resultFileId !='' ||formJieguo.value != null){
       const resultFileId = formJieguo.value.resultFileId;

       // 遍历 planLevelList1 查找匹配项
       for (const item of planLevelList1.value) {
         if (item.value === resultFileId) {
           displayFileName.value = item.name;
           break; // 找到后跳出循环
         }
       }
     }
     // displayFileName.value = planLevelList1.value[0].name
      console.log(planLevelList1.value)
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }

  })

}

const result=ref('')

const resDetail=ref('')
resDetail.value=route.query.resDetail
if (Object.keys(planInfo).length > 0) {
  console.log(planInfo);
  title = '修改我的履职记录'
  formJieguo.value = {
    id:planInfo.id,
    resultWhether:planInfo.resultWhether,
    resultDetail:planInfo.resultDetail,
    resultWhy:planInfo.resultWhy,
    resultFile:planInfo.resultFile,
    itemsId:planInfo.itemsId,
    resultFileId:planInfo.resultFileId,
    resType:planInfo.resType,
  }

  result.value=planInfo.resultFileId
  console.log(result.value);
}else {

  formJieguo.value={
    itemsId: route.query.itemsId
  }
  result.value=route.query.result
  console.log(result.value);
}
 const  whether=ref(false)
if (route.query.fileWhether=='1') {
  // 要上传文件
  whether.value=true
  getFieData()
}
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) => {
  formJieguo.value.resultWhether = item.name
  showActionSheet.value = false
  if (formJieguo.value.resultWhether=='已履职'){
    formJieguo.value.resultWhy=''
    isdisabled.value=false;
    isdisabled2.value=true;
  }else {
    isdisabled2.value=false;
    isdisabled.value=true;
    formJieguo.value.resultDetail=''

  }

}
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) {
      formJieguo.value.resultFileId=result.value
      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
  })
  formJieguo.value.resultFileId=result.value
  var url = '/sgsafe/ItemsResult/save';
  const params = {
    json: JSON.stringify(formJieguo.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
  formJieguo.value.addTime = 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')}`
})

/* 文件上传 */
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="resDetail"
          label="待履职项"
          name="planName"
          :disabled='true'
        />
        <van-field
          readonly
          v-model="formJieguo.resultWhether"
          label="履职情况"
          name="planLevel"
          required
          placeholder="请选择履职情况"
          :rules="[{required: true, message: '请输入履职情况'}]"
          @click="showActionSheet = true"
        />
        <van-field
          v-model="formJieguo.addTime"
          readonly
          label="履职时间"
          name="addTime"
          required
          placeholder="请选择履职时间"
          :rules="[{required: true, message: '请输入履职时间'}]"
          @click="showDatePicker = true"
        />

        <van-field
          v-model="formJieguo.resultDetail"
          label="履职内容"
          name="planName"
          :disabled='isdisabled'
          placeholder="请输入履职内容"

        />
        <van-field
          v-show='whether'
          readonly
          v-model="displayFileName"
          label="选择文件"
          name="planLevel"

          placeholder="请选择文件"

          @click="showActionSheet1 = true"
        />
        <van-field
          v-model="formJieguo.resultWhy"
          label="未履职原因"
          name="planName"
          :disabled='isdisabled2'
          placeholder="如若履职勿填！！"

        />
        <van-field label="附件上传" v-if="whether">
          <template #input>
            <AttachmentS3 :f-id="result" />
          </template>
        </van-field>

        <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="planLevelList"
        @select="onSelect"
      />

      <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"
          :min-date="minDate"
          :max-date="maxDate"
          @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>
