<template>
  <div class="h5-container">
    <van-nav-bar title="隐患举报" @click-left="onClickLeft">
    </van-nav-bar>
    <van-form @submit="baocun" ref="formRef">
      <div style="color: #4C93E6;font-size: 14px;margin-left: 0px;
      background-color: #f4f4f4;padding: 8px 12px;margin: 0 -10px 10px -10px;">隐患信息
      </div>
      <van-field border v-model="form.hdId" name="隐患编号" label="隐患编号" :colon="true" placeholder=""
                 :readonly="true" />
      <van-field is-link :colon="true" readonly v-model="form.hdType" required label="隐患类型"
                 placeholder="选择隐患类型"
                 @click="showPicker = true" :rules="[{ required: true, message: '请选择内容' }]" />
      <van-popup v-model:show="showPicker" round position="bottom">
        <van-picker :columns="yhlxs" @cancel="showPicker = false" @confirm="onConfirmYhlx" />
      </van-popup>

      <van-field
        v-model="form.discoveryTime"
        is-link
        readonly
        name="datetime"
        label="发现时间"
        :colon="true"
        placeholder="点击选择日期和时间"
        @click="showDatetimePicker = true"
        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
        v-model="form.hdLocation"
        label="隐患区域"
        placeholder="请选择隐患区域"
        readonly
        right-icon="arrow-down"
        @click="showPickerHandle"
        required
        :rules="[{ required: true, message: '请选择' }]"
      />
      <!--        部门弹出框-->
      <van-popup v-model:show="showBottom" position="bottom">
        <OrganizationalWithLeaf @update:selected-node="handleTableDataUserDeptUpdate" />
      </van-popup>
      <van-field
        readonly
        v-model="form.discovererDesc"
        :colon="true"
        label="发现人"
        name="发现人"
        placeholder="请选择发现人"
        required
        :rules="[{ required: true, message: '请选择' }]"
        @click="handleDepartmentLeaderName"
      />
      <OrganizationalWithLeafUserOne ref="PopupDepartmentLeaderNameRef" @receive-from-child="getDepartmentLeaderName"
                                     :main-key="leaderKey" />
      <van-field
        border
        v-model="form.hdDescription"
        name="隐患描述"
        label="隐患描述"
        :colon="true"
        placeholder="请输入内容"
        required
        :rules="[{ required: true, message: '请输入内容' }]"
        type="textarea"
        rows="1"
        autosize
      />

      <van-field
        is-link
        :colon="true"
        readonly
        v-model="form.hdLevel"
        required
        label="隐患等级"
        placeholder="选择等级"
        @click="showPicker2 = true"
        :rules="[{ required:true, message: '请选择内容' }]"
      />
      <van-popup v-model:show="showPicker2" round position="bottom">
        <van-picker
          :columns="yhdjs"
          @cancel="showPicker2 = false"
          @confirm="onConfirmYhdj"
        />
      </van-popup>

      <van-field
        v-model="form.picBefore"
        :colon="true"
        readonly
        label="整改前图片"
      ></van-field>
      <!--      <van-uploader v-model="fileList" :after-read="afterRead" @delete="handleDelete" acc-->
      <!--                    ept=".jpg,.gif,.png,.jpeg" upload-icon="plus" multiple />-->

      <AttachmentS3Image :f-id="form.hdPicId" />

      <van-field
        :colon="true"
        readonly
        label="附件上传"
      />
      <AttachmentS3 :f-id="form.hdPicId+'fjwj'" />

      <span v-if="!isStandardFlow" style="color: #4C93E6;font-size: 12px;">隐患分析确认</span>
      <van-field
        v-if="form.hdSelect==='即查即改'"
        readonly
        v-model="form.repairLeaderDesc"
        :colon="true"
        label="整改人"
        name="整改人"
        placeholder="请选择整改人"
        required
        :rules="[{ required: true, message: '请选择' }]"
        @click="handleDepartmentLeaderNamezgr"
      />
      <OrganizationalWithLeafUserOne ref="PopupDepartmentLeaderNameRefzgr"
                                     @receive-from-child="getDepartmentLeaderNamezgr" :main-key="leaderKeyzgr" />
      <van-field
        v-if="form.hdSelect==='即查即改'"
        readonly
        border
        v-model="form.repairOtherDesc"
        name="其他整改人"
        label="其他整改人"
        :colon="true"
        placeholder="请选择其他整改人"
        @click="handleDepartmentLeaderName2qtzgr"
        required
        :rules="[{ required: true, message: '请选择' }]"
      />
      <OrganizationalWithLeafUser ref="PopupDepartmentLeaderNameRef2qtzgr"
                                  @receive-from-child="getDepartmentLeaderName2qtzgr" :main-key="leaderKey2qtzgr" />

      <!--        部门选择-->
      
      <van-field
        label-width="300px"
        v-if="form.hdSelect==='即查即改'"
        :colon="true"
        readonly
        label="临时管控现场图片"
      />
      <AttachmentS3Image style="background-color: white;" v-if="form.hdSelect==='即查即改'"
                         :f-id="form.hdPicId+'lsgkxctp'" />
      <van-field
        v-if="form.hdSelect==='即查即改'"
        v-model="form.picAfter"
        :colon="true"
        readonly
        label="整改后图片"

      />
      <AttachmentS3Image style="background-color: white;" v-if="form.hdSelect==='即查即改'"
                         :f-id="form.hdPicId+'zgh'" />

      <van-field
        v-if="form.hdSelect==='即查即改'"
        border
        v-model="form.repairDescription"
        name="整改后情况描述"
        label="整改后情况描述"
        :colon="true"
        placeholder="请输入整改后情况描述"
        required
        :rules="[{ required: true, message: '请输入内容' }]"
        type="textarea"
        rows="1"
        autosize
      />
      <van-button v-if="!(form.workId)" block round type="primary" native-type="submit" style="margin-bottom: 5px;">
        保存
      </van-button>
      <van-button 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 } 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 saveCheckInfo = async () => {
  let url = '/sgsafe/ActivityRecords/save';
  if (checklistForm.value.checklistType === 'equipment') {
    url = '/sgsafe/EquipmentRecords/save';
  }
  const param = {
    json: JSON.stringify(checklistForm.value)
  };
  const res = await proxy.$axios.post(url, param);
  if (res.data.code === 0) {
    showSuccessToast('新增排查记录成功！');
    sessionStorage.setItem('inspectionResult', '已排查');
  } else {
    showFailToast('操作失败！' + res.data.msg);
  }
};

