<template>
  <main class="m-20">
    <div class="wrap text-black">
      <!--顶部搜索-->
      <el-row class="bg_white searchBox">
        <el-col :span="24">
          <el-form ref="form" :model="filter" label-width="100px" class="m-t-20">
            <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="0"></el-option>
                    <el-option label="未检测" value="1"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="4" :offset="2">
                <el-button type="primary" @click="searchClick">搜索</el-button>
                <el-button type="primary" @click="reset">重置</el-button>
              </el-col>
            </el-row>
          </el-form>
        </el-col>
      </el-row>
      <!--table-->
      <el-row class="bg_white m-t-20">
        <el-col :span="24">
          <el-row class="m-t-20">
            <el-col :span="6" class="m-l-40">
              <el-button type="primary" @click="makeSure(1)">确认</el-button>
              <el-button type="primary" @click="makeSure(0)">反确认</el-button>
            </el-col>
          </el-row>
          <el-table
            class="m-20"
            :data="tableData"
            style="width: auto;"
            border
            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="180" align="center" />
            <el-table-column fixed prop="pur_order_sn" label="采购订单号" width="180" />
            <el-table-column prop="delivery_order_sn" label="送货单号" width="180" fixed />
            <el-table-column prop="source" label="来源系统" />
            <el-table-column prop="supplier" label="供应商/生产厂名" width="180" />
            <el-table-column prop="sku" label="sku/产品型号" width="180" lign="center" />
            <el-table-column prop="name" label="物料名称" align="center" />
            <el-table-column prop="check_status" label="检测状态" align="center" />
            <el-table-column prop label="检测报告" width="180" 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"
                  :on-change="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="confirm_status" label="确认状态" align="center" />
            <el-table-column prop="num" label="送检数量(pcs)" width="180" align="center" />
            <el-table-column prop="depot" label="送货仓库" align="center" />
            <el-table-column prop="supplier_addr" label="供应商地址" width="180" align="center" />
            <el-table-column prop="contact_mobile" label="联络人/电话号码" width="180" align="center" />
            <el-table-column prop="scheck_date" label="送检日期" align="center" />
            <el-table-column prop="check_date" label="检测日期" 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="180" align="center" />
          </el-table>
          <el-row class="p-20">
            <el-pagination
              @size-change="changePageSize"
              @current-change="changePage"
              :current-page="filter.page"
              :page-sizes="[50, 100, 150, 200]"
              :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'
      },
      getRowKeys(row) {
        //记录每行的key值
        return row.id
      },
      select_number: '', //表格select选中的条数
      select_Id: [], //表格select复选框选中的id
      multipleSelection: [],
      multiplearry: []
    }
  },
  computed: {
    api_upload_url() {
      return process.env.VUE_APP_API_BASEURL + 'admin/Upload/file'
    }
  },
  mounted() {
    this.multiplearry = []
  },
  activated() {
    this.getList()
  },
  methods: {
    deleteFile(item) {
      this.$confirm('确认删除该质检报告？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.get('/qorder/delete_report', { id: item.id }).then(res => {
          if (res.errno == 200)
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          this.getList()
        })
      })
    },
    //上传
    handleSuccess(res, file, file_list, item) {
      if (res.status == 200) {
        this.$http.post('qorder/upload_report', { id: 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 {
        file_list.splice(file_list.length - 1, 1)
        this.$message({
          type: 'error',
          message: res.errmsg
        })
      }
    },
    //上传文件限制
    handleChange(file, fileList) {
      this.loading = true
      const isLt5M = file.size / 1024 / 1024 < 10
      if (!isLt5M) {
        this.$message({
          type: 'error',
          message: '上传文件大小不能超过 10MB'
        })
        file = null
        fileList = []
        this.$refs.upload.clearFiles() // 清除前端显示的文件列表
        this.loading = false
      }
    },
    // 勾选
    handleSelectionChange(rows) {
      this.multipleSelection = rows
      this.select_number = this.multipleSelection.length
      this.select_Id = []
      if (rows) {
        rows.forEach(row => {
          if (row) {
            this.select_Id.push(row.id)
          }
        })
      }
      console.log(rows, this.select_number, this.select_Id)
    },
    // 确认
    makeSure(status) {
      if (this.select_Id && this.select_Id.length > 0) {
        //status--0反确认 1确认
        this.$http.get('qorder/list', { ids: this.select_Id.join(','), status: status }).then(res => {
          if (res.errno == 200) {
            this.$message.success('确认成功')
            this.$refs.multipleTable.clearSelection()
          }
        })
      } else {
        this.$message.warning('请先确认勾选，在操作！')
      }
    },
    //搜索
    searchClick() {
      this.filter.page = 1
      this.filter.size = 10
      this.getList()
    },
    // 重置
    reset() {
      this.filter = {
        page: 1,
        size: 10,
        supplier: '',
        pur_order_sn: '',
        sale_order_sn: '',
        delivery_order_sn: '',
        sku: '',
        status: ''
      }
      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
          this.$refs.multipleTable.toggleRowSelection(this.multiplearry)
        }
      })
    },
    // 改变每页请求条数
    changePageSize(size) {
      this.filter.size = size
      this.getList()
    },
    // 翻页
    changePage(page) {
      this.filter.page = page
      this.getList()
    },
    // 删除
    deleteClick(row, index) {
      ElMessageBox.confirm('确认删除该专利？', '提示', {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            this.$http.delete('copyright/delete/id?id=' + row.id).then(res => {
              if (res.status == 200) {
                this.getList()
              } else {
                this.$message({
                  type: 'error',
                  message: res.message
                })
              }
            })
          }
          done()
        }
      })
    },
    // 下载
    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>
.wrap {
  width: auto;
}
</style>