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

const {
  proxy
} = getCurrentInstance()
const accidentDictList = ref([])
const columns = ref([])
const columnsLevel = 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(generateCode());

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


const getAccidentDicList = () => {
  tools.dic.getDicList(['case_type', 'SEX', 'case_source', 'accident_level', 'accident_type', 'sgsafe_taccidentTags']).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.case_source.map(item => ({
      text: item.dicName,
      value: item.dicCode
    }));
    columnsLevel.value = accidentDictList.value.accident_level.map(item => ({
      text: item.dicName,
      value: item.dicCode
    }));


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

  }))
}


const caseSourceFlag = ref(false)
const accidentLevelFlag = 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 isReadOnly = ref(route.query.readOnly === 'true');
const isCaseSubmitted = computed(() => isReadOnly.value && isEdit.value);
const result = ref('')
const fromVue = ref({})
if (route.query.mark) {
  planInfo = JSON.parse(route.query.mark)
}
console.log(planInfo);
// 新增模式
if (planInfo == -1) {
  const caseNumber = generateCode();
  const fileId = ref()
  result.value = caseNumber
  //初始化 fromVue
  fromVue.value = {
    caseNumber: caseNumber,
    caseTitle: '',
    caseSource: '',
    accidentLevel: '',
    accidentDept: '',
    accidentLocation: '',
    accidentTime: '',
    accidentType: '',
    accidentTags: '',
    casualtyCount: '',
    accidentSummary: '',
    preventiveMeasures: '',
    fileId: fileId,
    viewCount: '0',
    downloadCount: '0'
  };
  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 distestType = ref(false)
if (planInfo == 1) {
  console.log(planInfo);
  title = '查看事故案例'
  fromVue.value = JSON.parse(route.query.data)
  if (!fromVue.value.fileId) {
    const newFileId = guid();
    fromVue.value.fileId = newFileId;
    result.value = newFileId;
  } else {
    result.value = fromVue.value.fileId;
  }

  console.log('编辑模式 - fileId:', result.value);
}
const whether = ref(false)

const planLevelList1 = ref([])

const onConfirmDatetime = () => {
  const year = currentDate.value[0];
  const month = currentDate.value[1].toString().padStart(2, '0');
  const day = currentDate.value[2].toString().padStart(2, '0');
  const hours = currentTime.value[0].toString().padStart(2, '0');
  const minutes = currentTime.value[1].toString().padStart(2, '0');
  const seconds = currentTime.value[2].toString().padStart(2, '0');

  fromVue.value.accidentTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  showDatetimePicker.value = false;
  dateOrTime.value = false;
};


const showDatetimePicker = ref(false);
const currentTime = ref();
const minDate = ref();
const maxDate = ref();

const dateOrTime = ref(false);
const onDateConfirm = () => {
  // 日期选择确认后的处理
  dateOrTime.value = true;
};
const resetDatetime = () => {
  dateOrTime.value = false;

  // 初始化日期和时间
  if (fromVue.value.accidentTime) {
    const dt = new Date(fromVue.value.accidentTime);
    currentDate.value = [dt.getFullYear(), dt.getMonth() + 1, dt.getDate()];
    currentTime.value = [
      String(dt.getHours()).padStart(2, '0'),
      String(dt.getMinutes()).padStart(2, '0'),
      String(dt.getSeconds()).padStart(2, '0')
    ];
  } else {
    const now = new Date();
    currentDate.value = [now.getFullYear(), now.getMonth() + 1, now.getDate()];
    currentTime.value = [
      String(now.getHours()).padStart(2, '0'),
      String(now.getMinutes()).padStart(2, '0'),
      String(now.getSeconds()).padStart(2, '0')
    ];
  }
};
const cancelDatePicker = () => {
  showDatetimePicker.value = false;
  resetDatetime();
};

// 时间选择器取消
const cancelTimePicker = () => {
  resetDatetime();
  // 重置为当前时间或从表单获取时间
  if (fromVue.value.accidentTime) {
    const dt = new Date(fromVue.value.accidentTime);
    currentTime.value = [
      String(dt.getHours()).padStart(2, '0'),
      String(dt.getMinutes()).padStart(2, '0'),
      String(dt.getSeconds()).padStart(2, '0')
    ];
  } else {
    const now = new Date();
    currentTime.value = [
      String(now.getHours()).padStart(2, '0'),
      String(now.getMinutes()).padStart(2, '0'),
      String(now.getSeconds()).padStart(2, '0')
    ];
  }
};


/* 下拉框 */
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
  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



      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/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
  })

  fromVue.value.fileId = result.value

  var url = '/sgsafe/Manager/saveAccident';
  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])
//定义字典集合
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]
  // 初始化时间
  currentTime.value = [today.getHours(), today.getMinutes(), today.getSeconds()];
  // 如果是编辑模式且有已有的事故时间，解析并初始化
  if (isEdit.value && fromVue.value.accidentTime) {
    try {
      // 解析格式如 "2025-01-15 14:30:00" 的时间字符串
      const timeStr = fromVue.value.accidentTime;
      const [datePart, timePart] = timeStr.split(' ');
      if (datePart && timePart) {
        const [year, month, day] = datePart.split('-').map(Number);
        const [hours, minutes, seconds] = timePart.split(':').map(Number);
        currentDate.value = [year, month, day];
        currentTime.value = [hours || 0, minutes || 0, seconds || 0];
      }
    } catch (error) {
      console.error('解析事故时间失败:', error);
    }
  }
  //selectedDateText.value = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`
  getDicList()
})
const showActionSheet2 = ref(false)
/* 文件上传 */
import AttachmentS3 from '@/components/AttachmentS3.vue';

