<template>
  <div class="app-container">
    <el-row style="display: flex" :gutter="16">
      <el-col :span="8">
        <el-card style="min-height: 700px">
          <el-form
            :model="queryParams"
            ref="queryForm"
            size="small"
            :inline="true"
            v-show="showSearch"
            label-width="70px"
          >
            <el-form-item label="编排单" prop="arrangeCode">
              <el-input
                v-model="queryParams.arrangeCode"
                placeholder="请输入编排单"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="工单编码" prop="workorderCode">
              <el-input
                v-model="queryParams.workorderCode"
                placeholder="请输入工单编码"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                icon="el-icon-search"
                size="mini"
                @click="handleQuery"
                >搜索</el-button
              >
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
                >重置</el-button
              >
            </el-form-item>
          </el-form>

          <el-table
            v-loading="loading"
            :data="tableList"
            height="640px"
            highlight-current-row
            @current-change="handleCurrentChange"
          >
            <!-- <el-table-column type="selection" width="55" align="center" /> -->
            <el-table-column width="50" align="center">
              <template v-slot="scope">
                <!-- 可以手动的修改label的值，从而控制选择哪一项 -->
                <el-radio
                  class="radio"
                  v-model="selectedItemId"
                  :label="scope.row.workorderCode"
                  >{{ '' }}</el-radio
                >
              </template>
            </el-table-column>
            <el-table-column
              label="生产单号"
              align="center"
              prop="workorderCode"
            />
            <el-table-column
              label="销售单号"
              align="center"
              prop="sourceCode"
            />
            <el-table-column
              label="数量"
              width="80"
              align="center"
              prop="quantity"
            />
          </el-table>
        </el-card>
      </el-col>
      <el-col :span="16">
        <el-card style="height: 240px; margin-bottom: 10px">
          <el-button type="primary" plain size="mini" @click="handleProduce"
            >生成</el-button
          >
          <el-form
            :model="produceForm"
            ref="produceForm"
            size="small"
            label-width="130px"
            :rules="rules"
          >
            <el-row>
              <el-col :span="24">
                <el-form-item label="生产单号：" prop="workorderCode">
                  <span>{{ produceForm.workorderCode }}</span>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="包装数量：" prop="packNum">
                  <el-input
                    v-model="produceForm.packNum"
                    placeholder="请输入包装数量"
                    clearable
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="装箱数量：" prop="encasementNum">
                  <el-input
                    v-model="produceForm.encasementNum"
                    placeholder="请输入装箱数量"
                    clearable
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="包装类型：" prop="packType">
                  <el-select v-model="produceForm.packType">
                    <el-option
                      v-for="dict in dict.type.mes_package_type"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="合并包装：" prop="mergePack">
                  <el-radio-group v-model="produceForm.mergePack">
                    <el-radio :label="true">是</el-radio>
                    <el-radio :label="false">否</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="检验员：" prop="checkBy">
                  <el-input
                    v-model="produceForm.checkBy"
                    placeholder="请输入检验员"
                    clearable
                  >
                  <el-button slot="append" @click="userSelectShow" icon="el-icon-search"></el-button>
                  </el-input>
                </el-form-item>
              </el-col>

              <UserSingleSelect ref="userSelect" @onSelected="onUserSelected"></UserSingleSelect>
              <el-col :span="8">
                <el-form-item label="单位类型：" prop="materialsType">
                  <el-select v-model="materialsType">
                    <el-option
                      v-for="dict in dict.type.pro_materials_type"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="录入人：" prop="inputBy">
                  <el-input
                    v-model="produceForm.inputBy"
                    placeholder="请输入录入人"
                    clearable
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="录入时间：" prop="inputTime">
                  <el-date-picker
                    v-model="produceForm.inputTime"
                    type="datetime"
                    style="width: 100%"
                    value-format="yyyy-MM-dd HH:mm"
                    format="yyyy-MM-dd HH:mm"
                    placeholder="请选择录入时间"
                  >
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="备注：">
                  <span>{{ produceForm.remark }}</span>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
        <el-card style="min-height: 450px">
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" plain size="mini" @click="handleSave"
                >保存</el-button
              >
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                size="mini"
                @click="handleChooseTemplate"
                >打印</el-button
              >
            </el-col>
            <right-toolbar
              :showSearch.sync="showSearch"
              @queryTable="getPackageList"
            ></right-toolbar>
          </el-row>
          <el-table
            v-loading="loadingPackage"
            :data="tablePackageList"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column
              label="备注"
              width="150"
              align="center"
              prop="remark"
            >
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.remark"
                  placeholder="请输入备注"
                  clearable
                />
              </template>
            </el-table-column>
            <el-table-column
              label="净重"
              width="150"
              align="center"
              prop="netWeight"
            >
              <template slot-scope="scope">
                <el-input
                  v-model="scope.row.netWeight"
                  placeholder="请输入净重"
                  clearable
                  style="width: 100%"
                />
              </template>
            </el-table-column>
            <el-table-column
              label="指令"
              width="80"
              align="center"
              prop="directive"
            />
            <el-table-column
              label="SIZE"
              width="80"
              align="center"
              prop="standardSize"
            />
            <el-table-column
              label="条码"
              width="150"
              align="center"
              prop="barcode"
            />
            <el-table-column
              label="序号"
              width="80"
              align="center"
              prop="sheetCount"
            />
            <el-table-column
              label="数量"
              width="80"
              align="center"
              prop="packageNum"
            />
            <el-table-column
              label="LOSS数量"
              width="100"
              align="center"
              prop="lossNum"
            />
            <el-table-column
              label="样品数"
              width="100"
              align="center"
              prop="sampleNum"
            />
            <el-table-column
              label="打印次数"
              width="100"
              align="center"
              prop="printTime"
            />
            <el-table-column
              label="超报工"
              width="150"
              align="center"
              prop="isSurplus"
            >
              <template slot-scope="scope">
                {{ scope.row.isSurplus ? '是' : '否' }}
              </template>
            </el-table-column>
            <el-table-column
              label="入库时间"
              prop="warehouseTime"
              align="center"
              width="160"
            />
          </el-table>

          <pagination
            v-show="packageTotal > 0"
            :total="packageTotal"
            :page.sync="queryPackageParams.pageNum"
            :limit.sync="queryPackageParams.pageSize"
            @pagination="getPackageList"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 选择打印模版对话框 -->
    <el-dialog
      title="选择打印模版"
      :visible.sync="visible"
      width="960px"
      append-to-body
    >
      <templatePrint
        ref="templatePrintRef"
        v-if="visible"
        type="single"
        reportType="package_label"
        :operation="false"
      ></templatePrint>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSubmitPrint">确 定</el-button>
        <el-button @click="visible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  workorderList,
  workorderLinkInfo,
  buildPackagePrint,
  workorderPackageList,
  updatePackagePrintRecord,
  packagePrintRecordInfo,
} from '@/api/mes/pro/packageLablePrint'
import templatePrint from '@/views/mes/report/index'
import UserSingleSelect from "@/components/userSelect/checkUser.vue"
import { postBatchPrintPdf } from '@/utils/ruoyi'
export default {
  name: 'packageLablePrint',
  components: { templatePrint ,UserSingleSelect},
  dicts: ['mes_package_type','pro_materials_type'],
  data() {
    return {
      // 查询参数
      queryParams: {
        arrangeCode: null,
        workorderCode: null,
      },
      rules: {
        packType: [
          { required: true, trigger: 'blur', message: '包装类型必选' },
        ],
      },
      // 显示搜索条件
      showSearch: true,
      loading: false,
      tableList: [],
      produceForm: {
        packNum: '',
        checkBy: '',
        mergePack: false,
        packType: '',
        inputBy: '',
        inputTime: '',
        encasementNum: '',
      },
      materialsType: '0',
      loadingPackage: false,
      queryPackageParams: {
        pageNum: 1,
        pageSize: 10,
      },
      tablePackageList: [],
      packageTotal: 0,
      currentData: {},
      selectedItemId: null,
      selectPackageTable: [],
      visible: false,
    }
  },
  created() {
    // this.getList();
  },
  methods: {
    //人员选择返回
    onUserSelected(row){
      this.produceForm.checkBy = row.nickName
    },
    //点击人员选择按钮
    userSelectShow(){
        this.$refs.userSelect.showFlag = true;
    },
    /** 查询工单列表 */
    getList() {
      if (!this.queryParams.arrangeCode && !this.queryParams.workorderCode) {
        this.$message.error('请输入查询条件')
        return
      }
      this.loading = true
      workorderList(this.queryParams).then((response) => {
        console.log(response, 'response')
        this.tableList = response.rows
        this.total = response.total
        this.loading = false
        this.produceForm = {}
        this.selectedItemId = null
      })
    },
    /** 查询标签列表 */
    getPackageList() {
      this.loadingPackage = true
      this.queryPackageParams.workorderId = this.produceForm.workorderId
      workorderPackageList(this.queryPackageParams).then((response) => {
        console.log(response, 'response')
        this.tablePackageList = response.rows
        this.packageTotal = response.total
        this.loadingPackage = false
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    handleSave() {
      if (!this.validSelect()) {
        return
      }
      updatePackagePrintRecord(this.tablePackageList).then((response) => {
        console.log(response, 'response')
        if (response.code === 200) {
          this.getPackageList()
        }
      })
    },
    handleProduce() {
      if (!this.validSelect()) {
        return
      }
      this.$refs['produceForm'].validate((valid) => {
        if (valid) {
          const params = {
            encasementNum: this.produceForm.encasementNum,
            checkBy: this.produceForm.checkBy,
            mergePack: this.produceForm.mergePack,
            packType: this.produceForm.packType,
            inputBy: this.produceForm.inputBy,
            inputTime: this.produceForm.inputTime,
            packNum: Number(this.produceForm.packNum),
            workorderId: this.produceForm.workorderId,
          }
          buildPackagePrint(params).then((response) => {
            console.log(response, 'response')
            if (response.code === 200) {
              this.$message.success('生成成功！')
              this.getPackageList()
            }
          })
        }
      })
    },
    handleChooseTemplate() {
      if (!this.validSelect()) {
        return
      }
      if (this.selectPackageTable.length === 0) {
        this.$message.warning('请至少选择一条数据')
        return
      }
      this.visible = true
    },
    handleSubmitPrint() {
      if (!this.$refs.templatePrintRef.selectedItemId) {
        this.$message.warning('请选择打印模版')
        return
      }
      const forms = new FormData()
      forms.append('workorderId', this.produceForm.workorderId)
      this.selectPackageTable.forEach((item) => {
        forms.append('recordIds', item.recordId)
        forms.append('materialsType',this.materialsType)
      })
      packagePrintRecordInfo(forms).then((response) => {
        console.log(response, 'response')
        if (response.code === 200) {
          const valueList = response.data.map((item) => {
            const obj = {}
            if(item.standardSize) {
              const arr = item.standardSize.split('|')
              if(arr && arr.length > 0){
                arr.forEach((item1, index) => {
                  let [size, jh] = item1.split(":")
                  let zl, loss
                  if (jh) {
                    [zl, loss] = jh.split("+")
                    if(loss) {
                      jh = (Number(zl) + Number(loss)) + ''
                    } else {
                      jh = zl
                    }
                  }
                  obj['size' + (index + 1)] = size
                  obj['zl' + (index + 1)] = zl
                  obj['loss' + (index + 1)] = loss
                  obj['jh' + (index + 1)] = jh
                })
              }
            }
            return {
              packagePrint: item,
              standardSizeobj: obj
            }
          })
          postBatchPrintPdf(
            this.$refs.templatePrintRef.currentData.name,
            valueList
          ).then(() => {
            this.visible = false
            this.getPackageList()
          })
        }
      })
    },
    validSelect() {
      if (this.selectedItemId) {
        return true
      }
      this.$message.warning('请选择生产工单')
      return false
    },
    handleCurrentChange(row) {
      console.log(row, 'row88')
      workorderLinkInfo({ workorderId: row.workorderId }).then((response) => {
        console.log(response, 'response')
        if (response.code === 200) {
          row.mergePack = row.mergePack ? Number(row.mergePack) === 1 ? true : false : false
          row.packType = typeof response.data.packType === 'number' ? response.data.packType + '' : response.data.packType
          this.produceForm = Object.assign({}, row)
          this.produceForm
          // this.produceForm.packNum = response.data.packNum
          // this.produceForm.encasementNum = response.data.encasementNum || ''
          this.$set(
            this.produceForm,
            'packNum',
            response.data.usagePackNum || ''
          )
          this.$set(
            this.produceForm,
            'encasementNum',
            response.data.usageEncasementNum || ''
          )
          this.selectedItemId = row.workorderCode
          this.queryPackageParams = {
            pageNum: 1,
            pageSize: 10,
          }
          this.getPackageList()
        }
      })
    },
    handleSelectionChange(selection) {
      this.selectPackageTable = selection
    },
  },
}
</script>

<style lang="scss" scoped>
</style>

