<template>
    <!-- 新增工机具 -->
    <div>
       <el-form
      :model="maForm"
      ref="maForm"
      size="small"
      :inline="true"
      label-width="120px"
    >
      <el-form-item label="类型规格" prop="keyWord">
        <el-input
          v-model="maForm.keyWord"
          placeholder="请输入类型规格"
          clearable
          maxlength="50"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="机具厂家" prop="typeId">
        <el-select
          v-model="maForm.typeId"
          placeholder="请选择机具厂家"
          clearable
          filterable
          style="width: 240px"
        >
          <el-option
            v-for="typeItem in typesList"
            :key="typeItem.typeId"
            :label="typeItem.typeName"
            :value="typeItem.typeId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="出厂日期" prop="arrivalTime">
        <el-date-picker
          v-model="maForm.arrivalTime"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          :picker-options="pickerOptions"
          type="date"
          placeholder="请选择出厂日期"
        ></el-date-picker>
      </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-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleBackAll"
          >驳回</el-button
        >
      </el-col>
    </el-row>

     <el-table
      v-loading="loading"
      :data="equipmentList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column align="center" label="序号" type="index" width="55" />
      <el-table-column
        align="center"
        label="物资名称"
        prop="materialName"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        align="center"
        label="规格型号"
        prop="materialModel"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="到货数量"
        prop="checkNum"
        show-overflow-tooltip
      />
      <el-table-column align="center" label="单位" prop="unitName" />
      <el-table-column
        align="center"
        label="供应商"
        prop="supplierName"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        label="出厂日期"
        prop="productDate"
        show-overflow-tooltip
      />

      <el-table-column label="相关配套资料" align="center" prop="checkUrlName">
        <!-- <template slot-scope="scope">
            <div @click="openGt(scope.row)" style="color: #02a7f0; cursor: pointer">
                {{ '报告管理' }}
            </div>
            </template> -->
      </el-table-column>

      <el-table-column
        align="center"
        label="状态"
        prop="statusName"
        show-overflow-tooltip
      />

      <el-table-column label="操作" align="center" width="300">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-zoom-in"
            @click="handleView(scope.row)"
           
            >查看</el-button
          >
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-zoom-in"
            @click="handleUpload(scope.row)"
            v-if="scope.row.statusName != '待入库'"
            >下载</el-button
          >
          <el-button
            size="mini"
            type="danger"
            icon="el-icon-close"
            @click="handleBack(scope.row)"
            v-if="scope.row.statusName != '待入库'"
            >驳回</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="maForm.pageNum"
      :limit.sync="maForm.pageSize"
      @pagination="getList"
    />

    <!-- 新购查看弹窗 -->
    <el-dialog
      :title="titleBind"
      :visible.sync="showBind"
      width="1000px"
      append-to-body
    >
      <el-form
        :model="queryBind"
        ref="queryFormBind"
        size="small"
        :inline="true"
        v-show="showSearch"
        label-width="68px"
      >
      </el-form>
      <el-table
        v-loading="loadingTwo"
        :data="getListQr"
        width="800px"
        height="600px"
        @selection-change="handleSelectionChangeQr"
      >
        <!-- <el-table-column label="序号" align="center" prop="userName" sortable /> -->
        <el-table-column
          label="类型名称"
          align="center"
          prop="materialName"
          sortable
        />
        <el-table-column
          label="规格型号"
          align="center"
          prop="materialModel"
          sortable
        />
        <el-table-column
          label="设备编码"
          align="center"
          prop="maCode"
          sortable
        />
        <el-table-column
          label="绑定人员"
          align="center"
          prop="createBy"
          sortable
        />
        <el-table-column
          label="绑定时间"
          align="center"
          prop="createTime"
          sortable
        />
        <el-table-column
          label="出厂编号"
          align="center"
          prop="outFacCode"
          sortable
        />
        <el-table-column
          label="出厂时间"
          align="center"
          prop="productDate"
          sortable
        />
        <el-table-column
          label="二维码编码"
          align="center"
          prop="qrCode"

        >
        <template slot-scope="scope">
            <span
                style="color: blue; cursor: pointer"
                @click="labelUploadCode(scope.row)"
            >
                {{ scope.row.qrCode }}</span
            >
        </template>
         </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryBind.pageNum"
        :limit.sync="queryBind.pageSize"
        @pagination="getListQr"
      />
    </el-dialog>

    <!-- 绑定查看弹窗 -->
    <el-dialog
      :title="titleTwo"
      :visible.sync="showTwo"
      width="1100px"
      append-to-body
      @close="cancel"
    >
      <el-form
        :model="queryBindTwo"
        ref="queryFormBind"
        :rules="queryBindTwoRules"
        size="small"
        :inline="true"
        v-show="showSearch"
        label-width="68px"
      >
        <el-form-item label="前缀" label-width="50px" prop="codePrefix">
          <el-input
            v-model="queryBindTwo.codePrefix"
            placeholder="请输入前缀"
            clearable
            maxlength="20"
          />
        </el-form-item>

        <el-form-item
          label="后缀起始值"
          label-width="100px"
          prop="codeSuffixStart"
        >
          <el-input
            v-model="queryBindTwo.codeSuffixStart"
            clearable
            placeholder="请输入后缀起始值"
            maxlength="99999999"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="mini" @click="handleAdd"
            >填充</el-button
          >
          <el-button type="primary" size="mini" @click="handleBindTwo"
            >绑定</el-button
          >
        </el-form-item>
      </el-form>
      <el-table
        v-loading="loadingTwo"
        :data="codeTableList"
        width="1000px"
        height="600px"
      >
        <el-table-column label="设备名称" align="center" prop="materialName" />
        <el-table-column label="规格型号" align="center" prop="materialModel" />
        <el-table-column label="设备编码" align="center" prop="maCode" />
        <el-table-column label="出厂编号" align="center" prop="outFacCode">
          <template v-slot:default="{ row }">
            <el-input
              v-model="row.outFacCode"
              placeholder="请输入出厂编码"
              maxlength="30"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column label="出厂时间" align="center" prop="productDate">
          <template v-slot:default="{ row }">
            <el-date-picker
              v-model="row.productDate"
              type="date"
              placeholder="请输入检验时间"
              style="width: 160px"
            ></el-date-picker>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="140">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-remove"
              @click="handleRemove(scope.$index)"
            >
              移除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

        <!-- 标签下载对话框 -->
        <el-dialog
            :title="title"
            :visible.sync="uploadOpen"
            width="450px"
            append-to-body
            :close-on-click-modal="false"
        >
            <div style="text-align: center" ref="codeBox">
                <div class="uploadImg">
                    <div id="qrcode" class="qrcode" ref="codeItem"></div>
                    <!--        <img src="" alt="">-->
                </div>
                <div class="maCode">设备编号：{{ rowObj.maCode }}</div>
            </div>
            <div slot="footer" class="dialog-footer" style="text-align: center">
                <el-button type="primary" @click="downloadCode"
                    >下 载</el-button
                >
            </div>
        </el-dialog>
        <div style="background-color: transparent" ref="qrCodeAll">
            <div
                id="qrCode"
                v-for="(codeItem, codeIndex) in checkboxModel"
                :key="codeIndex"
                class="captureId"
                v-show="codeId"
                ref="QrcodePage"
                style="
                    z-index: -1111111;
                    position: absolute;
                    top: 10px;
                    left: -99999;
                    width: 450px;
                    height: 475px;
                    background-size: cover;
                "
            ></div>
            <!-- <center style="text-align: center; font-size: 1.5625rem">
        {{ codeVal }}
      </center> -->
        </div>
    </div>

    
