<script setup>
import { getCurrentInstance, onMounted, ref , computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import OrganizationalWithLeafUserOne from '@/components/OrganizationalWithLeafUserOne.vue';
const {
  proxy
} = getCurrentInstance()

let title = '新增通知公告'

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

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');

const result=ref('')
const fromVue=ref({})
if (route.query.mark) {
  planInfo = JSON.parse(route.query.mark)
}
console.log(planInfo);
if (planInfo==-1){
  result.value=guid()
  console.log( result.value);
}

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 showRule=ref(false);
const leaderKey = guid()
const distestType=ref(false)
const selectedUsers=ref([])
const createDeptUsers = (row) => {
  if (row.perName) {
    // 重置
    selectedUsers.value = [];

    const codes = row.perCode.split(',');
    const names = row.perName.split(',');

    // 确保两个数组长度一致（防止错位）
    const len = Math.min(codes.length, names.length);

    for (let i = 0; i < len; i++) {
      selectedUsers.value.push({
        userCode: codes[i].trim(),   // 去除可能的空格
        userDesc: names[i].trim()
      });
    }

    // 存入 sessionStorage
    sessionStorage.setItem(leaderKey, JSON.stringify(selectedUsers.value));
  }
};
const isshow=ref(false)
if (planInfo==1) {
  console.log(planInfo);
  title = '修改通知公告'
  fromVue.value= JSON.parse(route.query.data)
  createDeptUsers(fromVue.value);
  result.value=fromVue.value.fileId
  if (fromVue.value.ifAll=="否"){
    isshow.value=true
  }
  console.log(result.value);
}
 const  whether=ref(false)

const planLevelList1=ref([])


/* 下拉框 */
const showActionSheet = ref(false)
const showActionSheet1 = ref(false)
const planLevelList = [
  { name: '是', value: '是' },
  { name: '否', value: '否' },
];

const isdisabled2=ref(true)
const onSelect = (item) => {
fromVue.value.ifAll = item.name
  if (fromVue.value.ifAll=="否"){
    isshow.value=true
  }
  showActionSheet.value=false
}

const onSelect2 = (item) => {
  fromVue.value.fileType=item.name
  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 questionIds = ref([])
const actions=ref([])
/*const getQuestionId = () => {
  var url = '/sgsafe/AssessmentRecord/queryRuleNoPage';
  var param = {};
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      questionIds.value = response.data.data; // 先赋值给 questionIds.value


      // ✅ 关键：使用 questionIds.value.map
      actions.value = questionIds.value.map(item => ({
        name: item.ruleName,
        value: item.id
      }));
      console.log('actions:', actions.value); // 看看有没有输出
    } else {
      ElMessage.error('操作失败！' + response.data.msg);
    }
  });
};
getQuestionId()*/

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

      var url = '/sgsafe/Notice/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/Notice/save';
  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 showDatePicker1 = ref(false)
const onDatePicker = (value) => {
  const dateArr = value.selectedValues
  fromVue.value.startTime = dateArr[0] + '-' + dateArr[1] + '-' + dateArr[2]
  showDatePicker.value = false
}
const onDatePicker1 = (value) => {
  const dateArr = value.selectedValues
  fromVue.value.endTime = dateArr[0] + '-' + dateArr[1] + '-' + dateArr[2]
  showDatePicker1.value = false
}
const currentDate1 = ref([2025, 7, 25])
const currentDate = ref([2025, 7, 25])
//定义字典集合
const dicList = ref([])
//获取字典集合
import tools from '@/tools'
const getDicList = () => {
  tools.dic.getDicList(['systemTypes']).then((response => {

   const rawData = response.data.data
    dicList.value = rawData.systemTypes.map(item => ({
      name: item.dicName,      // 必须有 name 字段！
      code: item.dicCode       // 可选，保留原始 code 供后续使用
    }));
    console.log(JSON.stringify(dicList.value))
  }))
}
onMounted(() => {
  const today = new Date()
  const year = today.getFullYear()
  const month = today.getMonth() + 1 // 月份从 0 开始
  const day = today.getDate()
  currentDate.value = [year, month, day]
  currentDate1.value = [year, month, day]
  //selectedDateText.value = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`
  getDicList()
})
const showActionSheet2=ref(false)
/* 文件上传 */
import AttachmentS3 from '@/components/AttachmentS3.vue';
import OrganizationalWithLeafUser from '@/components/OrganizationalWithLeafUser.vue';

const onSubmit = (values) => {
  addEmergencyDrillPlan()
}
const leaderKeyysr = guid();
const PopupDepartmentperNameRefysr = ref();
const handleDepartmentperNameysr = () => {
  PopupDepartmentperNameRefysr.value.open();
};
const getDepartmentperNameysr = (item) => {
  fromVue.value.punCode = item.user.userCode;
  fromVue.value.punName = item.user.userDesc;
  fromVue.value.punId = item.user.id
};



const selectedUser = {
  userCode: '',
  userDesc: ''
};
const codeList = ref([])
const nameList = ref([])


const clearDeptUsers = () => {
  if (sessionStorage.getItem(leaderKey)) {
    sessionStorage.removeItem(leaderKey);
  }
};

/**
 * 选择人员
 */
const PopupDepartmentJoinPersonRef = ref();
const handleDepartmentJoinPerson = () => {
  PopupDepartmentJoinPersonRef.value.open();
};
const getDepartmentJoinPerson = (userArray) => {
  const codes = userArray.map(item => item.userCode).join(',');
  const descs = userArray.map(item => item.userDesc).join(',');
  console.log(codes);
  fromVue.value.perName=descs;
  fromVue.value.perCode=codes;
};
</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
          v-model="fromVue.processInstanceId"
          label="公告标题"
          name="fileSubmit"
          required
          placeholder="请输入公告标题"
          :rules="[{required: true, message: '请输入公告标题'}]"
        />

        <van-field
          v-model="fromVue.tContent"
          label="公告内容"
          name="tContent"
          required
          placeholder="请输入公告内容"
          type="textarea"
          rows="5"
        autosize
        show-word-limit
        maxlength="300"
        :rules="[{ required: true, message: '请输入公告内容' }]"
        />
        <van-field
          v-model="fromVue.startTime"
          readonly
          label="开始时间"
          name="startTime"
          required
          placeholder="请选择开始时间"
          :rules="[{required: true, message: '请输入开始时间'}]"
          @click="showDatePicker = true"
        />
        <van-field
          v-model="fromVue.endTime"
          readonly
          label="结束时间"
          name="endTime"
          required
          placeholder="请选择结束时间"
          :rules="[{required: true, message: '请输入结束时间'}]"
          @click="showDatePicker1 = true"
        />
        <van-field
          readonly
          v-model="fromVue.ifAll"
          label="是否全员发布"
          name="ifAll"
          @click="showActionSheet = true"
        />
        <van-field
          readonly
          v-show='isshow'
          v-model="fromVue.perName"
          label="参与人"
          name="perName"
          @click="handleDepartmentJoinPerson"
        />

        <OrganizationalWithLeafUser ref="PopupDepartmentJoinPersonRef" @receive-from-child="getDepartmentJoinPerson"
                                    :main-key="leaderKey" />
        <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="showActionSheet2"
        :actions="dicList"
        @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="showDatePicker1" position="bottom">
        <van-date-picker
          v-model="currentDate1"
          @confirm="onDatePicker1"
          @cancel="showDatePicker1 = false" />
      </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>
