<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" inline>
          <el-row>
            <el-col :span="5">
              <el-form-item label="设备名称">
                <el-input style="width: 100%" v-model="queryParams.equipmentName" clearable placeholder="请输入设备名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="分类编码">
                <treeselect v-model="queryParams.classificationCode" :options="classificationOptions"
                            :normalizer="normalizer" placeholder="请选择分类编码"/>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="设备状态">
                <el-select v-model="queryParams.equipmentState" clearable placeholder="请选择设备状态">
                  <el-option v-for="dict in dict.type.equipment_state" :key="dict.value" :label="dict.label"
                             :value="dict.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="归属类型">
                <el-select v-model="queryParams.affiliationType" clearable placeholder="请选择归属类型">
                  <el-option v-for="dict in dict.type.affiliation_type" :key="dict.value" :label="dict.label"
                             :value="dict.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-button class="ml20" type="primary" icon="el-icon-search" size="mini" @click="getList">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-col>
          </el-row>
        </el-form>
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="showDetail(0)">入库</el-button>
                <el-button type="danger" plain icon="el-icon-minus" size="mini"
                           @click="handleDelete(0)" :disabled="isDisabledBtn">批量出库</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="success" icon="el-icon-download" size="mini" @click="upload.open = true">导入</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="warning" icon="el-icon-upload2" size="mini" @click="handleExportClass">导出</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="warning" icon="el-icon-printer" size="mini"
                           @click="printBarcodes" :disabled="isDisabledBtn">批量打印条码</el-button>
            </el-col>
        </el-row>
        <!-- 表单数据 -->
        <el-table v-loading="loading" stripe :data="deviceData" @selection-change="handleSelectionChange" width="100%">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column align="center" type="index" label="序号" width="55" fixed="left" />
            <el-table-column align="center" prop="encode" label="自编码"></el-table-column>
            <el-table-column align="center" prop="equipmentName" label="设备名称"></el-table-column>
            <el-table-column align="center" prop="model" label="型号"></el-table-column>
            <el-table-column align="center" prop="specification" label="规格"></el-table-column>
            <el-table-column align="center" prop="classificationCode" label="分类编码"></el-table-column>
            <el-table-column align="center" prop="unit" label="单位"></el-table-column>
            <el-table-column align="center" prop="affiliationType" label="归属类型">
              <template slot-scope="{ row }">
                <div>{{ selectDictLabel(dict.type.affiliation_type, row.affiliationType) }}</div>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="equipmentState" label="设备状态">
              <template slot-scope="{ row }">
                <div>{{ selectDictLabel(dict.type.equipment_state, row.equipmentState) }}</div>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="isAllowLend" label="是否允许借出">
              <template slot-scope="{ row }">
                <div>{{ selectDictLabel(dict.type.is_lend, row.isAllowLend) }}</div>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="isLend" label="是否借出">
              <template slot-scope="{ row }">
                <div>{{ selectDictLabel(dict.type.is_lend, row.isLend) }}</div>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="dateOfProduction" label="投产日期"></el-table-column>
            <el-table-column align="center" prop="price" label="价格（元）"></el-table-column>
            <el-table-column align="center" prop="lifeOfUtility" label="效用年限（年）"></el-table-column>
            <el-table-column align="center" prop="place" label="地点"></el-table-column>
            <el-table-column align="center" prop="useName" label="使用人"></el-table-column>
            <el-table-column align="center" prop="remark" label="备注"></el-table-column>
            <el-table-column label="操作" align="center" min-width="220px" fixed="right">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-edit" @click="showDetail(1,scope.row.id)">编辑</el-button>
                    <el-button size="mini" type="text" icon="el-icon-view" @click="showDetail(2,scope.row.id)">查看</el-button>
                    <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(1,scope.row)">出库</el-button>
                </template>
            </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
                    :limit.sync="queryParams.pageSize" @pagination="getList" />

        <!-- 添加或修改对话框 -->
        <el-dialog :title="title" :visible.sync="dialogVisible" width="50%" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="100px">
                <el-row :gutter="20">
                    <el-col :span="24">
                        <el-form-item v-if="nowOptionType != 0" label="自编码:" prop="encode">
                            <el-input v-model="form.encode" placeholder="请输入自编码" disabled></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="分类编码:" prop="classificationCode">
                      <treeselect v-model="form.classificationCode" :options="classificationOptions"
                                  :normalizer="normalizer" @select="selectNode"
                                  placeholder="请选择分类编码" :disabled="nowOptionType==2?true:false"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="设备名称:" prop="equipmentName">
                      <el-input v-model="form.equipmentName" placeholder="请输入设备名称"
                                :disabled="nowOptionType==2?true:false" clearable></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="型号:" prop="model">
                      <el-input v-model="form.model" placeholder="请输入型号"
                                :disabled="nowOptionType==2?true:false" clearable></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="规格:" prop="specification">
                      <el-input v-model="form.specification" placeholder="请输入规格"
                                :disabled="nowOptionType==2?true:false" clearable></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="单位:" prop="unit">
                      <el-input v-model="form.unit" placeholder="请输入单位"
                                :disabled="nowOptionType==2?true:false" clearable></el-input>
                    </el-form-item>
                  </el-col>
                    <el-col :span="12">
                        <el-form-item label="归属类型:" prop="affiliationType">
                          <el-select v-model="form.affiliationType" clearable placeholder="请选择归属类型"
                                     :disabled="nowOptionType==2?true:false" class="selectWidth">
                            <el-option v-for="dict in dict.type.affiliation_type" :key="dict.value" :label="dict.label"
                                       :value="dict.value" />
                          </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="设备状态:" prop="equipmentState">
                      <el-select v-model="form.equipmentState" clearable placeholder="请选择设备状态"
                                 :disabled="nowOptionType==2?true:false" class="selectWidth">
                        <el-option v-for="dict in dict.type.equipment_state" :key="dict.value" :label="dict.label"
                                   :value="dict.value" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                    <el-col :span="12">
                        <el-form-item label="是否允许借出:" prop="isAllowLend">
                            <el-select v-model="form.isAllowLend" clearable placeholder="请选择是否允许借出"
                                       :disabled="nowOptionType==2?true:false" class="selectWidth">
                                <el-option v-for="dict in dict.type.is_lend" :key="dict.value" :label="dict.label"
                                    :value="dict.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="是否借出:" prop="isLend">
                      <el-select v-model="form.isLend" clearable placeholder="请选择是否借出"
                                 :disabled="nowOptionType==2?true:false" class="selectWidth">
                        <el-option v-for="dict in dict.type.is_lend" :key="dict.value" :label="dict.label"
                                   :value="dict.value" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                    <el-col :span="12">
                        <el-form-item label="投产日期:" prop="dateOfProduction">
                            <el-date-picker v-model="form.dateOfProduction" type="date" placeholder="选择日期"
                                            class="selectWidth" value-format="yyyy-MM-dd"
                                            :disabled="nowOptionType==2?true:false" clearable>
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="价格:" prop="price">
                      <el-input v-model="form.price" placeholder="请输入价格"
                                :disabled="nowOptionType==2?true:false" clearable></el-input>
                    </el-form-item>
                  </el-col>
                    <el-col :span="12">
                        <el-form-item label="效用年限:" prop="lifeOfUtility">
                            <el-input v-model="form.lifeOfUtility" placeholder="请输入效用年限（年）"
                                      :disabled="nowOptionType==2?true:false" clearable></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="地点:" prop="place">
                      <el-input v-model="form.place" placeholder="请输入地点"
                                :disabled="nowOptionType==2?true:false" clearable></el-input>
                    </el-form-item>
                  </el-col>
                    <el-col :span="12">
                        <el-form-item label="使用人:" prop="useName">
                          <el-select v-model="form.useId" filterable placeholder="请选择使用人"
                                     :disabled="nowOptionType==2?true:false" clearable>
                            <el-option v-for="(item,index) in userList" :key="index"
                                       :label="item.userName" :value="item.userId">
                            </el-option>
                          </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
              <el-row :gutter="20">
                <el-col :span="24">
                  <el-form-item label="备注:" prop="remark">
                    <el-input type="textarea" v-model="form.remark" placeholder="请输入备注"
                              :disabled="nowOptionType==2?true:false" clearable></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button v-if="nowOptionType != 2" type="primary" @click="submitForm">确 定</el-button>
                <el-button  @click="dialogVisible = false">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 导入对话框-->
        <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
            <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url"
                :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
                :auto-upload="false" drag>
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip text-center" slot="tip">
                    <span>仅允许导入xls、xlsx格式文件。</span>
                    <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
                        @click="importTemplate">下载模板
                    </el-link>
                </div>
            </el-upload>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitFileForm">确 定</el-button>
                <el-button @click="upload.open = false">取 消</el-button>
            </div>
        </el-dialog>

      <!-- 打印二维码 弹框部分 -->
      <el-dialog title="打印条码预览" :visible.sync="printDialog" width="30%">
        <div class="qrCodeList">
          <div v-for="(item,index) in chooseList" :key="index">
            <div class="titlShow">东营市二中</div>
            <div class="flexBlock qrCode">
              <div class="qrCodeLeft">
                <div :id="'qrcode' + index"></div>
                <div>{{item.encode}}</div>
              </div>
              <div class="qrCodeRight">
                <div>{{ item.equipmentName }}：{{ item.model }}</div>
                <div>地点：{{ item.place }}</div>
              </div>
            </div>
          </div>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="printCode">打  印</el-button>
        </div>
      </el-dialog>
      <!-- 打印二维码 弹框部分 -->

      <!-- 隐藏二维码页面样式 -->
      <div id="printBlock">
        <div v-for="(item,index) in printList" :key="index" class="printBody">
          <div class="titlePrint">东营市二中</div>
          <div class="flexBlock printQrCode">
            <div class="printLeft">
              <div :id="'print' + index" class="printImg"></div>
              <div>{{item.encode}}</div>
            </div>
            <div class="printRight">
              <div>{{ item.equipmentName }}：{{ item.model }}</div>
              <div>地点：{{item.place}}</div>
            </div>
          </div>
          <div style="page-break-after:always"></div>
        </div>
      </div>
      <!-- 隐藏二维码页面样式 -->



    </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import {
  addEquipmentLedger, deleteEquipmentLedger, editEquipmentLedger,
  getEquipmentLedger,
  getEquipmentLedgerDetailByID, getModelByID, getUserList
} from "../../../../api/smartSchool/schoolProperty/equipmenTledger";
import { getProduct } from "../../../../api/smartSchool/schoolProperty/classiFication";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import QRCode from "qrcodejs2"; // 生成二维码插件
import printJS from "print-js"; // 打印插件


