<template>
  <div class="h5-container">
    <van-nav-bar :title @click-left="onClickLeft">
    </van-nav-bar>
    <van-form @submit="baocun" ref="formRef">
      <van-field :readonly="ifElseReadonly" border v-model="form.accidentLocation" name="事故地点" label="事故地点"
                 :colon="true" placeholder="事故地点"
                 required
                 :rules="[{ required:true, message: '请填充内容' }]"
      />
      <van-field
        v-model="form.accidentTime"
        is-link
        readonly
        name="datetime"
        label="发生时间"
        :colon="true"
        placeholder="点击选择日期和时间"
        @click="showDatetimePicker = !ifElseReadonly"
        required
        :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  :readonly="ifElseReadonly" border v-model="form.sceneConditions" name="事故现场情况" label="事故现场情况"
                 type="textarea"
                 autosize
                 :colon="true" placeholder="事故现场情况"
                 required
                 :rules="[{ required:true, message: '请填充内容' }]"
      />
      <van-field  :readonly="ifElseReadonly" border v-model="form.accidentSummary" name="事故简要经过" label="事故简要经过"
                 type="textarea"
                 autosize
                 :colon="true" placeholder="事故简要经过"
                 required
                 :rules="[{ required:true, message: '请填充内容' }]"
      />
      
      <van-field is-link :colon="true" readonly v-model="form.accidentType" required label="事故类型"
                 placeholder="选择事故类型"
                 @click="showPicker = !ifElseReadonly" :rules="[{ required: true, message: '请选择内容' }]" />
      <van-popup :readonly="ifElseReadonly" v-model:show="showPicker" round position="bottom">
        <van-picker :columns="yhlxs" @cancel="showPicker = false" @confirm="onConfirmYhlx" />
      </van-popup>
      <van-field v-model="form.seriousInjuryCount" name="重伤人数" label="重伤人数" :colon="true" readonly clickable @touchstart.stop="showSeriousInjuryCount = !ifElseReadonly"
      required :rules="[{ required: true, message: '请输入重伤人数' }]"/>
      <van-number-keyboard
        :readonly="ifElseReadonly"
        v-model="form.seriousInjuryCount"
        :show="showSeriousInjuryCount"
        @blur="showSeriousInjuryCount = false"
      />
      <van-field v-model="form.deathCount" name="死亡人数" label="死亡人数" :colon="true" readonly clickable @touchstart.stop="showDeathCount = !ifElseReadonly"
                 required :rules="[{ required: true, message: '请输入死亡人数' }]"/>
      <van-number-keyboard
        :readonly="ifElseReadonly"
        v-model="form.deathCount"
        :show="showDeathCount"
        @blur="showDeathCount = false"
      />
      <van-field v-model="form.economicLoss" name="事故经济损失" label="事故经济损失(万元)" :colon="true" readonly clickable @touchstart.stop="showEconomicLoss = !ifElseReadonly"
                 required :rules="[{ required: true, message: '请输入事故经济损失并确认是否最多只有小数',pattern: /^\d+(\.\d{1,3})?$/ }]"/>
      <van-number-keyboard
        :readonly="ifElseReadonly"
        v-model="form.economicLoss"
        :show="showEconomicLoss"
        theme="custom"
        extra-key="."
        close-button-text="完成"
        @blur="showEconomicLoss = false"
        @input="onInput"
        @delete="cKeyDelete"
      />
      <van-field readonly border v-model="accidentLevel" name="事故等级" label="事故等级"
                 :colon="true" placeholder="事故等级"
      />

      <van-field v-if="false" border v-model="form.unlawfulAct" name="可能存在的违法行为" label="可能存在的违法行为"
                 type="textarea"
                 autosize
                 :colon="true" placeholder="可能存在的违法行为"
                 required
                 :rules="[{ required:true, message: '请填充内容' }]"
      />
      <van-field v-if="true" border v-model="form.unlawfulAct" name="可能存在的违法行为" label="可能存在的违法行为"
                 type="textarea"
                 :readonly="ifElseReadonly"
                 autosize
                 :colon="true" placeholder="可能存在的违法行为"
      />

      <van-field border v-model="form.measuresTaken" name="已采取的措施" label="已采取的措施"
                 type="textarea"
                 autosize
                 :readonly="ifElseReadonly"
                 :colon="true" placeholder="已采取的措施"
                 required
                 :rules="[{ required:true, message: '请填充内容' }]"
      />

      <van-field border v-model="form.otherConditions" name="其他应当报告的情况" label="其他应当报告的情况"
                 type="textarea"
                 autosize
                 :readonly="ifElseReadonly"
                 :colon="true" placeholder="其他应当报告的情况"
      />
      
      <van-button v-if="!ifElseReadonly" block round type="primary" native-type="submit" style="margin-bottom: 5px;">
        保存
      </van-button>
      <van-button v-if="!ifElseReadonly" block round plain type="default" @click="qvxiao">
        取消
      </van-button>
      <div style="height: 10px;"></div>
    </van-form>
  </div>


  <van-dialog v-model:show="showDialogVisible" title="删除文件" show-cancel-button
              confirm-button-color="#ee0124" message="确定删除该文件吗?" @confirm="onDelete" />
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance, nextTick, computed } from 'vue';
import { closeToast, Dialog, showFailToast, showLoadingToast, showSuccessToast, showToast } from 'vant';
import AttachmentS3Image from '@/components/AttachmentS3Image.vue';
import AttachmentS3 from '@/components/AttachmentS3.vue';
import OrganizationalWithLeafUserOne from '@/components/OrganizationalWithLeafUserOne.vue';
import OrganizationalWithLeafUser from '@/components/OrganizationalWithLeafUser.vue';
import OrganizationalWithLeaf from '@/components/JuBaoOrganizationalWithLeaf.vue';

