<template>
  <div class="app-container">
    <el-row>
      <div style="display: flex;margin: 20px 0">
        <van-field ref="barcode" v-model="barcode" left-icon="scan" clearable style="width: 260px;border-radius: 4px;border:1px solid #DCDFE6;height: 36px;line-height: 18px" />
        <van-field v-model="dateTimeShowInfo" left-icon="clock-o" style="width: 270px;border-radius: 4px;border:1px solid #DCDFE6;height: 36px;line-height: 18px" readonly  @focus="forbid;dateTimeShow=!dateTimeShow" />
        <van-calendar v-model="dateTimeShow" :min-date="minDate" :max-date="maxDate" :default-date="dateTimeDefault" type="range" @confirm="confirmFnDate" />
        <el-button type="success" icon="el-icon-search" size="small" style="margin-left: 10px;" @click="getTable2">查询</el-button>
      </div>
    </el-row>
    <el-row style="overflow: auto;height: 750px">
      <van-list
        v-model="loading_checkOrder"
        :finished="true"
        finished-text="没有更多了"
      >
        <van-cell v-for="(item,index) in RepairManagementDataLogTable" :key="index" style="padding: 10px 5px">
          <van-card class="s-card">
            <template #tags>
              <van-row style="font-size: 1.5rem">
                <van-tag type="primary" size="large">【{{index+1 }}】</van-tag>
                <van-tag type="success" size="large">【{{item.产品编号 }}】</van-tag>

                <van-tag style="float: right" v-if="item.放行方式 === '合格放行'" type="success" size="large">【{{item.放行方式 }}】</van-tag>
                <van-tag style="float: right" v-if="item.放行方式 === '偏差放行'" type="warning" size="large">【{{item.放行方式 }}】</van-tag>
                <van-tag style="float: right" v-if="item.放行方式 === '返工放行'" type="danger" size="large">【{{item.放行方式}}】</van-tag>
              </van-row>
              <van-row style="font-size: 1.3rem">
                <van-col span="20" style="margin-top: 10px">
                  <div style="margin: 10px 10px 0 0;">
                    <van-icon name="contact-o" color="#1989fa"/>
                    <span>记录人：</span>
                    <span> {{item.记录人 }}</span>
                  </div>
                  <div style="margin: 10px 10px 0 0;">
                    <van-icon name="clock-o" color="#1989fa"/>
                    <span>记录时间：</span>
                    {{item.记录时间}}
                  </div>
                  <div style="margin: 10px 10px 0 0;">
                    <van-icon name="comment-o" color="#1989fa"/>
                    <span>问题项目：</span>
                    {{item.问题项目}}
                  </div>
                  <div style="margin: 10px 10px 0 0;">
                    <van-icon name="notes-o" color="#1989fa"/>
                    <span>记录备注：</span>
                    <span> {{item.备注}}</span>
                  </div>
                </van-col>
                <van-col span="4">
                  <van-button plain icon="completed-o" size="small" type="primary" style="margin-top: 10px" @click="solveNc(item)">图片上传</van-button>
                  <br>
                  <van-button v-if="item.附件数量 > 0" plain icon="orders-o" size="small" type="warning" style="margin-top: 10px" @click="showFile(item)">查看附件</van-button>
                </van-col>
              </van-row>
            </template>
          </van-card>
        </van-cell>
      </van-list>
    </el-row>
    <van-dialog
      v-model="showTableData_content_exchange"
      width="70%"
      :lock-scroll="false"
      :show-cancel-button="false"
      :show-confirm-button="false"
      style="max-height: 70%!important;overflow: auto"
    >
      <div class="dialog-content">
        <!-- 固定顶部的内容 -->
        <div class="dialog-header">附件</div>
        <!-- 可滚动的内容区域 -->
        <div class="scrollable-content">
          <van-list :finished="true">
            <van-cell v-for="(item,index) in RepairManagementDataTableOrigin" :key="index">
              <el-row v-if="/(jpg|jpeg|png|GIF|JPG|PNG)$/i.test(item.附件类型)">
                【{{index + 1}}】<el-link type="primary" @click="showPic(item)">{{item.附件名称}}.{{item.附件类型 }}</el-link>
              </el-row>
              <el-row v-else>
                【{{index + 1}}】{{item.附件名称}}.{{item.附件类型 }}
              </el-row>
            </van-cell>
          </van-list>
        </div>
        <!-- 固定底部的内容 -->
        <div class="dialog-footer">
          <van-button plain size="small" style="width: 100%;font-size: 16px;height: 48px;" @click="showTableData_content_exchange=false">关闭</van-button>
        </div>
      </div>

    </van-dialog>
    <van-dialog
      v-model="showTableData_content_exchange1"
      width="70%"
      title="图片上传"
      :lock-scroll="false"
      :show-cancel-button="false"
      :show-confirm-button="false"
      style="max-height: 70%!important;overflow: auto"
    >
      <van-form validate-first ref="form_addCheckOrder">
        <van-field name="uploader" label="照片上传">
          <template #input>
            <van-uploader v-model="uploader" :after-read="afterRead" :max-count="1" :before-read='beforeRead' />
          </template>
        </van-field>
        <div style="background-color: white;text-align: center;margin-top: 10px;display: flex;">
          <van-button type="default" style="width: 100%" @click="showTableData_content_exchange1 = false">关闭</van-button>
          <van-button type="info" native-type="submit" style="width: 100%" @click="reportPicUpload()">上传</van-button>
        </div>
      </van-form>
    </van-dialog>
  </div>