export default {
  name: "index",
  dicts: ['equipment_state','affiliation_type','is_lend'],
  components: { Treeselect },
  data() {
      return {
        loading: true, // 遮罩层
        total: 0, // 总条数
        deviceData: [], // 设备台账表格数据
        title: "", // 弹出层标题
        dialogVisible: false, // 添加或修改
        queryParams: { // 查询参数
          pageNum: 1,
          pageSize: 10,
          equipmentName:'',
          classificationCode:undefined,
          equipmentState:'',
          affiliationType:'',
        },
        classificationOptions:[], // 分类编码树状结构
        upload: {
            // 是否显示弹出层
            open: false,
            // 弹出层标题
            title: "",
            // 是否禁用上传
            isUploading: false,
            // 设置上传的请求头部
            headers: { Authorization: "Bearer " + getToken() },
            // 上传的地址
            url: process.env.VUE_APP_BASE_API + "/equipmentLedger/importData"
        },
        form: {
          id:'',
          encode:'',
          equipmentName:'',
          model:'',
          specification:'',
          classificationCode:undefined,
          unit:'',
          affiliationType:'',
          equipmentState:'',
          isAllowLend:'',
          isLend:'',
          dateOfProduction:'',
          price:'',
          lifeOfUtility:'',
          place:'',
          useId:'',
          useName:'',
          remark:'',
        },
        rules: { // 表单校验
          equipmentName:[
            { required: true, message: '请输入设备名称', trigger: 'blur' },
          ],
          classificationCode: [
            { required: true, message: '请选择分类编码', trigger: 'change' }
          ],
          equipmentState: [
            { required: true, message: '请选择设备状态', trigger: 'change' }
          ],
        },
        nowOptionType:'', // 0 入库 1 编辑 2 查看
        electItem:[], // 选中的数据
        isDisabledBtn:true,
        chooseList:[], //用户选择的table数据
        printDialog:false, // 打印二维码预览
        printList:[],
        userList:[] //使用人列表
      };
  },
  created() {
    this.getClassificationCodeTree()
    this.getList()
  },
  methods: {
    //获取分类编码树形下拉框
    getClassificationCodeTree(){
      getProduct().then(res=>{
        if(res.code == 200){
          this.classificationOptions = this.handleTree(res.rows, "id")
        }
      })
    },

    /** 查询列表 */
    getList() {
      this.loading = true
      getEquipmentLedger({...this.queryParams}).then(res=>{
        if(res.code == 200){
          this.total = res.total
          this.deviceData = res.rows
          this.loading = false
        }
      })
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        equipmentName:'',
        classificationCode:undefined,
        equipmentState:'',
        affiliationType:'',
      }
      this.getList()
    },

    /** 转换分类编码数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.classificationCode,
        label: node.equipmentType,
        children: node.children
      };
    },

    //弹出层分类编码选择事件 获取当前分类编码的型号
    selectNode(node){
      const id = node.classificationCode
      getModelByID(id).then(res=>{
        if(res.code == 200){
          this.form.model = res.data.model
        }
      })
    },

    //0 入库 1 编辑 2 查看
    showDetail(type,id){
      this.form = {
        id:'',
        encode:'',
        equipmentName:'',
        model:'',
        specification:'',
        classificationCode:undefined,
        unit:'',
        affiliationType:'',
        equipmentState:'',
        isAllowLend:'',
        isLend:'',
        dateOfProduction:'',
        price:'',
        lifeOfUtility:'',
        place:'',
        useName:'',
        useId:'',
        remark:'',
      }
      this.nowOptionType = type
      this.getSelectUser()
      if(type != 0){
        getEquipmentLedgerDetailByID(id).then(res=>{
          if(res.code == 200){
            Object.keys(this.form).forEach(key => {
              res.data[key] && (this.form[key] = res.data[key])
            })
          }
        })
      }
      this.dialogVisible = true
    },

    //使用人列表数据
    getSelectUser(){
      getUserList().then(res=>{
        if(res.code == 200){
          this.userList = res.rows
        }
      })
    },

    //表单提交
    submitForm(){
      const useId = this.form.useId
      this.form.useName = useId == ''?'':this.userList.find(item=>item.userId == useId).userName
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if(this.nowOptionType == 0){
            //0 入库 1 编辑 2 查看
            const data = {
              equipmentName:this.form.equipmentName,
              model:this.form.model,
              specification:this.form.specification,
              classificationCode:this.form.classificationCode,
              unit:this.form.unit,
              affiliationType:this.form.affiliationType,
              equipmentState:this.form.equipmentState,
              isAllowLend:this.form.isAllowLend,
              isLend:this.form.isLend,
              dateOfProduction:this.form.dateOfProduction,
              price:this.form.price,
              lifeOfUtility:this.form.lifeOfUtility,
              place:this.form.place,
              useName:this.form.useName,
              useId,
              remark:this.form.remark,
            }
            addEquipmentLedger(data).then(res=>{
              if(res.code == 200){
                this.$message.success("设备台账入库成功！")
                this.dialogVisible = false
                this.getList()
              }
            })
          }else if(this.nowOptionType == 1){
            //1 编辑
            editEquipmentLedger({...this.form}).then(res=>{
              if(res.code == 200){
                this.$message.success("设备台账编辑成功！")
                this.dialogVisible = false
                this.getList()
              }
            })
          }
        }
      })
    },

    //出库
    handleDelete(type,item){
      let idString = type == 0?this.electItem.toString():item.id
      let message = type == 0?'是否确认批量出库选中设备？':`是否确认出库${item.model}设备？`
      this.$confirm(message, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteEquipmentLedger(idString).then(res=>{
          if(res.code == 200){
            this.$message({
              type: 'success',
              message: '出库成功!'
            });
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消出库！'
        });
      });

    },

    //模版下载
    importTemplate(){
      this.download(
        "/equipmentLedger/importTemplate",
        {},
        `设备台账_template_${new Date().getTime()}.xlsx`
      );
    },

    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
        response.msg +
        "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },

    //导出
    handleExportClass(){
      const data = {
        equipmentName:this.queryParams.equipmentName,
        classificationCode:this.queryParams.classificationCode,
        equipmentState:this.queryParams.equipmentState,
        affiliationType:this.queryParams.affiliationType,
      }
      this.download('/equipmentLedger/export', {
        ...data,
      }, `设备台账_${Date.now()}.xlsx`)
    },

    //生成批量打印条码
    printBarcodes(){
      this.printDialog = true
      this.printList = this.chooseList
      this.$nextTick(()=>{
        this.chooseList.map((item,index) => {
          const dom = document.getElementById(`qrcode${index}`).lastElementChild
          if(dom == null){
            new QRCode(`qrcode${index}`, {
              width: 150,
              height: 150,
              text: item.encode,
            });
          }
        })

        this.printList.map((item,index) =>{
          const domPrint = document.getElementById(`print${index}`).lastElementChild
          if(domPrint == null) {
            new QRCode(`print${index}`, {
              width: 60,
              height: 60,
              text: item.encode,
            });
          }
        })

      })
    },

    //打印条码
    printCode(){
      printJS({
        printable: 'printBlock', // 标签元素id
        type: 'html',
        targetStyles: ['*'],
        font_size: '10px',
        style:`
            @media print{
              @page{
                size:auto;
                margin:4mm 0mm 0mm 0mm
              }
              @page :first {
                margin-top:2mm
              }
              #printBlock{
              display:block!important
              }
            }`
      })
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.chooseList = selection
      this.electItem = selection.map(item=>{
        return item.id
      })
      this.isDisabledBtn = selection.length != 0?false:true
    },

  },
};
</script>

<style scoped>
::v-deep .el-form-item,
::v-deep .el-select{
  width: 100%;
}
::v-deep .el-form-item--small .el-form-item__content {
  width: 75%;
}
.qrCodeList{
  max-height: 500px;
  overflow-y: scroll;
}
.qrCode {
  width: 300px;
  font-size: 14px;
  line-height: 30px;
  align-items: flex-start;
  margin: 0 auto 20px auto;
}
.qrCodeLeft {
  text-align: center;
}
.qrCodeRight {
  padding:20px 0 20px 15px;
}
.titlShow {
  font-weight: bold;
  text-align: center;
  padding-bottom: 10px;
  font-size: 16px;
}

#printBlock {
  display: none;
  margin: 0px!important;
}

.printLeft {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}
.printBody {
  width: 250px;
}
.printQrCode {
  font-size: 6px;
  line-height: 20px;
  align-items: center;
  padding: 8px;
}
.printRight {
  width: 60%;
  padding:0 5px;
}
.titlePrint {
  font-size: 8px;
  font-weight: bold;
  text-align: center;
}
.printImg {
  display: block;
}
</style>