const { proxy } = getCurrentInstance();

const onClickLeft = () => {
  history.back();
};

/* 风险隐患排查发现隐患，进行登记代码 */
const checklistForm = ref({
  evaluationId: '',
  checklistType: '',
  hiddenDangerId: ''
});

const ifElseReadonly = ref(false)
const title = ref('')
onMounted(async () => {
  const id = proxy.$route.query.id
  const flag = proxy.$route.query.flag
  if('add'===flag){
    title.value='新增事故信息'
  }else if ('edit'===flag){
    title.value='修改事故信息'
  }else {
    title.value='查看事故信息'
  }
  if(id){
    const res = await proxy.$axios.get('/sgsafe/AccidentDirect/queryFormById', {
      id
    });
    if(res.data.code === 0){
      form.value = res.data.data
    }else {
      showToast({
        type: 'fail',
        message: '操作失败'+res.data.msg
      })
    }
    if(flag === 'look'){
      ifElseReadonly.value = true
    }
  }
});

/**表单*/
const form = ref({
  seriousInjuryCount:'',//重伤人数
  deathCount:'',//死亡人数
  economicLoss:'',//经济损失
  accidentLevel:'',//事故等级
});

const showPicker = ref(false);

const onConfirmYhlx = ({ selectedOptions }) => {
  showPicker.value = false;
  form.value.accidentType = selectedOptions[0].value;
  console.log('选择的内容', form.value);
};

const yhlxs = ref([{text: '泄露', value: '泄露'},
  {text: '坍塌', value: '坍塌'},
  {text: '灼烫', value: '灼烫'},
  {text: '触电', value: '触电'},
  {text: '机械伤害', value: '机械伤害'},
  {text: '高处坠落', value: '高处坠落'},
  {text: '中毒窒息', value: '中毒窒息'},
  {text: '容器爆炸', value: '容器爆炸'},
  {text: '爆炸', value: '爆炸'},
  {text: '火灾', value: '火灾'}]
);

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

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

const onTimeConfirm = () => {
  // 时间选择确认后的处理
};

