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

const {
  proxy
} = getCurrentInstance()
const accidentDictList = ref([])
const columns =  ref([])
const columnsLevel =  ref([])
const columnsprimary=ref([])

//     [
//   { text: '杭州', value: 'Hangzhou' },
//   { text: '宁波', value: 'Ningbo' },
//   { text: '温州', value: 'Wenzhou' },
//   { text: '绍兴', value: 'Shaoxing' },
//   { text: '湖州', value: 'Huzhou' },
// ];

// 定义生成编号的函数（你已写好的逻辑）

const generateCode = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const formattedDate = `${year}${month}${day}`;
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');
  const formattedTime = `${hours}${minutes}${seconds}`;
  const sequenceNumber = Math.floor(Math.random() * 1000);
  const paddedSequence = String(sequenceNumber).padStart(3, '0');
  return `SGAL${formattedDate}${formattedTime}${paddedSequence}`;
};

// 存储生成的编号（响应式变量）
const generatedCode = ref('');

// 重新生成编号的方法
const regenerateCode = () => {
  generatedCode.value = generateCode();
};



const getAccidentDicList = () => {
  tools.dic.getDicList([ 'case_type','sgsafe_culture_case_type', 'case_source','primary_domain','primary_domain_two','accident_level','accident_type','sgsafe_taccidentTags','sgsafe_culture_activity_type']).then((response => {
    console.log(JSON.stringify(response.data.data))
    accidentDictList.value = response.data.data
    console.log('case_source',accidentDictList.value.case_source)
    columns.value = accidentDictList.value.sgsafe_culture_case_type.map(item => ({
      text: item.dicName,
      value: item.dicCode
    }));
    columnsLevel.value = accidentDictList.value.sgsafe_culture_activity_type.map(item => ({
      text: item.dicName,
      value: item.dicCode
    }));
    columnsprimary.value = accidentDictList.value.primary_domain.map(item => ({
      text: item.dicName,
      value: item.dicCode
    }));


    console.log('accident_level',accidentDictList.value.accident_level)

  }))
}


const caseSourceFlag = ref(false)
const accidentLevelFlag = ref(false)
const primaryDomainFlag = ref(false)
const primaryDomainTwoFlag = ref(false)
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');
const isEdit = ref(route.query.mark === '1');

const result1=ref('')
const result2=ref('')
const result3=ref('')
const result4=ref('')
const result5=ref('')
const fromVue=ref({})
if (route.query.mark) {
  planInfo = JSON.parse(route.query.mark)
}
console.log(planInfo);
if (planInfo==-1){
  result1.value=guid()
  result2.value=guid()
  result3.value=guid()
  result4.value=guid()
  result5.value=guid()
  generatedCode.value = generateCode();

}

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 showSmit=ref(true);
const distestType=ref(false)
if (planInfo==1) {
  console.log(planInfo);
  title = '修改管理档案'
  fromVue.value= JSON.parse(route.query.data)
  generatedCode.value = fromVue.value.caseNumber || '';
  result1.value=fromVue.value.filePlan
  result2.value=fromVue.value.filePic
  result3.value=fromVue.value.fileEnd
  result4.value=fromVue.value.fileOther
  const userIds= localStorage.getItem('userId')
  if (userIds != fromVue.value.addId) {
    showSmit.value=false
    title = '查看管理档案'
  }

}
 const  whether=ref(false)

const planLevelList1=ref([])


/* 下拉框 */
const showActionSheet = ref(false)
const showActionSheet1 = ref(false)
const planLevelList = [
  { name: '转发', value: '转发' },
  { name: '内部', value: '内部' },
  { name: '文章', value: '文章' }
];
const isdisabled=ref(true)
const isdisabled2=ref(true)
const onSelect = (item) => {
fromVue.value.fileContent = item.name

  showActionSheet.value=false
}

const onSelect2 = (item) => {
  fromVue.value.fileType=item.name
  showActionSheet2.value=false
  }

const onCaseSourseSelect = (item) => {
  fromVue.value.caseSource=item.dicCode
  caseSourceFlag.value = false
}

