<template>
  <div class="app-container">
    <el-card class="topCard">
      <div class="topDiv">
        <span style="margin-left: 10px">产品编号：</span>
        <el-input v-model="barcode" style="width:200px;" clearable placeholder="" size="small"/>
        <span style="margin-left: 10px">日期：</span>
        <el-date-picker
          v-model="dateTime"
          :clearable="false"
          size="small"
          type="daterange"
          align="center"
          style="width: 240px;"
          value-format="yyyy-MM-dd"
          format="yyyy-MM-dd"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="getTable2()"/>
        <span style="margin-left: 10px">状态：</span>
        <el-select v-model="solveStatus" placeholder="请选择状态" size="small" style="width: 120px" @change="pageCurrent=1;getTable2()">
          <el-option
            v-for="item in solveStatusList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            size="mini"/>
        </el-select>
        <el-button type="primary" plain size="small" icon="el-icon-search" style="margin-left: 10px" @click="pageCurrent=1;getTable2()">查询</el-button>
        <!--        <el-button type="warning" size="small" icon="el-icon-circle-plus" @click="creatOrder('form')">创建NC</el-button>-->
        <!--        <el-button type="success" size="small" plain icon="el-icon-document-copy" @click="copyOrder('form4')">复制物料</el-button>-->
      </div>
      <el-table
        v-loading="loading"
        ref="multipleTable"
        :data="tableData"
        :header-cell-style="{background:'#eef1f6',color:'#606266'}"
        element-loading-text="数据加载中"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.2)"
        class="main"
        tooltip-effect="dark"
        height="650px"
        style="width: 100%"
        border
        size="mini">
        <el-table-column type="index" width="60" label="序号" align="center"/>
        <el-table-column align="center" label="产品编号" width="170">
          <template slot-scope="scope">
            {{ scope.row.产品编号 }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="问题描述">
          <template slot-scope="scope">
            {{ scope.row.备注 }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="记录时间" width="150">
          <template slot-scope="scope">
            {{ scope.row.记录时间 }}
          </template>
        </el-table-column>
        <!--        <el-table-column align="center" label="创建人员">-->
        <!--          <template slot-scope="scope">-->
        <!--            {{ scope.row.创建人员 }}-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column align="center" label="处理方式" width="100">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.放行方式 === ''" size="mini"/>
            <el-tag v-if="scope.row.放行方式 === '合格放行'" size="mini" type="success">{{ scope.row.放行方式 }}</el-tag>
            <el-tag v-if="scope.row.放行方式 === '偏差放行'" size="mini" type="warning">{{ scope.row.放行方式 }}</el-tag>
            <el-tag v-if="scope.row.放行方式 === '返工放行'" size="mini" type="error">{{ scope.row.放行方式 }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" label="附件" width="80">
          <template slot-scope="scope">
            <el-link type="primary" @click="showFileList(scope.row)">{{ scope.row.附件数量 }}</el-link>
          </template>
        </el-table-column>
        <el-table-column align="center" label="解除时间" width="150">
          <template slot-scope="scope">
            {{ scope.row.处理时间 }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="处理备注">
          <template slot-scope="scope">
            {{ scope.row.处理备注 }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="100">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" content="处理NC" placement="bottom">
              <el-button
                v-if="scope.row.合格放行 === 0 && tokenCode1 !== 3"
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="solveNc(scope.row)"/>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="上传附件" placement="bottom">
              <el-button
                v-if="scope.row.合格放行 === 1"
                size="mini"
                type="text"
                icon="el-icon-upload"
                @click="solveNc1(scope.row)"/>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <div class="block" style="margin-top: 10px;">
        <el-pagination
          v-if="!loading"
          :current-page="pageCurrent"
          :page-sizes="[15, 30, 40]"
          :page-size="pageSize"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"/>
      </div>
    </el-card>
    <el-dialog :visible.sync="dialogFormVisible" title="创建NC" center style="min-height: 200px;" width="400px">
      <el-form ref="formAdd" :model="formAdd" :rules="rulesAdd" label-position="right" label-width="110px">
        <el-form-item label="产品编号" prop="productCode" style="display: inline-block">
          <el-input
            v-model="formAdd.productCode"
            size="small"
            style="width: 200px"
            placeholder="请输入/扫描产品编号"/>
        </el-form-item>
        <el-form-item label="工位号" prop="opCode" style="display: inline-block">
          <el-select v-model="formAdd.opCode" size="small" placeholder="请选择工位号" style="width: 200px" @change="searchCheckContentBase">
            <el-option
              v-for="item in stationNumber"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="问题点" prop="problemId" style="display: inline-block">
          <el-select v-model="formAdd.problemId" size="small" placeholder="请选择问题点" style="width: 200px">
            <el-option
              v-for="item in problemList"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="问题描述" prop="remake" style="display: inline-block">
          <el-input
            v-model="formAdd.remake"
            :rows="3"
            type="textarea"
            clearable
            size="small"
            style="width: 200px"
            placeholder="问题描述"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="callOff('formAdd')">取消</el-button>
        <el-button type="primary" size="small" @click="submitAdd('formAdd')">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogFormVisible1" title="申告处理" center style="min-height: 200px;" width="400px">
      <el-form ref="formEdit" :model="formEdit" :rules="rulesEdit" label-position="right" label-width="110px">
        <el-form-item label="处理方式" prop="solveType" style="display: inline-block">
          <el-select v-model="formEdit.solveType" size="small" placeholder="请选择处理方式" style="width: 200px">
            <el-option
              v-for="item in solveTypeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="处理备注" prop="solveRemark" style="display: inline-block">
          <el-input v-model="formEdit.solveRemark" :row="2" type="textarea" style="width: 200px" />
        </el-form-item>
        <el-form-item label="附件" style="display: inline-block">
          <el-upload
            id="invoiceScan"
            ref="uploadPDF"
            :on-remove="handelLimitStyle"
            :on-change="handelLimit"
            :multiple="true"
            :auto-upload="false"
            :on-success="uploadSuccessPDF"
            :before-upload="beforeUploadPdf"
            :on-exceed="warningExceedPdf"
            :limit="limit"
            :data="DataPDF"
            :action="uploadPDF"
            class="custom-upload"
            drag>
            <i class="el-icon-upload"/>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div slot="tip">单次上传一个文件，不超过10mb</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="callOff('formEdit')">取消</el-button>
        <el-button type="primary" size="small" @click="solveNcSubmit('formEdit')">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogFormVisible2" title="上传附件" center style="min-height: 200px;" width="400px">
      <el-form ref="formEdit1" :model="formEdit1" label-position="right" label-width="110px">
        <el-form-item label="附件" style="display: inline-block">
          <el-upload
            id="invoiceScan"
            ref="uploadPDF"
            :on-remove="handelLimitStyle"
            :on-change="handelLimit"
            :multiple="true"
            :auto-upload="false"
            :on-success="uploadSuccessPDF"
            :before-upload="beforeUploadPdf"
            :on-exceed="warningExceedPdf"
            :limit="limit"
            :data="DataPDF"
            :action="uploadPDF"
            class="custom-upload"
            drag>
            <i class="el-icon-upload"/>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div slot="tip">单次上传一个文件，不超过10mb</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="callOff('formEdit1')">取消</el-button>
        <el-button type="primary" size="small" @click="solveNcSubmit1('formEdit1')">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="showTableData_content_exchange" title="附件" center style="min-height: 200px" width="400px">
      <el-row style="height: 300px;overflow: auto;border: 1px solid #bebebe">
        <div v-for="(item, index) in RepairManagementDataTableOrigin" :key="index" style="margin: 10px 0">
          <el-row v-if="/(jpg|jpeg|png|GIF|JPG|PNG)$/i.test(item.附件类型)">
            <el-link type="primary" @click="showPic(item)">
              <span class="tmp">
                {{ index + 1 }}.{{ item.附件名称 }}.{{ item.附件类型 }}
              </span>
            </el-link>
            &nbsp;&nbsp;
            <el-link type="primary" @click="downLoadFile(item)">
              <span class="el-icon-download"/>
            </el-link>
            <div style="height: 1px;background-color: #bebebe;margin-top: 2px" />
          </el-row>
          <el-row v-else>
            <span class="tmp">
              {{ index + 1 }}.{{ item.附件名称 }}.{{ item.附件类型 }}
            </span>
            &nbsp;&nbsp;
            <el-link type="primary" @click="downLoadFile(item)">
              <span class="el-icon-download"/>
            </el-link>
            <div style="height: 1px;background-color: #bebebe;margin-top: 2px" />
          </el-row>
        </div>
      </el-row>
      <el-image-viewer
        v-if="imgViewerVisible"
        :url-list="imgViewerList"
        :on-close="()=>{imgViewerVisible=false}"
        style="z-index: 98965"
      />
    </el-dialog>

  </div>
</template>

<script>
import { url } from '../../../utils/request'
import { base64ImgtoFile, getBeforeOrAfterTime, getNowTime2 } from '../../../utils/tool'
import { mapGetters } from 'vuex'
import elImageViewer from 'element-ui/packages/image/src/image-viewer'
let forms = null // 设置公共变量，用来创建 FromData 对象，把文件带到后台
export default {
  name: 'RepairManagement',
  components: {
    'el-image-viewer': elImageViewer
  },
  data() {
    return {
      imageType: ['bmp', 'jpg', 'png', 'gif'],
      pdfType: ['pdf'],
      imgViewerVisible: false,
      imgViewerList: [],
      solveTypeList: [{ label: '合格放行', value: '合格放行' }, { label: '偏差放行', value: '偏差放行' }, { label: '返工放行', value: '返工放行' }],
      stationNumber: [],
      tableData: [],
      formAdd: {
        productCode: '',
        opCode: '',
        problem: '',
        problemId: '',
        remake: ''
      },
      rulesAdd: {
        productCode: [{ required: true, message: '请输入/扫描产品编号！', trigger: 'blur' }],
        problemId: [{ required: true, message: '请选择问题点！', trigger: 'blur' }],
        remake: [{ required: true, message: '请输入具体问题原因！', trigger: 'blur' }]
      },
      formEdit: {
        ID: 0,
        productCode: '',
        solvePeople: '',
        solveRemark: '',
        solveType: ''
      },
      rulesEdit: {
        solveType: [{ required: true, message: '请选择处理方式！', trigger: 'blur' }]
      },
      formEdit1: {
        ID: 0
      },
      dialogFormVisible: false,
      dialogFormVisible1: false,
      dialogFormVisible2: false,
      solveStatus: 9999,
      solveStatusList: [
        {
          label: '全部',
          value: 9999
        },
        {
          label: '未处理',
          value: 0
        },
        {
          label: '已处理',
          value: 1
        }
      ],
      limit: 1,
      DataPDF: {},
      uploadPDF: url,
      total: 0, // 总条数
      pageList: 30, // 每页显示条数
      pageSize: 30, // 每页显示条数
      pageCurrent: 1, // 后台获取页
      loading: false,
      problemList: [],
      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',
      tokenCode1: '',
      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 // 产品型号字符串北汽专用
      }
    }
  },
  computed: {
    ...mapGetters([
      'name',
      'id',
      'token',
      'tokenCode'
    ])
  },
  created() {
    this.tokenCode1 = parseInt(this.tokenCode)
    this.dateTime = [getBeforeOrAfterTime(-7), getNowTime2()]
    // this.userInfo = localStorage.getItem('userInfo') === '' ? {} : JSON.parse(localStorage.getItem('userInfo'))
  },
  mounted() {
    this.getStationNumber()
    this.getTable2()
  },
  methods: {
    // 工位号
    getStationNumber() {
      this.stationNumber = []
      var param = []
      var Data = this.CreateData('11', 'MES_计划BOM_工位与名称_查询', param)
      this.ExecDatabase(Data).then(response => {
        for (let i = 0; i < response.data.length; i++) {
          this.stationNumber.push({
            label: response.data[i].工位号,
            value: response.data[i].工位号
          })
        }
      })
    },
    searchCheckContentBase(stationNumberValue) {
      this.problemList = []
      this.formAdd.problemId = ''
      var param = []
      param[0] = ['工位号', stationNumberValue]
      var Data = this.CreateData('11', 'CATL_基础_OCC_查询', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data.length !== 0) {
          for (let i = 0; i < response.data.length; i++) {
            this.problemList.push({
              label: response.data[i].问题项目,
              value: response.data[i].ID
            })
          }
          this.formAdd.problemId = response.data[0].ID
        }
      })
    },

    // 查询NC
    getTable2() {
      this.tableData = []
      this.loading = true
      const param = []
      param[0] = ['产品编号', this.barcode]
      param[1] = ['开始日期', this.dateTime[0]]
      param[2] = ['结束日期', this.dateTime[1]]
      param[3] = ['PageCurrent', this.pageCurrent]
      param[4] = ['PageSize', this.pageSize]
      param[5] = ['PageCount', '1111', 'int', '1']
      param[6] = ['ItemCount', '1111', 'int', '1']
      param[7] = ['状态', this.solveStatus]
      const Data = this.CreateData('11', 'CATL_问题申告_查询_分页', param)
      this.ExecDatabase(Data).then(response => {
        if (response.data.result && response.data.result.length > 0) {
          this.tableData = response.data.result
          this.total = parseInt(response.data.output[0].ItemCount)
          this.loading = false
        } else {
          this.tableData = []
          this.loading = false
          this.$message.error('不存在未处理申告！')
        }
      })
    },
    // 新增NC
    creatOrder(formName) {
      if (this.$refs[formName] !== undefined) {
        this.$refs[formName].resetFields()
      }
      this.formAdd.productCode = ''
      this.formAdd.opCode = ''
      this.formAdd.problem = ''
      this.formAdd.problemId = ''
      this.formAdd.remake = ''
      this.dialogFormVisible = true
    },
    // 提交新增NC
    submitAdd(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          var param = []
          param[0] = ['产品编号', this.formAdd.productCode]
          param[1] = ['问题ID', this.formAdd.problemId]
          param[2] = ['备注', this.formAdd.remake]
          param[3] = ['记录人', this.name]
          var Data = this.CreateData('12', 'CATL_OCC_历史_增加', param)
          this.ExecDatabase(Data).then(response => {
            if (response.data[0]['result'] === '1') {
              this.$message({
                message: 'NC记录成功！',
                type: 'success'
              })
              this.dialogFormVisible = false
              this.getTable2()
            } else {
              this.$message.error('NC记录失败！')
            }
          })
        } else {
          return false
        }
      })
    },
    // 取消新增NC
    callOff(formName) {
      this.dialogFormVisible = false
      this.dialogFormVisible1 = false
      this.dialogFormVisible2 = false
      this.$refs[formName].resetFields()
    },
    solveNc(row) {
      this.dialogFormVisible1 = true
      this.formEdit.ID = row.ID
      this.formEdit.solvePeople = this.name
      this.formEdit.solveRemark = ''
    },
    solveNcSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          var param = []
          param[0] = ['ID', this.formEdit.ID]
          param[1] = ['放行方式', this.formEdit.solveType]
          param[2] = ['处理人', this.formEdit.solvePeople]
          param[3] = ['处理备注', this.formEdit.solveRemark]
          var Data = this.CreateData('12', 'CATL_OCC_历史处理_增加', param)
          this.ExecDatabase(Data).then(response => {
            if (response.data[0].result === '1') {
              this.$message.success('处理成功!')
              if (this.$refs.uploadPDF.uploadFiles.length > 0) {
                this.reportPicUpload(this.formEdit.ID)
              } else {
                this.getTable2()
                this.dialogFormVisible1 = false
              }
            } else {
              this.$message.error('处理失败!')
            }
          })
        }
      })
    },
    solveNc1(row) {
      this.dialogFormVisible2 = true
      this.formEdit1.ID = row.ID
    },
    solveNcSubmit1() {
      if (this.$refs.uploadPDF.uploadFiles.length > 0) {
        this.reportPicUpload(this.formEdit1.ID)
      } else {
        this.$message.warning('请选择附件')
      }
    },
    showFileList(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) {
          for (let i = 0; i < response.data.length; i++) {
            if (this.imageType.indexOf(response.data[i]['附件类型'].toLowerCase()) !== -1) {
              response.data[i]['url'] = window.URL.createObjectURL(base64ImgtoFile(response.data[i]['附件内容'], response.data[i]['附件名称'], response.data[i]['附件类型']))
            } else {
              response.data[i]['url'] = window.URL.createObjectURL(base64ImgtoFile(response.data[i]['附件内容'], response.data[i]['附件名称'], response.data[i]['附件类型']))
            }
          }
          this.RepairManagementDataTableOrigin = response.data
          this.showTableData_content_exchange = true
        } else {
          this.RepairManagementDataTableOrigin = []
        }
      })
    },
    showPic(item) {
      this.imgViewerList = [item.url]
      this.imgViewerVisible = true
    },
    downLoadFile(item) {
      const url = item.url
      const fileName = item.附件名称 + '.' + item.附件类型
      const xhr = new XMLHttpRequest()
      xhr.open('GET', url)
      xhr.responseType = 'blob'
      xhr.onload = function() {
        const blob = xhr.response
        const link = document.createElement('a')
        link.href = URL.createObjectURL(blob)
        link.download = fileName
        link.target = '_blank' // 可选，如果希望在新窗口中下载文件，请取消注释此行
        link.click()
      }
      xhr.send()
    },
    afterRead(file) {
      forms = new FormData()
      forms.append('file', file.file) // 获取上传图片信息
    },

    reportPicUpload(OCC_ID) {
      // 如果文件列表为空，则不需要调用上传
      var param = []
      param[0] = ['OCC_ID', OCC_ID]
      param[1] = ['文件名称', '']
      param[2] = ['文件后缀', '']
      param[3] = ['文件内容', null]
      var Data1 = this.CreateData('15', 'CATL_OCC_历史附件_增加', param)
      this.DataPDF.param = Data1
      this.$refs.uploadPDF.submit()
    },
    // 分页
    handleSizeChange(val) {
      this.pageCurrent = 1
      this.pageSize = val
      this.getTable2()
    },
    handleCurrentChange(val) {
      this.pageCurrent = val
      this.getTable2()
    },
    // 给样式的
    handelLimitStyle() {
      var obj = document.getElementsByClassName('el-upload--picture-card')
      if (obj[0].style.display === 'none') {
        for (var i = 0; i < obj.length; i++) {
          obj[i].style.display = 'block'
        }
      }
    },
    handelLimit() {
      var obj = document.getElementsByClassName('el-upload--picture-card')
      if (obj[0].style.display === '') {
        for (var i = 0; i < obj.length; i++) {
          obj[i].style.display = 'none'
        }
      }
    },
    // 上传成功回调
    uploadSuccessPDF(res) {
      this.dialogFormVisible1 = false
      this.dialogFormVisible2 = false
      this.$refs.uploadPDF.clearFiles()
      // var obj = document.getElementsByClassName('el-upload--picture-card')
      // if (obj[0].style.display === 'none') {
      //   for (var i = 0; i < obj.length; i++) {
      //     obj[i].style.display = 'block'
      //   }
      // }
      this.getTable2()
      this.$message.success('文件上传成功!')
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisiblePictureCard = true
    },
    // 上传前检测
    beforeUploadPdf(file) {
      const isLt2M = file.size / 1024 / 1024 < 10
      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过 10MB!')
        return false
      }
      return true
    },
    warningExceedPdf() {
      this.$message.error('一次仅可上传一份文件')
    }
  }
}
</script>

<style scoped>
.tmp {
  white-space:nowrap;/*强制单行显示*/
  text-overflow:ellipsis;/*超出部分省略号表示*/
  overflow:hidden;/*超出部分隐藏*/
  width: 300px;/*设置显示的最大宽度*/
  display:inline-block;
  font-size: 16px;
}
.custom-upload ::v-deep.el-upload-dragger{
  width: 210px;
}
.custom-upload {
  width: 220px;  /* 设置上传框的宽度 */
  height: 150px; /* 设置上传框的高度 */
}

.custom-upload ::v-deep .el-upload {
  width: 100%;
  height: 100%;
}

.custom-upload .el-icon-plus {
  font-size: 28px; /* 图标大小 */
  line-height: 150px; /* 垂直居中对齐 */
}
</style>