const resetDatetime = () => {
  dateOrTime.value = false;

  // 初始化日期和时间
  if (form.value.accidentTime) {
    const dt = new Date(form.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 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');

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


const formRef = ref(null);
const qvxiao = () => {
  showToast({
    type: 'fail',
    message: '操作取消！'
  });
  onClickLeft();
};
const baocun = async () => {
  form.value.accidentLevel = accidentLevel
  // 原有保存逻辑保持不变
  var url = 'sgsafe/AccidentDirect/save';
  var param = {
    json: JSON.stringify(form.value)
  };
  const response = await proxy.$axios.post(url, param);
  if (response.data.code === 0) {
    showToast({
      type: 'success',
      message: '保存成功！'
    });
    onClickLeft();
  } else {
    showToast({
      type: 'fail',
      message: '操作失败！'
    });
  }
};

const guid = () => {
  function S4() {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
  }

  return (S4() + S4() + S4() + S4() + S4() + S4() + S4() + S4());
};

const codeAndDesc2 = ref([]);
const getDepartmentLeaderName2 = (items) => {
  console.log('人员数据', items);
  let codeList = [];
  let descList = [];
  for (let item of items) {
    codeAndDesc2.value.push(item.userCode + '-' + item.userDesc);
    codeList.push(item.userCode);
    descList.push(item.userDesc);
  }
  form.value.discovererOther = codeList.join(',');
  form.value.discovererOtherDesc = descList.join(',');
};

//定义一个变量切换即查即改还是标准流程
const isStandardFlow = ref(true);

//当是即查即改时得到隐患编号并赋值
const getYHID = () => {
  //直接请求后端返回一个隐患编号
  console.log('getYHID');
  if (form.value.hdSelect === '即查即改') {
    var url = 'safe/JuBaoHiddendanger/getYhbhTemp';
    var param = {};
    proxy.$axios.get(url, param).then(response => {
      if (response.data.code == '0') {
        form.value.hdId = response.data.data;
      } else {
        ElMessage.error('操作失败！' + response.data.msg);
      }
    });
  } else {
    form.value.hdId = '';
  }
};

/* 整改人 */
const leaderKeyzgr = guid();
const PopupDepartmentLeaderNameRefzgr = ref();
const handleDepartmentLeaderNamezgr = () => {
  PopupDepartmentLeaderNameRefzgr.value.open();
};

const codeAndDesczgr = ref([]);
const getDepartmentLeaderNamezgr = (item) => {
  form.value.repairLeader = item.user.userCode;
  form.value.repairLeaderDesc = item.user.userDesc;
  form.value.repairDept = item.dept.deptName;
};

/* 其他整改人 */
const leaderKey2qtzgr = guid();
const PopupDepartmentLeaderNameRef2qtzgr = ref();
const handleDepartmentLeaderName2qtzgr = () => {
  PopupDepartmentLeaderNameRef2qtzgr.value.open();
};

const codeAndDesc2qtzgr = ref([]);
const getDepartmentLeaderName2qtzgr = (items) => {
  console.log('人员数据', items);
  let codeList = [];
  let descList = [];
  for (let item of items) {
    codeAndDesc2qtzgr.value.push(item.userCode + '-' + item.userDesc);
    codeList.push(item.userCode);
    descList.push(item.userDesc);
  }
  form.value.repairOther = codeList.join(',');
  form.value.repairOtherDesc = descList.join(',');
};

/* 组织树选择 */
const showBottom = ref(false);
const handleTableDataUserDeptUpdate = async (nodeData) => {
  let temp = nodeData.split('-');
  if(temp[0].length<9){
    showFailToast('请选择四级及以下部门')
    return
  }
  form.value.hdLocation = temp[1];
  form.value.hdLocationCode = temp[0];
  form.value.hdConfirm = temp[2]
  // form.value.repairDept = nodeData.deptCode + '-' + nodeData.deptName
  showBottom.value = false;
};
const showPickerHandle = () => {
  showBottom.value = true;
};

/**表单*/

/***********************新图******************************/
//公共区
import { atob } from 'js-base64';

const bucket = ref(import.meta.env.VITE_BUCKET);

function base64ToBlob(base64) {
  const contentType = base64.substring(base64.indexOf(':') + 1, base64.indexOf(';'));
  const byteCharacters = atob(base64);
  const byteArrays = [];

  for (let i = 0; i < byteCharacters.length; i++) {
    byteArrays.push(byteCharacters.charCodeAt(i));
  }

  const byteArray = new Uint8Array(byteArrays);
  return new Blob([byteArray], { type: contentType });
}

const headers = ref({
  token: localStorage.getItem('token'),
  userId: localStorage.getItem('userId')
});

//整改前
const fileList = ref([]);
const afterRead = (file) => {
  const content = base64ToBlob(file.content);
  const formData = new FormData();
  formData.append('fId', form.value.hdPicId);
  formData.append('bucket', bucket.value);
  formData.append('value1', null);
  formData.append('value2', null);
  formData.append('value3', null);
  formData.append('value4', null);
  formData.append('value5', null);
  formData.append('file', content, file.file.name);
  let url = import.meta.env.VITE_BASE_API + '/framework/Common/uploadFileS3';
  proxy.$axios.post(url, formData, { headers: headers.value }).then(res => {
    if (res.data.code === 0) {
      showSuccessToast('上传成功');
      getTableData();
    } else {
      showFailToast('上传失败' + res.data.msg);
    }
  }).catch(error => {
    console.log(error);
  });
};
const getTableData = () => {
  //携带自定义参数
  var url = 'framework/Common/queryFileWithValues';
  var param = {
    fId: form.value.hdPicId, //必填
    value1: null, //非必填
    value2: null, //非必填
    value3: null, //非必填
    value4: null, //非必填
    value5: null //非必填
  };
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code === 0) {
      for (var item of response.data.data) {
        fileList.value.push({
          id: item.id,
          uploadFile: item.fileName,
          url: import.meta.env.VITE_BASE_API +
            '/framework/Common/downloadFileS3?bucket=' + bucket.value +
            '&id=' + item.id
        });
        form.value.picBefore = fileList.value[0].url;
      }
    } else {
      showFailToast('失败！' + response.data.msg);
    }
  });
};
/* 在线删除 */
const showDialogVisible = ref(false);
const deleteInfo = ref();
const handleDelete = (row) => {
  showDialogVisible.value = true;
  deleteInfo.value = row;
};
const onDelete = () => {
  let url = 'framework/Common/removeFile';
  let param = {
    id: deleteInfo.value.id
  };
  proxy.$axios.post(url, param).then(response => {
    if (response.data.code === 0) {
      showSuccessToast('删除成功!');
      getTableData();
    } else {
      showFailToast('删除失败;' + response.data.msg);
    }
  });
};

