<template>
  <main>
    <div class="wrap text-black gyszj">
      <!--顶部搜索-->
      <el-row class="bg_white searchBox">
        <el-col :span="24" style="margin-top:20px">
          <el-form ref="form" :model="filter" label-width="100px">
            <el-row>
              <el-col :span="6">
                <el-form-item label="供应商" prop>
                  <el-input v-model="filter.supplier" placeholder="请输入单个供应商名称查询"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="采购订单号" prop>
                  <el-input v-model="filter.pur_order_sn" placeholder="仅支持单个采购订单号"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="销售订单号" prop>
                  <el-input v-model="filter.sale_order_sn" placeholder="仅支持单个销售订单号"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="送货单号" prop>
                  <el-input v-model="filter.delivery_order_sn" placeholder="仅支持单个送货单号"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="sku/产品型号" prop>
                  <el-input v-model="filter.sku" placeholder="搜索多个sku时用逗号隔开"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="检测状态" prop>
                  <el-select v-model="filter.status" placeholder="请选择检测状态">
                    <el-option label="全部" value="-1"></el-option>
                    <el-option label="已检测" value="1"></el-option>
                    <el-option label="未检测" value="0"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="4" :offset="2" style="display: flex; align-items: center;">
                <el-button type="primary" size="mini" @click="searchClick">搜索</el-button>
                <el-button type="primary" size="mini" @click="reset">重置</el-button>
              </el-col>
            </el-row>
          </el-form>
        </el-col>
      </el-row>
      <!--table-->
      <el-row class="bg_white">
        <el-col :span="24">
          <el-row class="m-t-10">
            <el-col :span="6" class="m-l-40">
              <el-button type="primary" @click="makeSure(1)" size="mini">确认</el-button>
              <el-button type="primary" @click="makeSure(0)" size="mini">反确认</el-button>
              <el-button type="primary" size="mini">
                <el-upload :action="api_upload_url" :with-credentials="true"
                  :on-success="function (res, file, file_list) { return manyhandleSuccess(res, file, file_list) }"
                  :show-file-list="false" name="file" ref="upload" v-loading.fullscreen.lock="loading"
                  :beforeUpload="manyhandleChange">
                  <span class="text_blue Cursor" style="color:white">批量上传</span>
                </el-upload>
              </el-button>
              <el-button type="primary" @click="manydelet()" size="mini">批量删除</el-button>
            </el-col>
          </el-row>
          <el-table class="m-20" :data="tableData" style="margin-bottom: 10px;padding-right: 40px;" border height="620"
            ref="multipleTable" :header-cell-style="header_style" @selection-change="handleSelectionChange"
            :row-key="getRowKeys">
            <el-table-column type="selection" :reserve-selection="true" width="55" align="center"></el-table-column>
            <el-table-column fixed prop="sale_order_sn" label="销售订单号" width="150" />
            <el-table-column fixed prop="pur_order_sn" label="采购订单号" width="150" />
            <el-table-column fixed prop="delivery_order_sn" label="送货单号" width="120" align="center" />
            <el-table-column fixed prop label="检测报告" width="150" align="center">
              <template #default="scope">
                <el-upload v-if="!scope.row.report_url" :action="api_upload_url" :with-credentials="true"
                  :on-success="function (res, file, file_list) { return handleSuccess(res, file, file_list, scope.row) }"
                  :show-file-list="false" name="file" ref="upload" v-loading.fullscreen.lock="loading"
                  :beforeUpload="handleChange">
                  <span class="text_blue Cursor m-r-10">上传</span>
                </el-upload>
                <div v-else>
                  <span @click="downloadTemplate(scope.row)" class="text_blue Cursor m-r-10">下载</span>
                  <span @click="deleteFile(scope.row, scope.$index)" class="text_blue Cursor">删除</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="source" label="来源系统" width="120" />
            <el-table-column prop="supplier" label="供应商/生产厂名" width="220" />
            <el-table-column prop="sku" label="sku/产品型号" width="220" />
            <el-table-column prop="name" label="物料名称" width="210" />
            <el-table-column prop="check_status" label="检测状态" width="90" align="center" />
            <el-table-column prop="confirm_status" label="确认状态" width="90" align="center" />
            <el-table-column prop="num" label="送检数量(pcs)" width="130" align="center" />
            <el-table-column prop="depot" label="送货仓库" width="220" align="center" />
            <el-table-column prop="supplier_addr" label="供应商地址" width="220" />
            <el-table-column prop="contact_mobile" label="联络人/电话号码" width="220" />
            <el-table-column prop="scheck_date" label="送检日期" width="180" align="center" />
            <el-table-column prop="check_date" label="检测日期" width="180" align="center" />
            <el-table-column prop="check_user" label="检测人" align="center" />
            <el-table-column prop="confirm_name" label="确认人" align="center" />
            <el-table-column prop="remark" label="备注" width="300">
              <template #default="scope">
                <el-input v-model="scope.row.remark" @blur="remarkChange($event, scope.row)" maxlength="80"></el-input>
              </template>
            </el-table-column>
          </el-table>
          <el-row style="margin-bottom: 10px;float: right;">
            <el-pagination @size-change="changePageSize" @current-change="changePage" :current-page="filter.page"
              :page-sizes="[50, 100, 200, 300]" :page-size="filter.size" layout="total, sizes, prev, pager, next, jumper"
              :total="total"></el-pagination>
          </el-row>
        </el-col>
      </el-row>
    </div>
  </main>