onMounted(async () => {
  /**初始化时间**/
    // 更智能的日期范围设置
  const now = new Date();
  const currentYear = now.getFullYear();
  const currentMonth = now.getMonth();

  // 设置更合理的动态范围
  minDate.value = new Date(currentYear - 20, 0, 1); // 20年前
  maxDate.value = new Date(currentYear + 2, currentMonth, 28); // 2年后，日期固定为28号避免2月问题

  fileList.value = [];
  form.value.id = '';
  if (proxy.$route.query) {
    form.value = proxy.$route.query;
  }

  const hiddenDangerId = sessionStorage.getItem('hiddenDangerId');
  if (hiddenDangerId) {
    form.value.id = hiddenDangerId;
    sessionStorage.removeItem('hiddenDangerId');
  }

  const checklistInfoStr = sessionStorage.getItem('checklistInfo');
  if (checklistInfoStr) {
    checklistForm.value = JSON.parse(checklistInfoStr);
    sessionStorage.removeItem('checklistInfo');
  }

  form.value.hdSelect = '隐患举报';
  form.value.workId = '';
  form.value.discoveryTime = getTimeFormatter(new Date());
  if (form.value.id) {
    var url = '/sgsafe/JuBaoHiddendanger/queryById';
    var param = {
      id: form.value.id
    };
    await proxy.$axios.get(url, param).then(response => {
      if (response.data.code === 0) {
        form.value = response.data.data;
      } else {
        showToast({
          message: '操作失败！' + response.data.msg
        });
      }
    });
  }
  getTableData();
  console.log('路由传值', proxy.$route.query);
  console.log('form值', form.value);

  // 添加日期时间选择器初始化
  resetDatetime();
});

