<template>
  <el-card v-loading.fullscreen="loadingOne" element-loading-background="rgba(0, 0, 0, 0.3)" :element-loading-text="loadingText">
    <el-form :model="queryParams" ref="queryForm" :inline="true">
      <el-form-item label="订单号" prop="contractCode">
        <el-input placeholder="请输入" v-model="queryParams.contractCode" clearable size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="万里牛单号" prop="tradeNo">
        <el-input placeholder="请输入" v-model="queryParams.tradeNo" clearable size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="BOM品号" prop="specCode">
        <el-input placeholder="请输入" v-model="queryParams.specCode" clearable size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="BOM品名" prop="nameChinese">
        <el-input placeholder="请输入" v-model="queryParams.nameChinese" clearable size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="事业部" prop="subsidiaryId">
        <el-select v-model="queryParams.subsidiaryId" placeholder="请选择事业部" size="small" style="width: 100%" @change="handleQuery">
          <el-option v-for="item in companyList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="投产时间">
        <el-col :span="11">
          <el-date-picker
            v-model="queryParams.beginTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="开始日期"
            size="small"
            style="width: 100%"
          >
          </el-date-picker>
        </el-col>
        <el-col :span="2" style="text-align: center">-</el-col>
        <el-col :span="11">
          <el-date-picker
            v-model="queryParams.endTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="结束日期"
            size="small"
            style="width: 100%"
          >
          </el-date-picker>
        </el-col>
      </el-form-item>
      <el-form-item>
        <el-button size="small" @click="handleQuery" class="searchBtn">搜索</el-button>
        <el-button size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" style="margin-bottom: 15px">
      <el-button size="mini" @click="clickSetLabel">标签</el-button>
      <el-button size="mini" @click="outExcel">1. 打印备料单</el-button>
      <el-button size="mini" @click="handlePrint1">2. 打印生产面单</el-button>
      <el-button size="mini" @click="clickQuickDelivery">3. 快捷出库</el-button>
      <el-button size="mini" @click="handleComplete">4. 完成备料</el-button>
    </el-row>

    <el-row :gutter="10" style="margin-bottom: 10px">
      <el-col :span="24">
        <span>
          订单数量:
          <span style="margin-left: 4px" v-if="statisticsData && statisticsData.contractCount">{{ Number(statisticsData.contractCount) }}</span>
          <span style="margin-left: 4px" v-else>0</span>
        </span>
        <span style="margin-left: 16px">
          主材数量:
          <span style="margin-left: 4px" v-if="statisticsData && statisticsData.quantity">{{ Number(statisticsData.quantity) }}</span>
          <span style="margin-left: 4px" v-else>0</span>
        </span>
      </el-col>
    </el-row>

    <el-table
      :data="tableList"
      size="small"
      :row-style="{ height: '35px' }"
      :cell-style="{ padding: '0' }"
      v-loading="loading"
      header-row-class-name="tableHeader"
      :row-class-name="tableRowClass"
      @selection-change="handleSelectionChange"
      :cell-class-name="cellClassName"
    >
      <el-table-column type="selection" width="50" />
      <el-table-column label="设计图" prop="workCode" align="left" width="60">
        <template slot-scope="scope">
          <div v-if="scope.row.imgPath && scope.row.dataResource === 1">
            <img
              v-if="!scope.row.imgPath.includes('https')"
              class="img"
              v-lazy="pathPrefix + scope.row.imgPath"
              @click="openFile(pathPrefix + scope.row.imgPath)"
            />
            <img v-else class="img" v-lazy="scope.row.imgPath" @click="openFile(scope.row.imgPath)" />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="事业部" prop="subsidiaryName" align="left" width="120" />
      <el-table-column label="BOM品号" prop="specCode" align="left" width="180">
        <template slot-scope="scope">
          <div>
            <el-tag type="warning" size="mini" v-if="scope.row.bookSign">{{ getName(scope.row) }}</el-tag>
            <span
              style="border-radius: 50%; height: 20px; width: 20px; display: inline-block; background: #f30303; vertical-align: top"
              v-if="scope.row.type === 1"
            >
              <span style="display: block; color: #ffffff; height: 20px; line-height: 20px; text-align: center">补</span>
            </span>
            <span style="cursor: pointer; padding-left: 8px" :style="{ color: scope.row.type === 1 ? 'red' : '#409eff' }">{{ scope.row.specCode }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="BOM品名" prop="nameChinese" align="left" min-width="200" />
      <el-table-column label="件数" width="80">
        <template slot-scope="scope">
          <span>{{ Number(scope.row.quantity) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="投产时间" prop="putTime" align="center" width="140" />
      <el-table-column label="订单号" prop="contractCode" width="150" />
      <el-table-column label="万里牛单号" prop="tradeNo" width="140" />
      <el-table-column label="SKU品名" prop="productColorName" width="280" />
    </el-table>

    <div style="display: none">
      <div style="width: 250px" id="printMini">
        <div v-for="(item, index) in QRcodeList" :key="index">
          <div style="height: 442px; padding-top: 2px; overflow: hidden; position: relative">
            <div style="border-bottom: 1px solid #000; display: flex; align-items: center; justify-content: center" v-if="item.tradeNo">
              <barcode :value="item.tradeNo" :height="50" :width="1.6" />
            </div>
            <div style="border-bottom: 1px solid #000; display: flex; align-items: center; justify-content: center" v-else>
              <barcode :value="item.contractCode" :height="50" :width="1.6" />
            </div>
            <div style="display: flex; align-items: center; justify-content: center">
              <div style="width: 150px; height: 150px; margin-top: 8px" :id="'print' + index" :ref="'print' + index">
                <img src="" alt="" style="vertical-align: middle; height: 100%; width: 100%" />
              </div>
            </div>
            <div style="text-align: center; font-size: 20px; font-weight: 700; padding: 4px 0; border-bottom: 1px solid #000">{{ item.dataForTime }}</div>
            <div style="word-break: break-all; padding: 2px">SKU品号：{{ item.productColorCode }}</div>
            <div style="word-break: break-all; padding: 2px">SKU品名：{{ item.productColorName }}</div>
            <div style="word-break: break-all; padding: 2px">BOM品号：{{ item.specCode }}</div>
            <div style="word-break: break-all; padding: 2px">BOM品名：{{ item.nameChinese }}</div>
            <div v-if="item.contractDataResource === 1" class="one">
              <div class="two">
                <div class="three">万里牛</div>
              </div>
            </div>
          </div>
          <div style="page-break-after: always"></div>
        </div>
      </div>
      <el-button type="primary" size="mini" v-print="'#printMini'" id="printBtnMini"></el-button>
    </div>

    <div style="width: 0px; height: 0px; overflow: hidden">
      <div class="printBomList" id="printBomList">
        <div class="t">生产备料单</div>
        <div class="time" style="text-align: right">
          {{ printTime }}
        </div>
        <table border class="table">
          <thead>
            <tr>
              <td>编号</td>
              <td>物料品号</td>
              <td>物料品名</td>
              <td>数量</td>
              <td>备注</td>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item, index) in printBomList" :key="index">
              <td style="width: 8%">{{ index + 1 }}</td>
              <td style="width: 20%">{{ item.specCode }}</td>
              <td style="width: 35%">{{ item.nameChinese }}</td>
              <td style="width: 12%">{{ item.quantity }}</td>
              <td style="width: 25%"></td>
            </tr>
          </tbody>
        </table>
      </div>
      <el-button type="primary" size="mini" v-print="'#printBomList'" id="printBomListBtn"></el-button>
    </div>

    <!-- 设置标签 -->
    <el-dialog title="设置标签" v-if="openSetLabel" :visible.sync="openSetLabel" width="30%" append-to-body>
      <el-form ref="ruleForm" :model="form" :rules="formRules" label-width="100px">
        <el-form-item label="标签:" prop="bookSign">
          <el-radio-group v-model="form.bookSign">
            <el-radio v-for="(item, index) in bookSignAndNo" :key="index" :label="item.dictKey">{{ item.dictValue }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <div style="width: 100%; text-align: center">
          <el-button type="primary" @click="clickSetLabelSubmit" size="small" v-db-click>确 认</el-button>
          <el-button size="small" @click="openSetLabel = false">取 消</el-button>
        </div>
      </el-form>
    </el-dialog>

    <!-- 快捷出库 -->
    <el-dialog title="快捷出库" v-if="openQuickDelivery" :visible.sync="openQuickDelivery" width="90%" append-to-body>
      <QuickDelivery :selectList="excelList" @clickCancel="clickCancel"></QuickDelivery>
    </el-dialog>
  </el-card>
</template>
<script>
import QRCode from 'qrcodejs2'
import Print from 'vue-print-nb'
import Vue from 'vue'
Vue.use(Print)
import { dateFormat } from '@/util/date.js'
import { getUid } from '@/util/saas.js'
import * as API from '@/api/shengde/productionSystem/productionOperation/batching/index'
import { mapGetters } from 'vuex'
import QuickDelivery from '@/components/shengde/quickDelivery/index'
import { getSubsidiaryList } from '@/api/shengde/subsidiary/bill/bill'

export default {
  name: 'stay',
  components: { QuickDelivery },
  data() {
    return {
      pathPrefix: process.env.VUE_APP_IMG_URL,
      queryParams: {
        pageNum: 1,
        pageSize: 9999,
        contractCode: '',
        tradeNo: '',
        specCode: '',
        nameChinese: '',
        beginTime: '',
        endTime: '',
        status: '0',
        subsidiaryId: '',
      },
      loading: false,
      tableList: [],
      // tableHeight: '',
      total: null,
      printIdList: [], //要打印生产面单的id集合
      loadingOne: false,
      loadingText: '请稍后',
      QRcodeDialog: false,
      QRcodeList: [],
      excelList: [], //选中的完整数据
      showPrint: false,
      printBomList: [],
      printTime: '',
      uidList: [], //唯一uid集合
      bookSign: [],
      bookSignAndNo: [{ dictKey: '0', dictValue: '无' }],
      form: { bookSign: '' },
      formRules: {
        bookSign: [{ required: true, message: '请选择标签', trigger: 'change' }],
      },
      openSetLabel: false,
      openQuickDelivery: false,
      statisticsData: {
        quantity: 0,
        contractCount: 0,
      },
      companyList: [],
    }
  },
  created() {
    this.bookSign = this.dictData.filter((item) => item.code === 'book_sign')[0].children
    this.bookSignAndNo = this.bookSignAndNo.concat(this.bookSign)
  },
  mounted() {
    getSubsidiaryList({ pageNum: 1, pageSize: 9999 }).then((res) => {
      this.companyList = res.data.data.records
    })
  },
  computed: mapGetters(['dictData']),
  methods: {
    pageInit() {
      this.getList()
    },
    getList() {
      this.loading = true
      API.list(this.queryParams).then(
        (res) => {
          this.tableList = res.data.data.records
          this.total = res.data.data.total
          this.loading = false
        },
        (err) => {
          console.log('list:' + err)
          this.loading = false
        }
      )
      API.bladeStatistics(this.queryParams).then((res) => {
        this.statisticsData = res.data.data
      })
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.queryParams.beginTime = ''
      this.queryParams.endTime = ''
      this.resetForm('queryForm')
      this.handleQuery()
    },

    handleComplete() {
      if (!this.excelList.length > 0) return this.msgInfo('请选择要完成的备料单！')
      let arr = this.excelList.map((item) => item.id)
      this.$confirm('请先确认是否已经打印【备料单】与【生产面单】', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        this.$confirm('确认完成备料吗？', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          API.completeBatch(arr).then(() => {
            this.msgSuccess('操作成功！')
            this.handleQuery()
          })
        })
      })
    },
    outExcel() {
      if (!this.excelList.length > 0) return this.msgInfo('请选择要打印的备料单！')
      this.printTime = ''
      let arr = this.sortOut(this.excelList, 'bomColorId') //根据bom规格id进行数据归类
      //对相同的bom规格id的数据中的数量进行汇总
      arr.sort((a, b) => b.sort - a.sort)
      for (let i = 0; i < arr.length; i++) {
        const iele = arr[i]
        let sum = 0
        for (let j = 0; j < iele.children.length; j++) {
          const jele = iele.children[j]
          sum = sum + Number(jele.quantity)
        }
        iele.quantity = sum
      }
      this.printBomList = arr
      this.$nextTick(() => {
        this.$confirm('确认打印吗？', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          this.printTime = dateFormat(new Date())
          const btn = document.getElementById('printBomListBtn')
          btn.click()
        })
      })
    },
    sortOut(arr, att) {
      let newArr = []
      arr.forEach((oldItem) => {
        let index = -1
        let bomColorId = oldItem[att]
        let alreadyExists = newArr.some((newItem, j) => {
          if (bomColorId === newItem[att]) {
            index = j
            return true
          }
        })
        if (!alreadyExists) {
          let bomColorId = oldItem[att]
          newArr.push({
            bomColorId,
            specCode: oldItem.specCode,
            nameChinese: oldItem.nameChinese,
            sort: oldItem.dataResource,
            quantity: 0,
            children: [
              {
                ...oldItem,
              },
            ],
          })
        } else {
          newArr[index].children.push({
            ...oldItem,
          })
        }
      })
      return newArr
    },
    handlePrint1() {
      if (this.excelList.length > 0) {
        if (!this.printIdList.length > 0) return this.msgInfo('选择的数据没有主材！')
      } else {
        return this.msgInfo('请选择要打印的主材！')
      }
      let num = 0
      for (let i = 0; i < this.excelList.length; i++) {
        if (this.excelList[i].dataResource === 1) {
          num = Number(num) + Number(this.excelList[i].quantity)
        }
      }
      if (num > 100) {
        this.msgInfo('一次性打印件数超过100件')
      } else {
        API.getQRcode(this.printIdList).then((res) => {
          const list = res.data.data.list
          for (let i = 0; i < list.length; i++) {
            const ele = list[i]
            let uid = getUid()
            ele.uid = uid
          }
          this.QRcodeList = list
          this.$nextTick(() => {
            for (let i = 0; i < this.QRcodeList.length; i++) {
              let element = this.QRcodeList[i]
              this.$refs['print' + i][0].innerHTML = '' //清除二维码方法一
              let text = element.contractProductId + '-' + element.uid
              new QRCode(this.$refs['print' + i][0], {
                text: text, //页面地址 ,如果页面需要参数传递请注意哈希模式#
                width: 150,
                height: 150,
                colorDark: '#000000',
                colorLight: '#ffffff',
                correctLevel: QRCode.CorrectLevel.H,
              })
            }
          })
          this.$confirm('确认打印吗？', '警告', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }).then(() => {
            const btn = document.getElementById('printBtnMini')
            btn.click()
          })
        })
      }
    },
    tableRowClass({ row }) {
      if (row.type === 1) {
        return 'red'
      } else return ''
    },
    handleSelectionChange(selection) {
      this.printIdList = selection.filter((item) => item.dataResource === 1).map((item) => item.id)
      this.excelList = selection
    },
    openFile(path) {
      window.open(path)
    },
    cellClassName(val) {
      if (val && val.row && val.row.dataResource === 0) {
        return 'colorDim'
      }
    },
    clickSetLabel() {
      if (!this.excelList.length > 0) return this.msgInfo('请选择要设置标签的列表数据!')
      this.form = { bookSign: '' }
      this.openSetLabel = true
    },
    clickSetLabelSubmit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          let data = []
          if (this.form.bookSign === '0') {
            data = this.excelList.map((item) => {
              return {
                id: item.id,
                bookSign: '',
              }
            })
          } else {
            data = this.excelList.map((item) => {
              return {
                id: item.id,
                bookSign: this.form.bookSign,
              }
            })
          }
          API.burdeningLabel(data).then(() => {
            this.msgSuccess('保存完成')
            this.openSetLabel = false
            this.getList()
          })
        }
      })
    },
    getName(row) {
      return this.selectConstantsLabel(this.bookSign, row.bookSign)
    },
    clickQuickDelivery() {
      if (!this.excelList.length > 0) return this.msgInfo('请选择要进行快捷出库的数据!')
      this.openQuickDelivery = true
    },
    clickCancel(status) {
      this.openQuickDelivery = false
      if (status) {
        this.getList()
      }
    },
  },
}
</script>
<style>
@media print {
  @page {
    size: auto;
    margin: 5mm;
  }
  body,
  html {
    height: auto !important;
  }
}
</style>
<style lang="scss" scoped>
::v-deep {
  .vue-barcode-element {
    text {
      font-size: 20px !important;
      font-weight: 700;
    }
  }
  .el-button {
    border-radius: 0;
  }
  .miniBtn .el-button {
    padding: 0px !important;
  }
  .tableHeader th {
    background-color: #edf0f5;
    height: 35px;
    padding: 0;
  }
  .colorDim {
    color: #909399;
  }
  .el-dialog {
    margin: 0 auto;
    margin-top: 10px !important;
  }
}
.img {
  margin-top: 3px;
  width: 40px;
  height: 40px;
  cursor: pointer;
  object-fit: contain;
  vertical-align: middle;
}
.one {
  position: absolute;
  right: 10px;
  top: 320px;
  width: 70px;
  height: 70px;
  z-index: 99;
  line-height: 80px;
  text-align: center;
  border-radius: 50%;
  border: 1px solid #000;
  .two {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 60px;
    height: 60px;
    line-height: 60px;
    text-align: center;
    border-radius: 50%;
    border: 1px dashed #000;
    .three {
      rotate: -45deg;
      font-size: 14px;
    }
  }
}
.searchBtn {
  background: #20b2aa;
  color: #fff;
  border: 1px solid #20b2aa;
}
.codeList {
  width: 340px;
  .item {
    margin-top: 15px;
    border: 1px solid #000;
    height: 510px;
    overflow: hidden;
    position: relative;
    .top {
      .QRbox {
        border-bottom: 1px solid #000;
        padding: 4px 8px;
        display: flex;
        height: 270px;
        .img {
          width: 200px;
          height: 200px;
          img {
            vertical-align: middle;
            width: 100%;
            height: 100%;
          }
        }
      }

      .productInfo {
        display: flex;
        flex-direction: column;
        padding: 5px 10px;
        .title1 {
          margin-bottom: 5px;
          font-size: 12px;
          .val {
            font-size: 12px;
            font-weight: 700;
          }
        }
      }
      .address {
        padding: 5px 10px;
        display: flex;
        align-items: center;
        border-top: 1px dashed #000;
      }
    }
    .seal {
      position: absolute;
      right: 10px;
      top: 320px;
      width: 70px;
      height: 70px;
      z-index: 99;
      line-height: 80px;
      text-align: center;
      border-radius: 50%;
      border: 1px solid #000;

      .wln {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 60px;
        height: 60px;
        line-height: 60px;
        text-align: center;
        border-radius: 50%;
        border: 1px dashed #000;
        .aa {
          rotate: -45deg;
          font-size: 14px;
        }
      }
    }
    .two-sided {
      width: 40px;
      height: 40px;
      line-height: 40px;
      text-align: center;
      border: 1px solid #000;
      position: absolute;
      right: 20px;
      top: 400px;
      .wln {
        width: 30px;
        height: 30px;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        line-height: 30px;
        text-align: center;
        border: 1px dashed #000;
      }
    }
  }
}
.printBomList {
  width: 100vw;
  .t {
    text-align: center;
    font-size: 26px;
    font-weight: 700;
    margin: 10px 0px;
  }
  .time {
    // font-size: 16px;
    margin-bottom: 10px;
    // font-weight: 500;
  }
  .table {
    width: 100%;
    td {
      padding: 10px;
    }
  }
}
.red {
  color: red !important;
}
</style>