</template>
<script>
import { ElMessageBox } from 'element-plus'
import axios from 'axios'
export default {
  name: 'copyRight',
  data () {
    return {
      loading: false,
      api_upload_url: '',
      fileList: [], //上传的文件列表
      header_style: {
        'background-color': '#F5F7FA',
        color: '#606266',
        fontSize: '14px',
        fontWeight: '600',
        textAlign: 'center'
      },
      form: {},
      tableData: [],
      currentPage: 1,
      total: 0,
      filter: {
        page: 1,
        size: 50,
        supplier: '',
        pur_order_sn: '',
        sale_order_sn: '',
        delivery_order_sn: '',
        sku: '',
        status: '-1'
      },
      select_number: '', //表格select选中的条数
      select_Id: [], //表格select复选框选中的id
      multipleSelection: []
    }
  },
  computed: {
    api_upload_url () {
      return process.env.VUE_APP_API_BASEURL + 'admin/Upload/file'
    }
  },
  mounted () {
    this.getList()
  },
  // activated () {
  //   this.getList()
  // },
  methods: {
    // 批量删除
    manydelet () {
      if (this.select_Id && this.select_Id.length > 0) {
        ElMessageBox.confirm('你是否确定将所选行中的质检报告删除？', '提示', {
          type: 'warning',
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
              this.$http.get('qorder/delete_report?ids=' + this.select_Id).then(res => {
                if (res.errno == 200) {
                  this.$message.success('删除成功')
                  this.$refs.multipleTable.clearSelection()
                  this.getList()
                }
              })
            }
            done()
          }
        })
      } else {
        this.$message({
          message: '请先选择需要删除报告的质检单',
          type: 'warning'
        })
      }
    },
    getRowKeys (row) {
      //记录每行的key值
      return row.id
    },
    // 修改备注
    remarkChange (val, item) {
      this.$http.post('qorder/edit', { id: item.id, remark: item.remark }).then(res => {
        if (res.errno === 200) {
          this.getList()
        }
      })
    },
    deleteFile (item) {
      this.$confirm('确认删除该质检报告？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.get('qorder/delete_report?ids=' + item.id).then(res => {
          if (res.errno == 200)
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          this.getList()
        })
      })
    },
    // 批量上传
    manyhandleSuccess (res, file, file_list) {
      this.loading = true
      const ids = []
      this.multipleSelection.forEach((it, index) => {
        ids.push(it.id)
      })
      if (res.status == 200) {
        if (this.select_Id && this.select_Id.length > 0) {
          this.$http.post('qorder/upload_report', { ids: ids.join(), report_url: res.data.imgpath }).then(ress => {
            if (ress.errno == 200) {
              this.getList()
              this.$message({
                type: 'success',
                message: ress.errmsg
              })
              this.$refs.multipleTable.clearSelection()
            } else {
              this.$message({
                type: 'error',
                message: ress.errmsg
              })
            }
            this.loading = false
          })
        } else {
          this.$message.warning('请先确认勾选，在操作！')
        }
      } else {
        this.loading = false
        file_list.splice(file_list.length - 1, 1)
        this.$message({
          type: 'error',
          message: res.errmsg
        })
      }
    },
    //上传
    handleSuccess (res, file, file_list, item) {
      this.loading = true
      if (res.status == 200) {
        this.$http.post('qorder/upload_report', { ids: item.id, report_url: res.data.imgpath }).then(ress => {
          if (ress.errno == 200) {
            this.getList()
            this.$message({
              type: 'success',
              message: ress.errmsg
            })
          } else {
            this.$message({
              type: 'error',
              message: ress.errmsg
            })
          }
          this.loading = false
        })
      } else {
        this.loading = false
        file_list.splice(file_list.length - 1, 1)
        this.$message({
          type: 'error',
          message: res.errmsg
        })
      }
    },
    //批量上传文件限制
    manyhandleChange (file) {
      this.loading = true
      if (!this.select_Id || this.select_Id.length === 0) {
        this.$message({
          message: '请先选择需要上传报告的质检单',
          type: 'warning'
        })
        this.loading = false
        return false
      }
      const isLt2M = file.size / 1024 / 1024 < 10
      if (!isLt2M) {
        this.$message({
          message: '上传文件大小不能超过 10MB!',
          type: 'warning'
        })
        this.loading = false
      }
      return isLt2M
    },
    //上传文件限制
    handleChange (file) {
      this.loading = true
      const isLt2M = file.size / 1024 / 1024 < 10
      if (!isLt2M) {
        this.$message({
          message: '上传文件大小不能超过 10MB!',
          type: 'warning'
        })
        this.loading = false
      }
      return isLt2M
    },
    // 勾选
    handleSelectionChange (rows) {
      this.multipleSelection = rows
      if (rows.length === 1 && Object.keys(this.multipleSelection[0]).length == 0) {
        this.select_number = 0
      } else {
        this.select_number = this.multipleSelection.length
      }
      this.select_Id = []
      if (rows) {
        rows.forEach(row => {
          if (row && (row.id || row.id == 0)) {
            this.select_Id.push(row.id)
          }
        })
      }
    },
    // 确认
    makeSure (status) {
      if (this.select_Id && this.select_Id.length > 0) {
        //status--0反确认 1确认
        this.$http.get('qorder/confirm', { ids: this.select_Id.join(','), status: status }).then(res => {
          if (res.errno == 200) {
            this.$message.success('确认成功')
            this.$refs.multipleTable.clearSelection()
            this.getList()
          }
        })
      } else {
        this.$message.warning('请先确认勾选，在操作！')
      }
    },
    //搜索
    searchClick () {
      this.filter.page = 1
      this.getList()
    },
    // 重置
    reset () {
      this.filter = {
        page: 1,
        size: 50,
        supplier: '',
        pur_order_sn: '',
        sale_order_sn: '',
        delivery_order_sn: '',
        sku: '',
        status: '-1'
      }
      this.isCopyright = true
      this.getList()
    },
    //版权list
    getList () {
      this.$http.get('qorder/list', this.filter).then(res => {
        if (res.errno == 200) {
          this.tableData = res.data.data
          this.total = res.data.total
        }
      })
    },
    // 改变每页请求条数
    changePageSize (size) {
      this.filter.size = size
      this.getList()
    },
    // 翻页
    changePage (page) {
      this.filter.page = page
      this.getList()
    },
    // 下载
    downloadTemplate (data) {
      this.$message({
        type: 'success',
        message: '正在下载，请稍后...'
      })
      let url = ''
      if (data == '') {
        url = this.url
      } else {
        url = data.report_url
      }
      axios
        .get(url, {
          responseType: 'blob',
          headers: {
            /*'X-Token': getToken(),*/
            'Content-Type': 'application/json;charset=utf-8'
          }
        })
        .then(res => {
          if (!res) {
            this.$message.error('下载模板文件失败')
            return false
          }
          const stream = res.data // 后端用stream返回Excel文件
          const blob = new Blob([stream])
          // 前端获取业务码，成功执行正常业务
          const downloadElement = document.createElement('a')
          const href = window.URL.createObjectURL(blob) // 创建下载的链接
          downloadElement.href = href
          const timeStamp = new Date().toString()
          const url_arr = res.config.url.split('/')
          const nameStr = decodeURI(url_arr[url_arr.length - 1])
          console.log(nameStr)
          downloadElement.download = nameStr // 下载后文件名
          document.body.appendChild(downloadElement)
          downloadElement.click() // 点击下载
          document.body.removeChild(downloadElement) // 下载完成移除元素
          window.URL.revokeObjectURL(href) // 释放掉blob对象
        })
    }
  }
}
</script>

<style scoped>
::v-deep(.gyszj .el-input__inner) {
  height: 30px;
}

::v-deep(.gyszj .el-form-item) {
  margin-bottom: 5px;
}

::v-deep(.el-form-item__label, .el-form-item__label) {
  font-size: 12px;
}

::v-deep(.gyszj .el-table .el-table__cell) {
  padding: 0;
  font-size: 12px;
}

::v-deep(.gyszj .el-table) {
  font-size: 12px;
}

.wrap {
  width: auto;
}

.bg_white {
  overflow: hidden;
}
</style>