const getTimeFormatter = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从 0 开始，需加 1
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

/**表单*/
const form = ref({
  discovererOtherDesc: '',
  hdPicId: '',
  hdId: '',
  hdType: '',
  discoveryTime: '',
  hdSubtype: '',
  discoverer: '',
  discovererOther: '',
  hdDescription: '',
  hdLevel: '',
  bz: '',
  hdLocation: '',
  picBefore: '',
  workId: '',

  equipmentId: '',
  hdmanageLevel: '',
  handlingProcesses: '',
  companyId: '',
  repairLeader: '',
  repairOther: '',
  repairSuggest: '',
  repairDdl: '',
  repairDept: '',
  acceptLeader: '',
  acceptOther: '',
  picAfter: '',
  picTemp: '',
  repairDescription: '',
  discovererDept: '',
  discovererDeptCode: '',
  hdLocationCode: '',
  hdLocationName: '',

  status: '',


  hdSelect: '隐患举报',
  id: ''
});

const showPicker = ref(false);

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

const yhlxs = ref([{ 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.discoveryTime) {
    const dt = new Date(form.value.discoveryTime);
    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.discoveryTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  showDatetimePicker.value = false;
  dateOrTime.value = false;
};

const showPicker2 = ref(false);

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

const yhdjs = ref([{ text: '一般隐患', value: '一般隐患' },
  { text: '重大隐患', value: '重大隐患' }]
);

const formRef = ref(null);
const qvxiao = () => {
  showToast({
    type: 'fail',
    message: '操作取消！'
  });
  onClickLeft();
};
const baocun = async () => {
  if (form.value.hdSelect === '隐患举报') {
    form.value.status = '0';
  } 

  console.log('保存的参数', form.value);

  // 原有保存逻辑保持不变
  var url = 'sgsafe/JuBaoHiddendanger/save';
  var param = {
    json: JSON.stringify(form.value)
  };
  const response = await proxy.$axios.post(url, param);
  if (response.data.code === 0) {
    checklistForm.value.hiddenDangerId = response.data.data.id;
    if (checklistForm.value.hiddenDangerId) {
      await saveCheckInfo();
    }
    showToast({
      type: 'success',
      message: '保存成功！'
    });
    onClickLeft();
  } else {
    showToast({
      type: 'fail',
      message: '操作失败！'
    });
  }
};

const handleChangeHdSelect = (value) => {
  form.value.hdSelect = value;
  if (value === '隐患举报') {
    isStandardFlow.value = true;
  } else if (value === '即查即改') {
    isStandardFlow.value = false;
  }
  getYHID();
};

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

  return (S4() + S4() + S4() + S4() + S4() + S4() + S4() + S4());
};
/* 发现人 */
const leaderKey = guid();
const PopupDepartmentLeaderNameRef = ref();
const handleDepartmentLeaderName = () => {
  PopupDepartmentLeaderNameRef.value.open();
};

const codeAndDesc = ref([]);
const getDepartmentLeaderName = (item) => {
  form.value.discoverer = item.user.userCode;
  form.value.discovererDesc = item.user.userDesc;
  form.value.discovererDeptCode = item.dept.deptCode;
  form.value.discovererDept = item.dept.deptName;
};

/* 其他发现人 */
const leaderKey2 = guid();
const PopupDepartmentLeaderNameRef2 = ref();
const handleDepartmentLeaderName2 = () => {
  PopupDepartmentLeaderNameRef2.value.open();
};

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 = 'sgsafe/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.discoveryTime) {
    const dt = new Date(form.value.discoveryTime);
    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')
    ];
  }
};
/**修改发现时间**/

</script>

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

.radio-group {
  display: flex;
  background-color: white;
  padding: 10px;
  border-radius: 5px;
  margin: 10px 0;
  gap: 10px;
}

.radio-item {
  padding: 8px 12px;
  border: 1px solid #222;
  border-radius: 4px;
  background-color: white;
  cursor: pointer;
  transition: background-color 0.3s ease;
  /* 添加过渡效果 */
}

.radio-item.active {
  background-color: #4285f4;
  /* 选中时的蓝色 */
  color: white;
  border-color: #4285f4;
}
</style>
