<template>
  <div class="task-no-check">
    <headNav title="不检查"></headNav>
    <div class="check-list">
      <van-cell-group>
        <van-cell class="no-check-reason" is-link :value="reason" @click="selectReason">
          <template #title>
            <span class="custom-title">不检查原因</span>
          </template>
        </van-cell>
        <van-field
          class="no-check-textarea"
          required
          rows="4"
          autosize
          v-model="description"
          label="不检查情况说明"
          type="textarea"
          maxlength="300"
          placeholder="请输入..."
          show-word-limit
        />
        <van-field name="fileList" input-align="right" label="现场照片">
          <template #input>
            <!-- <van-uploader
                v-model="cers.fileList"
                :max-count="1"
                :before-read="beforeAvatarUpload"
                :after-read="afterRead"
                multiple
                capture="camera"
                @delete="deleteCerFile"
            /> -->
            <van-uploader
              v-model="fileList"
              :before-read="beforeAvatarUpload"
              :after-read="afterRead"
              multiple
              capture="camera"
            />
          </template>
        </van-field>
      </van-cell-group>
    </div>

    <div style="margin: 16px;">
      <van-button round block type="info" native-type="submit" @click="confirmSubmit">提交</van-button>
    </div>


    <van-popup
      v-model="showPicker"
      position="bottom"
      round
    >
      <van-picker show-toolbar title="标题" :columns="columns" @cancel="showPicker = false" @confirm="onConfirm" />
    </van-popup>
  </div>
</template>
<script>
import headNav from "@/components/headNav.vue";
import { compressAccurately } from "image-conversion";
import { get, put } from "@/utils/http.js";
export default {
  name: 'taskNoCheck',
  components: {
    headNav
  },
  data () {
    return {
      showPicker: false,
      columns: ['停业', '歇业', '关门', '其他'],
      description: '',
      reason: '请选择',
      fileList: []
    }
  },
  methods: {
    uploadFile(data) {
      let name = data.file.name;
      if (!name || name.length == 0) {
        name = Date.now() + '.jpeg';
      }
      const form = new FormData();
      form.append('fileName', name);
      form.append('fileBinary', data.file);
      this.$http.post('/v2/api/file', form).then(res => {
        if (res && res.data && res.data.id) {
          data.fileID = res.data.id;
          this.checkFile();
        }
      })
    },
    checkFile() {
      let have = false;
      if (this.fileList.length > 0) {
        for (let index = 0; index < this.fileList.length; index++) {
          const item = this.fileList[index];
          if (!item.url && !item.fileID) {
            have = true;
            this.uploadFile(item);
            break;
          }
        }
      }
      if (!have) {
        this.commitFormData();
      }
    },
    commitFormData() {
      const {ID} = this.$route.params
      let ids = [];
      if (this.fileList.length > 0) {
        this.fileList.map(item => {
          if (item.fileID) {
            ids.push(item.fileID);
          }
        })
      }
      put(`/v2/api/enforce-job/${ID}`, {
        job_result_remark: `不检查（${this.reason}）`,
        job_result_content: this.description,
        job_result_pictures: ids.join(','),
        enforce_result: 'OVERPASS',
        job_status: 'ARCHIVED'
      }).then(res => {
        this.$toast.success('提交成功');
        this.$router.back();
      }).catch(e => {
        this.$toast.fail('提交失败， 请重试！');
      })
    },
    beforeAvatarUpload(file) {
      console.debug('file1: ', file);
      const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
      if (!isJpgOrPng) {
        this.$toast.fail("图片只能是 JPG 或 PNG 格式!");
        return false;
      }
      this.showOverLay = true;
      this.tipMsg = '图片处理中';
      return new Promise((resolve) => {
        compressAccurately(file, {
          size: 100, //图片大小压缩到100kb
          // width: 1280, //宽度压缩到1280
        })
          .then((res) => {
            this.showOverLay = false;
            console.debug('file2: ', res);
            resolve(res);
          });
      });
    },
    afterRead(file) {
      if (file && file.file && file.file.size > 2000000) {
        let canvas = document.createElement('canvas');
        let context = canvas.getContext('2d');
        let img = new Image();
        img.src = file.content;
        img.onload = () => {
          canvas.width = img.width;
          canvas.height = img.height;
          context.drawImage(img, 0, 0, img.width, img.height);
          let base_img = canvas.toDataURL(file.file.type, 0.75);
          const blodBin = atob(base_img.split(',')[1]);
          let data = [];
          for (let i = 0; i < blodBin.length; i++) {
            data.push(blodBin.charCodeAt(i));
          }
          let blob1 = new Blob([new Uint8Array(data)], { type: 'image/png' });
          let file1 = new File([blob1], new Date().getTime() + '.png');
          file.file = file1;
        };
      }
    },
    selectReason() {
      this.showPicker = true
    },
    onConfirm(value) {
      this.reason = value
      this.showPicker = false
    },
    confirmSubmit() {
      if (!this.reason || this.reason === '请选择') {
        this.$toast.fail('请选择不检查原因！')
        return
      }
      if (!this.description) {
        this.$toast.fail('请填写不检查情况说明！')
        return
      }
      this.checkFile()
    }
  }
}
</script>
<style lang="scss" scoped>
.check-list {
  margin-top: 57px;
  .no-check-textarea {
    flex-wrap: wrap;
    /deep/.van-cell__title {
      width: 100%;
      margin-bottom: 5px;
    }
    /deep/.van-cell__value {
      border: 1px solid #eee;
      padding: 5px;
    }
  }
  /deep/.no-check-reason {
    .van-cell__title {
      position: relative;
      &:before {
        content: '*';
        position: absolute;
        color: #ee0a24;
        left: -7px;
      }
    }
  }
}
</style>