</template>

<script>
// import {
// } from '@/api/store/newBuy'
// import {
//   getPurchaseCheckInfo,
//   equipmentTypeTree,
//   addPurchaseCheckInfo,
//   //     getPurchaseCheckInfo,
//   updatePurchaseCheckInfo,
// } from "@/api/baseGround/newBuy";

import { getListDetail, getListDetailById,bindAllData,exportNewBuy } from "@/api/purchase/goodsBind";
import { downloadFile } from '@/utils/download'
import QRCode from 'qrcodejs2'
import html2canvas from 'html2canvas'
import JSZip from 'jszip'
import FileSaver from 'file-saver'
// import { getUserByRoleList } from '@/api/system/user'
// import { equipmentTypeTree, supplierInfoList } from '@/api/store/tools'
// import Treeselect from '@riophae/vue-treeselect'
// import '@riophae/vue-treeselect/dist/vue-treeselect.css'
// import HoldingpoleDialog from '@/components/HoldingpoleDialog/index.vue'

// import {} from '@/api/store/newBuy

export default {
    name: 'BindQrTools',
    // dicts: ['sys_normal_disable'],
    // components: { Treeselect, HoldingpoleDialog },
    props: {
        editTaskId: {
        type: [String, Number],
        default: () => {
            return "";
        },
        },
    },
    data() {
    return {
      taskId: "",
      // isEdit: false,
      // 遮罩层
      loading: false,
      loadingTwo: false,
      typesList:[],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      num: 0,
      //机具类型
      equipmentTypeList: [],
      // 角色表格数据
      equipmentList: [],
      getListQr:[],
      // 弹出层标题
      title: "",
      titleBind: "",
      titleTwo: "",
      // 是否显示弹出层
      open: false,
      showBind: false,
      showTwo: false,
      // 日期范围
      dateRange: [],
      queryBind: {
        pageNum: 1,
        pageSize: 10,
      },
      queryBindTwo: {
        codePrefix: undefined,
        codeSuffixStart: undefined,
      },
      // 查询参数
      queryParams: {
        equipmentId: undefined,
        productionTime: "",
        supplierId: "",
      },
      maForm: {
        pageNum: 1,
        pageSize: 10,
        taskId:undefined,
      },
      // 表单参数
      form: {},
      materialName: undefined,
      materialModel: undefined,
      codeTableList: [],
      codeTableListTemp: [],
      productDate: undefined,
      taskIdTemp:undefined,
      typeIdTemp:undefined,
      rowObj:{},
      labelmaCode: '',
      uploadOpen: false,
      qrUrl: this.globalUrl.qrUrl,
      checkboxModel: [], // 列表复选框
      qrcodeArr:[],
      codeId: true,
      queryBindTwoRules: {
        codePrefix: [
          { required: true, message: "请输入前缀", trigger: "blur" },
        ],
        codeSuffixStart: [
          {
            required: true,
            message: "请输入后缀起始值",
            trigger: "blur",
          },
          {
            pattern: /^[1-9][0-9]*$/,
            message: "请输入大于0且不能以0开头的正整数",
          },
        ],
      },
    };
  },
  computed: {
    pickerOptions() {
      return {
        disabledDate(time) {
          const currentDate = new Date();
          currentDate.setHours(0, 0, 0, 0);
          return time.getTime() < currentDate.getTime();
        },
      };
    },
  },
  watch: {
    // 'maForm.purchaseTime'() {
    //     if (this.maForm.purchaseTime != '') {
    //         // this.maForm.arrivalTime = ''
    //     }
    // },
  },
  mounted() {
    this.taskId = this.editTaskId;
    this.maForm.taskId = this.taskId;
    this.getTaskInfo();
    // this.getUserList()
    // this.getList();
    // this.supplierInfoList()
  },
  methods: {
            handleSelectionChangeQr(selection){
            this.checkboxModel = selection
            // this.checkboxModel.forEach((item) => {
            //     item.exportUrl = this.qrUrl + item.qrCode
            // })
            this.single = selection.length != 1
            this.multiple = !selection.length
            },

            async handleDownloadQr() {
            this.codeId = true;
            console.log('checkboxModel', this.checkboxModel)
            if(this.checkboxModel.length>0){
                const msg = this.$modal.loading('批量生成中，请稍候...')
                let that = this
                try {
                    let captureId = document.getElementsByClassName('captureId')
                    for (let i = 0; i < this.checkboxModel.length; i++) {
                        const element = this.checkboxModel[i]
                        captureId[i].innerHTML = ''
                        let shareContent = that.$refs['QrcodePage'][i],
                            width = shareContent.offsetWidth,
                            height = shareContent.offsetHeight
                        const maCodeText = document.createElement('div')
                        maCodeText.innerHTML = '编码:' + element
                        maCodeText.style =
                            'font-size=18px; width:100%;text-align:center;margin:10px;'
                        shareContent.appendChild(maCodeText)
                        console.log(element)
                        new QRCode(captureId[i], {
                            width: width,
                            height: height,
                            text: this.qrUrl + element.qrCode,
                            colorDark: '#000',
                            colorLight: '#fff',
                        })
                        let canvas = document.createElement('canvas'),
                            scale = 0.9
                        canvas.width = width * scale
                        canvas.height = height * scale
                        canvas.style.width =
                            (shareContent.clientWidth * scale) / 100 + 'px'
                        canvas.style.height =
                            (shareContent.clientHeight * scale) / 100 + 'px'
                        canvas.getContext('2d').scale(scale, scale)
                        let opts = {
                            scale: scale,
                            canvas: canvas,
                            logging: false,
                            width: width,
                            height: height,
                            useCORS: true,
                        }
                        await html2canvas(shareContent, opts)
                            .then(function (canvas) {
                                const qrContentImage = canvas.toDataURL(
                                    'image/jpeg',
                                    1.0,
                                )
                                if (i <= that.checkboxModel.length - 1) {
                                    that.qrcodeArr.push({
                                        url: qrContentImage,
                                        name: element,
                                    })
                                }
                            })
                            .catch(function (reason) {
                                console.log(reason)
                                this.$emit('clearCheck')
                                that.$modal.closeLoading()
                            })
                    }
                    await new Promise((resolve) => setTimeout(resolve, 2000))
                    that.packageImages()
                    setTimeout(msg, 1000)
                    that.$modal.closeLoading()
                } catch (error) {
                    setTimeout(msg, 1000)
                    // that.getList()
                    this.$emit('clearCheck')
                    that.$modal.closeLoading()
                }
            }else{
                this.$modal.msgError("请先选择导出设备");
            }
            
        },
        //打包压缩
        packageImages() {
            let that = this
            const zip = new JSZip()
            const cache = {}
            let arr = that.qrcodeArr
            arr.forEach((item, index) => {
                let fileName = item.name
                zip.file(fileName + '.png', item.url.substring(22), {
                    base64: true,
                })
                cache[fileName] = item.url
            })
            zip.generateAsync({ type: 'blob' }).then((content) => {
                FileSaver.saveAs(content, '二维码.zip')
            })
            // that.getList()
            this.$emit('clearCheck')
            that.qrcodeArr = []
            that.codeId = false;
        },

    //二维码查看
    labelUploadCode(row) {
            // if (row.maCode == null) {
            //   this.$message.error('当前设备没有设备编码');
            //   return
            // }
            this.rowObj = row
            this.uploadOpen = true
            this.title = '二维码查看'
            this.labelmaCode = row.qrCode
            let str = this.qrUrl + row.qrCode
            console.log('qrUrl',this.qrUrl)
            console.log('str',str)
            this.$nextTick(() => {
                // this.selectionList.forEach((item, index) => {
                this.$refs.codeItem.innerHTML = ''
                var qrcode = new QRCode(this.$refs.codeItem, {
                    text: str, //二维码内容
                    width: 256,
                    height: 256,
                    colorDark: '#000000',
                    colorLight: '#ffffff',
                    correctLevel: QRCode.CorrectLevel.H,
                })

                // });
            }, 500)
    },

    downloadCode(e) {
            if (document.getElementById('qrcode').childNodes[0]) {
                let element = this.$refs.codeBox
                html2canvas(element).then((canvas) => {
                    // 将canvas转换为图片URL
                    const image = canvas.toDataURL('image/png')
                    const alink = document.createElement('a')
                    alink.href = image
                    alink.download = this.labelmaCode
                    alink.click()
                })
            }
    },
    resetQuery(){

    },

    /** 新增按钮操作 */
    handleBackAll() {},

    //获取任务详情--- 编辑回显数据
    getTaskInfo() {
      this.maForm.pageNum = 1;
      this.getList();
    },

        //获取任务详情--- 编辑回显数据
    handleQuery() {
      this.maForm.pageNum = 1;
      this.getList();
    },

    getList(){
        this.loading = true;
        // this.maForm.statusList=[3,13]
        this.maForm.taskStage=3
        getListDetail(this.maForm).then((response) => {
        this.equipmentList = response.rows;
        this.total = response.total;
        this.loading = false;
      }); 
    },


    //打开查看页面
    handleView(row) {
      this.loadingTwo = true;
      getListDetailById({ taskId: row.taskId, typeId: row.typeId }).then(
        (response) => {
          this.getListQr = response.data;
          this.showBind = true;
          this.titleBind = "查看";
          this.loadingTwo = false;
        }
      );
    },
    //打开绑定页面
    handleBind(row) {
      this.queryBindTwo = {};
      this.resetForm("queryFormBind");
      this.titleTwo = "绑定";
      this.showTwo = true;
      this.num = row.checkNum;
      this.materialName = row.materialName;
      this.materialModel = row.materialModel;
      this.productDate = row.productDate;
      this.taskIdTemp = row.taskId;
      this.typeIdTemp = row.typeId;
    },

    //填充
    handleAdd() {
      this.$refs["queryFormBind"].validate((valid) => {
        if (valid) {
          this.codeTableList = [];
          // 设备编码: 前缀 拼接 后缀
          for (let i = 0; i < this.num; i++) {
            let suffix = parseInt(this.queryBindTwo.codeSuffixStart) + i;
            suffix = suffix.toString().padStart(5, "0");
            console.log("suffix", suffix);
            suffix = isNaN(suffix) ? "" : suffix;
            console.log("suffixTwo", suffix);
            const maCode = `${this.queryBindTwo.codePrefix || ""}${suffix}`;
            console.log("maCode", maCode);
            // 出厂编码
            const outFacCode = "";
            const materialName = this.materialName;
            const materialModel = this.materialModel;
            const productDate = this.productDate;
            this.codeTableList.push({
              materialName,
              materialModel,
              maCode,
              outFacCode,
              productDate,
            });
          }
        }
      });
    },

    handleBindTwo(){
        this.codeTableList.forEach(item=>{
           this.codeTableListTemp.push({maCode:item.maCode,outFacCode:item.outFacCode,productDate:item.productDate})
        })
            bindAllData({taskId:this.taskIdTemp,typeId:this.typeIdTemp,dtoList:this.codeTableListTemp}).then(
                (response) => {
                   this.$modal.msgSuccess("绑定成功");
                    this.getList();
                    this.showTwo = false
                    
                },
            )
    },

    handleRemove(index){
        this.codeTableList.splice(index,1)
    },
    
    cancel() {
      this.codeTableList = [];
      this.showTwo = false;
      this.reset();
    },
    reset() {
      this.resetForm("queryFormBind");
    },


    // 表单重置
    reset() {
      if (this.$refs.menu != undefined) {
        this.$refs.menu.setCheckedKeys([]);
      }
      (this.menuExpand = false),
        (this.menuNodeAll = false),
        (this.deptExpand = true),
        (this.deptNodeAll = false),
        (this.form = {
          roleId: undefined,
          roleName: undefined,
          roleKey: undefined,
          roleSort: 0,
          status: "0",
          menuIds: [],
          deptIds: [],
          menuCheckStrictly: true,
          deptCheckStrictly: true,
          remark: undefined,
        });
      this.resetForm("form");
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.roleId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      // this.reset();
      //   this.form = response.data;
      //   this.open = true;
    },
    /** 明细按钮操作 */
    handleDetail(row) {
      this.holdingpoleData = row;
      this.showDialog = true;
    },

    /** 删除按钮操作 */
    handleBack(row) {
      // console.log(row.id)
      this.$modal
        .confirm("是否确认删除所选择的数据项？")
        .then(() => {
          this.deviceType.forEach((e, index) => {
            if (e[3] === row.typeId) {
              this.deviceType.splice(index, 1);
              this.propsKey++;
            }
          });
          this.equipmentList.forEach((item, index) => {
            if (item.id == row.id) {
              this.equipmentList.splice(index, 1);
            }
          });
        })
        .catch(() => {});

      // const roleIds = row.roleId || this.ids;
      // this.$modal.confirm('是否确认删除角色编号为"' + roleIds + '"的数据项？').then(function() {
      //   return delRole(roleIds);
      // }).then(() => {
      //   this.getList();
      //   this.$modal.msgSuccess("删除成功");
      // }).catch(() => {});
    },

    /** 导出二维码按钮操作 */
        handleUpload(row) {
            exportNewBuy({purchaseId:row.purchaseId}).then(res => {
              downloadFile({ fileName: `二维码_${new Date().getTime()}.zip`, fileData: res, fileType: 'application/zip;charset=utf-8' })
            })
          }
        
  },
};
</script>
<style lang="scss">
.uploadImg {
    padding-top: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
}
.maCode {
    margin-top: 10px;
    padding-bottom: 20px;
    font-size: 18px;
}
.popper-select {
    .el-cascader-panel .el-scrollbar .el-checkbox {
        display: none;
    }

    .el-cascader-panel .el-scrollbar:nth-child(4) .el-checkbox {
        display: block !important;
    }
}
</style>