const onAccidentLevelSelect = (item) => {
  fromVue.value.accidentLevel = item.dicCode
  accidentLevelFlag.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

  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/Manager/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) => {
  console.log(nodeData);
  const [deptCode, deptName] = nodeData.split('-', 2); // 只按第一个 '-' 分割
  fromVue.value.activityDept = deptCode.trim();
  fromVue.value.activityName = deptName.trim();

  showBottom.value = false
}

/* 组织树选择 */
const showBottom1 = ref(false)

const handleTableDataUserDeptUpdate1 = async (nodeData) => {
  console.log('选中的部门字符串:', nodeData); // e.g. "D1101120701-型钢炼钢站"

  // 确保 nodeData 是字符串
  if (typeof nodeData !== 'string') {
    console.warn('nodeData 不是字符串，跳过处理');
    showBottom1.value = false; // 假设你有另一个 showBottom1 控制弹窗
    return;
  }

  // 获取当前已选的 otherDept，转为数组（按逗号分割）
  const currentList = fromVue.value.otherDept
      ? fromVue.value.otherDept.split(',').filter(item => item.trim() !== '')
      : [];

  // 可选：防止重复添加
  if (!currentList.includes(nodeData)) {
    currentList.push(nodeData);
  }

  // 重新拼成逗号分隔的字符串
  fromVue.value.otherDept = currentList.join(',');

  showBottom1.value = false;
}