</template>

<script>
import {Dialog, ImagePreview, Toast} from 'vant'
import {base64ImgtoFile, dataURLtoFile, formatDate, getBeforeOrAfterTime, getNowTime2} from '../../../utils/tool'
import axios from 'axios'
let forms = null; //设置公共变量，用来创建 FromData 对象，把文件带到后台
export default {
  name: 'RepairManagement',
  props: {
    pageType: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      minDate: null,
      maxDate: null,
      statusNumber: [
        {
          label: '全部',
          value: 9999
        },
        {
          label: '未处理',
          value: 0
        },
        {
          label: '已处理',
          value: 1
        }
      ],
      statusNumberValue: 1,
      dateTimeShowInfo: '',
      dateTimeShow: false,
      dateTimeDefault: [],
      dateTime: [],
      barcode: '',
      barcodeMaterial: '',
      loading_checkOrder: false,
      showImages: false,
      imageList: [],
      RepairManagementDataTable: [],
      userInfo: '',
      showTableData_content: false,
      loading_checkOrder_content: false,
      RepairManagementMaterialDataTable: [],
      showTableData_content_exchange1: false,
      uploader: [],
      Data: {},
      RepairManagementReplaceForm: {
        ID: 0,
        productCode: '',
        solveType: '',
        solvePeople: ''
      },
      showTableData_content_exchange: false,
      loading_checkOrder_content_exchange: false,


      RepairType: 1,
      currentSelectRow: {},
      RepairManagementReplaceDialogVisible: false,
      RepairManagementDestroyAllDialogVisible: false,
      RepairManagementReplaceRules: {
        materialBarCodeNew: [{ required: true, message: '请输入/扫描新物料码！', trigger: 'blur' }]
      },
      RepairManagementType: '1',
      partCode: '',
      opCode: '',
      opCodeS: [],
      stationArr: [],
      RepairManagementDataLogTable: [],
      RepairManagementDataTableOrigin: [],
      engineValue: {
        OpName: null,
        EngineID: null, // 产品编号
        EngineType: null, // 产品型号
        EngineTypeID: null, // 机型代码
        PalletCode: null,
        ProcessCode: null, // 程序号
        PartPalletCode: null, // 托盘号
        PalletInfo: null, // 托盘信息
        RepairPartStatusPLC: null,
        QualityMask: null,
        OrderForm: null, // 订单号
        EngineTypeString: null // 产品型号字符串北汽专用
      }
    }
  },
  created() {
    if(localStorage.getItem('userInfo') === '' || localStorage.getItem('userInfo') === null) {
      alert('账号失效，请重新登录')
      this.$router.push('/')
    }
    // 获取今日日期
    const today = new Date();
    this.minDate = new Date(today.getFullYear(), today.getMonth() - 1, today.getDate());
    this.maxDate = new Date(today.getFullYear(), today.getMonth() + 1, today.getDate());

    this.userInfo = localStorage.getItem('userInfo') === '' ? {} : JSON.parse(localStorage.getItem('userInfo'))
    this.dateTime = [getBeforeOrAfterTime(-7), getNowTime2()]
    this.dateTimeShowInfo = this.dateTime[0] + ' ~ ' + this.dateTime[1]
    this.dateTimeDefault = [new Date(getBeforeOrAfterTime(-7)), new Date(getNowTime2())]
  },
  mounted() {

    document.getElementById('topPageName').innerText = '历史查询'
    this.$refs.barcode.focus()
    this.getTable2()
  },
  methods: {
    forbid(){
      //禁止软键盘弹出
      document.activeElement.blur();
    },
    getTable2() {
      this.RepairManagementDataLogTable = []
      const param = []
      param[0] = ['产品编号', this.barcode]
      param[1] = ['开始日期', this.dateTime[0]]
      param[2] = ['结束日期', this.dateTime[1]]
      param[3] = ['状态', this.statusNumberValue]
      param[4] = ['PageCurrent', 1]
      param[5] = ['PageSize', 50]
      param[6] = ['PageCount', '1111', 'int', '1']
      param[7] = ['ItemCount', '1111', 'int', '1']
      const Data = this.CreateData('11', 'CATL_OCC_历史_查询_分页', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data.result && response.data.result.length > 0) {
          this.RepairManagementDataLogTable = response.data.result
        } else {
          this.RepairManagementDataLogTable = []
          Toast.fail('不存在NC项目！')
        }
      })
    },
    showFile(item) {
      const param = []
      param[0] = ['ID', item.ID]
      const Data = this.CreateData('11', 'CATL_OCC_历史附件列表_查询', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data.length > 0) {
          try {
            for (let i = 0; i < response.data.length; i++) {
              if(!/\.(jpg|jpeg|png|GIF|JPG|PNG)$/.test(response.data[i]['附件类型'])) {
                response.data[i]['url'] = window.URL.createObjectURL(base64ImgtoFile(response.data[i]['附件内容']))
              }
            }
          } catch (e) {
          }
          this.RepairManagementDataTableOrigin = response.data
          this.showTableData_content_exchange = true
        } else {
          this.showTableData_content_exchange = true
          this.RepairManagementDataTableOrigin = []
        }
      })
    },
    showPic(item) {
      ImagePreview({
        images: [
          item.url
        ]
      });
    },
    beforeRead(file) {
      const imgformat = /image\/(png|jpg|jpeg)$/;
      if (!imgformat.test(file.type)) {
        Toast.fail('请上传 jpg/jpeg/png 格式图片');
        return false;
      }
      if (file.size > 20 * 1024 * 1024) {
        Toast.fail('文件大小不能超过 20M');
        return false;
      }
      return true
    },
    afterRead(file){
      let canvas = document.createElement('canvas'); // 创建Canvas对象(画布)
      let context = canvas.getContext('2d');
      let img = new Image();
      img.src = file.content;                         // 指定图片的DataURL(图片的base64编码数据)
      img.onload = function () {
        // 画布大小 这里的this指向img
        canvas.width = this.width;
        canvas.height = this.height;
        context.drawImage(img, 0, 0, this.width, this.height);  // 图片大小
        // file.content = canvas.toDataURL(file.file.type, 0.3);   // 0.92为默认压缩质量
        const dataurl = canvas.toDataURL(file.file.type, 0.5);   // 0.92为默认压缩质量

        var arr = dataurl.split(','),
          mime = arr[0].match(/:(.*?);/)[1],
          bstr = atob(arr[1]),
          n = bstr.length,
          u8arr = new Uint8Array(n);
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
        }
        var fileNew = new File([u8arr], file.file.name, {type: mime});

        forms = new FormData()
        forms.append("file", fileNew); //获取上传图片信息
      };

    },
    solveNc(row) {
      this.showTableData_content_exchange1 = true
      this.RepairManagementReplaceForm.ID = row.ID
      this.uploader = []
    },
    reportPicUpload() {
      //如果文件列表为空，则不需要调用上传
      if(this.uploader == null || this.uploader.length === 0){
        return
      }
      var param = []
      param[0] = ['OCC_ID', this.RepairManagementReplaceForm.ID]
      param[1] = ['文件名称', '']
      param[2] = ['文件后缀', '']
      param[3] = ['文件内容', null]
      var Data1 = this.CreateData('15', 'CATL_OCC_历史附件_增加', param)
      this.Data.param = Data1
      axios({
        method: "post",
        url: window.dt_Config.requestConfig,
        params: this.Data,
        data: forms,
      }).then((res) => {
        if(res.status === 200){
          Toast.success('附件上传成功！')
          this.getTable2()
          this.showTableData_content_exchange1 = false
        }else{
          Toast.fail('附件上传失败！');
        }
      })
    },
    confirmFnDate(date) {
      this.dateTimeShow = false
      this.dateTime=[formatDate(date[0]), formatDate(date[1])]
      this.dateTimeShowInfo= this.dateTime[0] + ' ~ ' + this.dateTime[1]
      this.getTable2()
    }
  }
}
</script>

<style scoped>
.app-container{
  margin-top: 50px;
}
.dialog-content {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.dialog-header,
.dialog-footer {
  position: sticky;
  z-index: 10;
}

.dialog-header {
  top: 0;
  background-color: white;
  padding-top: 26px;
  font-weight: 500;
  line-height: 24px;
  text-align: center;
}

.dialog-footer {
  bottom: -3px;
  background-color: white;
  text-align: center;
  margin-top: 10px;
  display: flex;
}

.scrollable-content {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}
</style>