const onSubmit = (values) => {
  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.caseSource = selectedOptions[0].text;
};

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

</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="fromVue.caseNumber"
            label="案例编号"
            name="caseNumber"
            readonly
            :rules="[{required: true, message: '编号生成失败，请点击“重新生成”'}]"
        />

        <van-field
            v-model="fromVue.caseTitle"
            label="案例标题"
            name="caseTitle"
            :readonly="isCaseSubmitted"
            required
            placeholder="请输入案例标题"
            :rules="[{required: true, message: '请输入标题名称'}]"
        />

        <van-field
            v-model="fromVue.caseSource"
            readonly
            label="案例来源"
            name="caseSource"
            :readonly="isCaseSubmitted"
            @click="!isCaseSubmitted && (caseSourceFlag = true)"
        />
        <van-field
            readonly
            v-model="fromVue.accidentLevel"
            label="事故等级"
            name="accidentLevel"
            :readonly="isCaseSubmitted"
            @click="!isCaseSubmitted && (accidentLevelFlag = true)"
        />

        <van-field
            v-model="fromVue.accidentDept"
            label="事故单位"
            name="accidentDept"
            placeholder="请输入事故单位"
            :readonly="isCaseSubmitted"
            :rules="[{required: true, message: '请输入事故单位'}]"
        />

        <van-field
            v-model="fromVue.accidentLocation"
            label="事故地点"
            name="accidentLocation"
            :readonly="isCaseSubmitted"
            placeholder="请输入事故地点"
            :rules="[{required: true, message: '请输入事故地点'}]"
        />

        <!--        //时间-->
        <van-field
            v-model="fromVue.accidentTime"
            is-link
            readonly
            name="datetime"
            label="发生时间"
            :colon="true"
            placeholder="点击选择日期和时间"
            @click="showDatetimePicker = !isCaseSubmitted"
            :rules="[{ required:true, message: '请选择内容' }]"
        />

        <van-popup
            v-model:show="showDatetimePicker"
            position="bottom"
            round
            style="max-height: 50vh;"
        >
          <van-date-picker
              v-if="!dateOrTime"
              v-model="currentDate"
              title="选择日期"
              :min-date="minDate"
              :max-date="maxDate"
              @confirm="onDateConfirm"
              @cancel="cancelDatePicker"
          >
            <template #confirm>
              <van-button type="primary" @click="onDateConfirm">下一步</van-button>
            </template>
            <template #cancel>
              <van-button type="danger" @click="cancelDatePicker">取消</van-button>
            </template>
          </van-date-picker>

          <van-time-picker
              v-if="dateOrTime"
              v-model="currentTime"
              title="选择时间"
              :columns-type="['hour', 'minute', 'second']"
              @confirm="onConfirmDatetime"
              @cancel="cancelTimePicker"
          >
            <template #confirm>
              <van-button type="primary" @click="onConfirmDatetime">确定</van-button>
            </template>
            <template #cancel>
              <van-button type="danger" @click="cancelTimePicker">取消</van-button>
            </template>
          </van-time-picker>
        </van-popup>
        <!--        // 标签-->

        <van-field
            v-model="fromVue.accidentTags"
            label="关键词/标签"
            name="accidentTags"
            :readonly="isCaseSubmitted"
            :rules="[{required: true, message: '请输入事故关键词/标签”'}]"
        />

        <van-field
            v-model="fromVue.casualtyCount"
            label="事故造成后果"
            name="casualtyCount"
            rows="1"
            autosize
            type="textarea"
            placeholder="请输入事故造成后果"
            :readonly="isCaseSubmitted"
            :rules="[{required: true, message: '请输入事故造成后果'}]"
        />
        <van-field
            v-model="fromVue.accidentSummary"
            label="事故简要经过"
            name="accidentSummary"
            rows="3"
            autosize
            type="textarea"
            placeholder="请输入事故简要经过"
            :readonly="isCaseSubmitted"
            :rules="[{required: true, message: '请输入事故简要经过'}]"
        />
        <van-field
            v-model="fromVue.preventiveMeasures"
            label="防范与整改措施"
            name="preventiveMeasures"
            rows="3"
            autosize
            type="textarea"
            placeholder="请输入防范与整改措施"
            :readonly="isCaseSubmitted"
            :rules="[{required: true, message: '请输入防范与整改措施'}]"
        />

        <van-field label="附件上传">
          <template #input>
            <AttachmentS3 :f-id="result"/>
          </template>
        </van-field>
        <div style="margin: 16px;">
          <van-button v-if="!isReadOnly" round block type="primary" 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-action-sheet
          v-model:show="caseSourceFlag"
          :actions="accidentDictList.case_source"
          @select="onCaseSourseSelect"
      />

      <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-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="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>