const addEmergencyDrillPlan = async () => {
  const loadingToast = showLoadingToast({
    duration: 0,
    message: '加载中',
    forbidClick: true
  })
  var url = '/sgsafe/Manager/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 onDatePicker = (value) => {
  const dateArr = value.selectedValues
  fromVue.value.startTime = dateArr[0] + '-' + dateArr[1] + '-' + dateArr[2]
  showDatePicker.value = false
}
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(() => {
  getAccidentDicList()
  console.log('这是编辑页面')
  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) => {
  fromVue.value.caseNumber = generatedCode.value;

  fromVue.value.filePlan =result1.value
  fromVue.value.filePic=result2.value
  fromVue.value.fileEnd =result3.value
  fromVue.value.fileOther=result4.value
  fromVue.value.filePicBefore=fileUrl.value
  addEmergencyDrillPlan()
}
const leaderKeyysr = guid();
const PopupDepartmentLeaderNameRefysr = ref();
const handleDepartmentLeaderNameysr = () => {
  PopupDepartmentLeaderNameRefysr.value.open();
};
const getDepartmentLeaderNameysr = (item) => {
  fromVue.value.punCode = item.user.userCode;
  fromVue.value.punName = item.user.userDesc;
  fromVue.value.punId = item.user.id
};

const onCaseSourceConfirm = ({ selectedOptions }) => {
  caseSourceFlag.value = false;
  fromVue.value.caseType = selectedOptions[0].text;
};

const onAccidentLevelConfirm = ({ selectedOptions }) => {
  accidentLevelFlag.value = false;
  fromVue.value.caseType = selectedOptions[0].text;
};

const onprimaryTwoConfirm = ({ selectedOptions }) => {
  primaryDomainTwoFlag.value = false;
  fromVue.value.primaryDomainTwo = selectedOptions[0].text;
};
const selectedPrimary = ref(null)
const onprimaryConfirm = ({ selectedOptions }) => {
  if (!selectedOptions?.length) {
    selectedPrimary.value = null;
    fromVue.value.primaryDomainTwo = '';
    primaryDomainFlag.value = false;
    return;
  }

  primaryDomainFlag.value = false;
  fromVue.value.primaryDomain = selectedOptions[0].text;

  const primaryList = accidentDictList.value?.primary_domain || [];
  const selectedItem = primaryList.find(item => item.dicName === selectedOptions[0].text);

  selectedPrimary.value = selectedItem || null;
  fromVue.value.primaryDomainTwo = '';
};

const filteredSecondaryList = computed(() =>
  selectedPrimary.value?.dicValue1
    ? (accidentDictList.value?.primary_domain_two || [])
      .filter(item => item.dicValue1 === selectedPrimary.value.dicValue1)
      .map(({ dicName, dicCode }) => ({ text: dicName, value: dicCode }))
    : []
);
const getDepartmentJoinPerson = (userArray) => {

}
const currentDate1 = ref([2025, 7, 25])
const showDatePicker1 = ref(false)
const onDatePicker1 = (value) => {
  const dateArr = value.selectedValues
  fromVue.value.endTime = dateArr[0] + '-' + dateArr[1] + '-' + dateArr[2]
  showDatePicker1.value = false
}
const fileUrl=ref('')
const handleFirstFileUrl = (url) => {
  console.log('第一张文件URL:', url)
  fileUrl.value=url
}
import AttachmentS3ImageReturnURL from '@/components/AttachmentS3ImageReturnURL.vue';
</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.caseNumber"-->
<!--          label="案例编号"-->
<!--          name="caseNumber"-->
<!--          required-->
<!--          placeholder="请输入案例编号"-->
<!--          :rules="[{required: true, message: '请输入文件编号'}]"-->
<!--        />-->
        <van-field
            v-model="generatedCode"
        label="案例编号"
        name="caseNumber"
            :readonly="true"
        :rules="[{required: true, message: '编号生成失败，请点击“重新生成”'}]"
        />

        <van-field
          v-model="fromVue.activityTitle"
          label="活动主题"
          name="caseTitle"
          required
          placeholder="请输入活动主题"
          :rules="[{required: true, message: '请输入活动主题'}]"
        />

        <van-field
          v-model="fromVue.caseType"
          readonly
          label="案例类型"
          name="caseType"
          required
          @click="caseSourceFlag = true"
        />
        <van-field
          readonly
          v-model="fromVue.activityType"
          label="活动形式"
          name="activityType"
          @click="accidentLevelFlag = true"
        />

        <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.activityName"
            label="主办单位"
            name="perName"
            @click="showBottom=true"
        />
        <van-field
            readonly
            v-model="fromVue.otherDept"
            label="协办/承办单位"
            name="perName"
            @click="showBottom1=true"
        />

        <van-field
            v-model="fromVue.activitySummary"
            label="活动简介"
            name="activitySummary"
            required
            rows="3"
            autosize
            type="textarea"
            placeholder="请输入活动简介"
            :rules="[{required: true, message: '请输入活动简介'}]"
        />

        <van-field label="活动照片">
          <template #input>
            <AttachmentS3ImageReturnURL style="background-color: white;" :f-id="result2"  @update:firstFileUrl="handleFirstFileUrl" />
          </template>
        </van-field>

        <van-field label="活动方案" >
          <template #input>
            <AttachmentS3 :f-id="result1" />
          </template>
        </van-field>
        <van-field label="活动总结及效果评价" >
          <template #input>
            <AttachmentS3 :f-id="result3" />
          </template>
        </van-field>
        <van-field label="签到表及其他材料" >
          <template #input>
            <AttachmentS3 :f-id="result4" />
          </template>
        </van-field>
        <div style="margin: 16px;">
          <van-button round block type="primary" v-show='showSmit' native-type="submit">
            {{ isEdit ? '保存' : '提交' }}
          </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-popup v-model:show="caseSourceFlag" round position="bottom">
        <van-picker
            :columns="columns"
            @cancel="caseSourceFlag = false"
            @confirm="onCaseSourceConfirm"
        />
      </van-popup>

      <van-popup v-model:show="accidentLevelFlag" round position="bottom">
        <van-picker
            :columns="columnsLevel"
            @cancel="accidentLevelFlag = false"
            @confirm="onAccidentLevelConfirm"
        />
      </van-popup>
      <van-popup v-model:show="primaryDomainFlag" round position="bottom">
        <van-picker
          :columns="columnsprimary"
          @cancel="primaryDomainFlag = false"
          @confirm="onprimaryConfirm"
        />
      </van-popup>
      <van-popup v-model:show="primaryDomainTwoFlag" round position="bottom">
        <van-picker
          :columns="filteredSecondaryList"
          @cancel="primaryDomainTwoFlag = false"
          @confirm="onprimaryTwoConfirm"
        />
      </van-popup>

<!--      <van-action-sheet-->
<!--          v-model:show="accidentLevelFlag"-->
<!--          :actions="accidentDictList.accident_level"-->
<!--          @select="onAccidentLevelSelect"-->
<!--      />-->

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