<template>
  <div class="h5-container">
    <van-nav-bar title="隐患登记" @click-left="onClickLeft">
<!--      <template #left>-->
<!--        <svg t="1749540528155" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"-->
<!--             p-id="4132" width="6vw" height="6vh">-->
<!--          <path-->
<!--            d="M801.630938 934.023203m-36.203868 36.203867l0 0q-36.203867 36.203867-72.407734 0l-434.446406-434.446406q-36.203867-36.203867 0-72.407734l0 0q36.203867-36.203867 72.407734 0l434.446406 434.446406q36.203867 36.203867 0 72.407734Z"-->
<!--            fill="#000000" p-id="4133"></path>-->
<!--          <path-->
<!--            d="M729.223203-8.030938m36.203867 36.203868l0 0q36.203867 36.203867 0 72.407734l-434.446406 434.446406q-36.203867 36.203867-72.407734 0l0 0q-36.203867-36.203867 0-72.407734l434.446406-434.446406q36.203867-36.203867 72.407734 0Z"-->
<!--            fill="#000000" p-id="4134"></path>-->
<!--        </svg>-->
<!--      </template>-->
    </van-nav-bar>
    <van-form @submit="baocun" ref="formRef">
      <div style="color: #4C93E6;font-size: 12px;background-color: white;margin-left: 10px">隐患信息</div>
      <div class="radio-group">
        <div
          class="radio-item"
          :class="{ 'active': form.hdSelect === '正常登记' }"
          @click="selectOption('正常登记')"
        >
          标准流程
        </div>
        <div
          class="radio-item"
          :class="{ 'active': form.hdSelect === '即查即改' }"
          @click="selectOption('即查即改')"
        >
          即查即改
        </div>
      </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 @open="resetDatetime" 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="showDatetimePicker = false"
        >
          <!-- 自定义确认按钮 -->
          <template #confirm>
            <van-button type="primary"  @click="onDateConfirm">下一步</van-button>
          </template>
        </van-date-picker>
        <van-time-picker
          v-if="dateOrTime"
          v-model="currentTime"
          title="选择时间"
          :columns-type="['hour', 'minute', 'second']"
          @confirm="onTimeConfirm"
          @cancel="showDatetimePicker = false"
        >
          <!-- 自定义确认按钮 -->
          <template #confirm>
            <van-button  type="primary" @click="onConfirmDatetime">确定</van-button>
          </template>
        </van-time-picker>
<!--        <div v-if="dateOrTime" style="display: flex; justify-content: space-between;">-->
<!--          <van-button type="danger" @click="showDatetimePicker = false">取消</van-button>-->
<!--          <van-button type="primary" @click="onConfirmDatetime">确定</van-button>-->
<!--        </div>-->
      </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
        readonly
        border
        v-model="form.discovererOtherDesc"
        name="其他发现人"
        label="其他发现人"
        :colon="true"
        placeholder="请选择其他发现人"
        @click="handleDepartmentLeaderName2"
      />
      <OrganizationalWithLeafUser ref="PopupDepartmentLeaderNameRef2" @receive-from-child="getDepartmentLeaderName2"
                                  :main-key="leaderKey2" />
      <van-field
        border
        v-model="form.hdDescription"
        name="隐患描述"
        label="隐患描述"
        :colon="true"
        placeholder="请输入内容"
        required
        :rules="[{ required: true, message: '请输入内容' }]"
        type="textarea"
        rows="3"
      />

      <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
        v-if="form.hdSelect==='即查即改'"
        v-model="form.repairDept"
        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
        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="3"
      />
      <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="warning" @click="qvxiao">
        取消
      </van-button>
    </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/OrganizationalWithLeaf.vue';

const { proxy } = getCurrentInstance();

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


onMounted(async () => {
  fileList.value = [];
  form.value.id = '';
  form.value = proxy.$route.query;
  form.value.hdSelect = '正常登记';
  form.value.workId = ''
  form.value.discoveryTime = getTimeFormatter(new Date())
  if (form.value.id) {
    var url = '/sgsafe/Hiddendanger/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);
});

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 = new Date(2000, 0, 1);
const maxDate = new Date(9999, 11, 31);

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

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

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

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';
  } else if (form.value.hdSelect === '下发隐患') {
    form.value.status = '2';
  } else {
    form.value.status = '-1';
  }

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

  // 原有保存逻辑保持不变
  var url = 'sgsafe/Hiddendanger/save';
  var param = {
    json: JSON.stringify(form.value)
  };
  proxy.$axios.post(url, param).then(response => {
    if (response.data.code == 0) {
      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/Hiddendanger/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) => {
  form.value.repairDept = nodeData.deptName;
  // 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();
}

/**修改发现时间**/

/**修改发现时间**/

</script>

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

.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>