//隐患选择
const selectOption = (option) => {
  if (form.value.workId.length > 0) {
    return;
  }
  form.value.hdSelect = option;
  if (option === '隐患举报') {
    isStandardFlow.value = true;
  } else if (option === '即查即改') {
    isStandardFlow.value = false;
  }
  getYHID();
};

/**修改发现时间**/
// 日期选择器取消
const cancelDatePicker = () => {
  showDatetimePicker.value = false;
  resetDatetime();
};

// 时间选择器取消
const cancelTimePicker = () => {
  resetDatetime();
  // 重置为当前时间或从表单获取时间
  if (form.value.accidentTime) {
    const dt = new Date(form.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 showSeriousInjuryCount = ref(false)
const showDeathCount = ref(false)
const showEconomicLoss = ref(false)

/**控制输入**//*
const onInput = (value) =>{
  console.log('输入的值', value)
  // 1. 过滤所有非数字和非小数点的字符（只保留数字和一个小数点）
  // let value = val.replace(/[^\d.]/g, '');

  // 2. 处理多个小数点：只保留第一个小数点，后续的小数点删除
  // const dotIndex = value.indexOf('.');
  if (value !== -1) {
    // 从第一个小数点后开始，删除所有其他小数点
    value = value.slice(0, dotIndex + 1) + value.slice(dotIndex + 1).replace(/\./g, '');
  }

  // 3. 处理开头为小数点的情况：自动补0（如 .123 → 0.123）
  if (value.startsWith('.')) {
    value = '0' + value;
  }

  // 4. 限制小数位最多3位：如果有小数点，截取小数点后前3位
  if (value.includes('.')) {
    const parts = value.split('.');
    // 整数部分 + 小数点 + 小数部分前3位
    value = parts[0] + '.' + (parts[1] || '').slice(0, 3);
  }

  // 5. 赋值给表单（避免空值时显示undefined）
  form.value.economicLoss = value || '';
}*/

/**控制键盘删除**/
const cKeyDelete = () => {
  if (!form.value.economicLoss) return; // 为空时不操作

  // 截取掉最后一个字符
  let value = form.value.economicLoss.slice(0, -1);

  // 处理删除后可能出现的不合理格式（比如只剩小数点）
  if (value === '.') {
    value = ''; // 如果删除后只剩小数点，清空
  }

  form.value.economicLoss = value;
}

/**计算属性**/
//计算属性
const accidentLevel = computed(()=>{
  if(form.value.deathCount>=30 || form.value.economicLoss>=100000 || form.value.seriousInjuryCount>=100){
    return '特别重大事故'
  }else if(form.value.deathCount>=10 || form.value.economicLoss>=5000 || form.value.seriousInjuryCount>=50){
    return '重大事故'
  }else if(form.value.deathCount>=3 || form.value.economicLoss>=1000 || form.value.seriousInjuryCount>=10){
    return '较大事故'
  }else{
    return '一般事故'
  }
})

</script>

<style scoped>
.h5-container {
  width: 100%;
  box-sizing: border-box;
  height: 100vh;
  background-color: white;
  padding: 10px;
  padding-bottom: 20px;
}

</style>
