<template>
  <div class="h5-container">
    <van-nav-bar title="隐患登记" @click-left="onClickLeft">
    </van-nav-bar>
    <van-form @submit="baocun" ref="formRef">
        <van-field
          is-link
          :colon="true"
          readonly
          v-model="form.type"
          required
          label="类别"
          placeholder="选择类别"
          @click="showPicker = true"
          :rules="[{ required:true, message: '请选择内容' }]"
        />
        <van-popup v-if="false" v-model:show="showPicker" round position="bottom">
          <van-picker
            :columns="yhlxs"
            @cancel="showPicker = false"
            @confirm="onConfirmYhlx"
          />
        </van-popup>

        <van-field
          border
          readonly
          v-model="form.item"
          name="项目"
          label="项目"
          :colon="true"
          placeholder="请输入项目"
        />

        <van-field
          border
          v-model="form.checkContent"
          name="内容"
          label="内容"
          :colon="true"
          placeholder="请输入内容"
        />

        <van-field
          border
          readonly
          v-model="form.checkWorkStandard"
          name="工作标准"
          label="工作标准"
          :colon="true"
          placeholder="请输入工作标准"
        />

        <van-field
          border
          readonly
          v-model="form.checkScoreStandard"
          name="评分标准"
          label="评分标准"
          :colon="true"
          placeholder="请输入评分标准"
        />

        <van-field
          is-link
          :colon="true"
          readonly
          v-model="form.ifFlag"
          required
          label="是否符合"
          placeholder="请选择"
          @click="showPicker3 = true"
          :rules="[{ required:true, message: '请选择' }]"
        />
        <van-popup v-model:show="showPicker3" round position="bottom">
          <van-picker
            :columns="sf"
            @cancel="showPicker3 = false"
            @confirm="onConfirmYhlx3"
          />
        </van-popup>

        <van-field
          border
          v-model="form.checkResult"
          name="检查结果"
          label="检查结果"
          :colon="true"
          placeholder="请输入检查结果"
          type="textarea"
          maxlength="1000"
          show-word-limit
          rows="4"
        />

        <van-field
          border
          readonly
          v-model="form.hdId"
          name="隐患编号"
          label="隐患编号"
          :colon="true"
          placeholder="请输入隐患编号"
        />

        <van-field
          border
          readonly
          v-model="form.hdSubmitTime"
          name="隐患下发时间"
          label="隐患下发时间"
          :colon="true"
          placeholder="请输入隐患下发时间"
        />

        <van-field
          border
          readonly
          v-model="form.notes"
          name="备注"
          label="备注"
          :colon="true"
          placeholder="请输入备注"
        />

        <van-field
          :colon="true"
          readonly
          label="问题图片上传"
        />
<!--        <van-uploader disabled v-model="fileList"  :after-read="afterRead" @delete="handleDelete" acc-->
<!--                      ept=".jpg,.gif,.png,.jpeg"  upload-icon="plus" multiple />-->
        <AttachmentS3Image :f-id="form.id" />

          <van-button block type="primary" native-type="submit" style="margin-bottom: 10px;">
            保存
          </van-button>
          <van-button block type="warning" plain @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';

const { proxy } = getCurrentInstance();

const onClickLeft = () => {
  history.back();
};
const form = ref({
  id: '',
  type: '',
  item: '',
  checkContent: '',
  checkWorkStandard: '',
  checkScoreStandard: '',
  notes: '',
  ifFlag: '',
  checkResult: '',
  hdId: '',
  hdSubmitTime: ''
});

onMounted(async () => {
  try {
    const url = '/sgsafe/CheckResultItem/queryByTaskId';
    const param = {
      id: proxy.$route.query.id
    };

    // 发起网络请求
    const response = await proxy.$axios.get(url, param);
    console.log('查询结果', response.data);

    if (response.data.code === 0) {
      form.value = response.data.data;
      console.log('查询结果', response.data.data);
    } else {
      showToast({
        message: '操作失败！' + response.data.msg
      });
    }

    // 确保在获取到数据后再调用 getTableData
    getTableData();
  } catch (error) {
    console.error('请求失败', error);
    showToast({
      message: '请求失败，请重试！'
    });
  }
});




  const showPicker = ref(false);

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

  const showPicker3 = ref(false);

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

  const yhlxs = ref([{ text: '管理标准化', value: '管理标准化' },
    { text: '现场标准化', value: '现场标准化' },
    { text: '检查标准化', value: '检查标准化' }]
  );
  const sf = ref([{ text: '是', value: '是' },
    { text: '否', value: '否' }]
  );

  const formRef = ref(null);
  const qvxiao = () => {
    showToast({
      type: 'fail',
      message: '操作取消！'
    });
    onClickLeft();
  };
  const baocun = async () => {
    var url = '/sgsafe/CheckResultItem/save';
    var param = {
      json: JSON.stringify(form.value)
    };
    proxy.$axios.post(url, param).then(response => {
      if (response.data.code === 0) {
        const data = response.data.data;
        console.log('插入时返回的数据', data)
        onClickLeft()
      } else {
        showToast({
          message: '操作失败！' + response.data.msg,
          type:'error'
        })
      }

    })
  };


  /***********************新图******************************/
//公共区
  import { atob } from 'js-base64';
import AttachmentS3 from '@/components/AttachmentS3.vue';
import AttachmentS3Image from '@/components/AttachmentS3Image.vue';

  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.id);
    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.id, //必填
      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);
      }
    });
  };
  

</script>

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

</style>
