<template> 
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
            <el-form-item label="生成日期">
                <el-date-picker
                    type="daterange"
                    v-model="queryTime"
                    range-separator="-"
                    style="width: 240px"
                    value-format="yyyy-MM-dd"
                    end-placeholder="结束日期"
                    start-placeholder="开始日期"
                    @change="onTimeChange"
                ></el-date-picker>
            </el-form-item> 
            <el-form-item label="关键字" prop="keyWord">
                <el-input
                    v-model="queryParams.keyWord"
                    placeholder="请输入关键字"
                    clearable
                    maxlength="50"
                    style="width: 240px"
                    @keyup.enter.native="handleQuery"/>
            </el-form-item>
            <el-form-item label="状态" prop="status">
                <el-select
                v-model="queryParams.status"
                placeholder="请选择状态"
                clearable
                filterable
                style="width: 240px"
                >
                <el-option
                    v-for="item in statusList" 
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                ></el-option>
                </el-select>
            </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-button type="success" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
            </el-form-item>
        </el-form> 
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="warning" plain icon="el-icon-download" size="mini" :disabled="multiple" @click="handleExport">下载</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
        <el-table border :data="tableList" v-loading="loading" ref="multipleTable" @selection-change="handleSelectionChange" row-key="id">
            <el-table-column type="selection" width="55" align="center" :reserve-selection="true"/>
            <el-table-column label="序号" align="center" type="index">
                <template slot-scope="scope">
                    <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
                </template>
            </el-table-column>
            <el-table-column label="二维码编码" align="center" prop="qrCode" show-overflow-tooltip/>
            <el-table-column label="物资名称" align="center" prop="typeName" show-overflow-tooltip/>
            <el-table-column label="规格型号" align="center" prop="typeModelName" show-overflow-tooltip/>
            <el-table-column label="设备犏码" align="center" prop="maCode" show-overflow-tooltip/>
            <!-- <el-table-column label="二维码类型" align="center" prop="boxType" show-overflow-tooltip>
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.qr_box_type" :value="scope.row.boxType"/>
                </template>
            </el-table-column> --> 
            <el-table-column label="生产厂家" align="center" prop="" show-overflow-tooltip/> 
            <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip/> 
              <el-table-column label="状态" align="center" prop="status" show-overflow-tooltip>
                <template slot-scope="scope">
                    <span v-if="scope.row.status==0">未绑定</span>
                    <span v-if="scope.row.status==1">已绑定</span> 
                </template>
            </el-table-column> 
            <el-table-column label="操作" align="center" width="200">
                <template slot-scope="{ row }">
                    <el-button size="mini" @click="handleView(row)">
                        查看
                    </el-button>
                    
                    <!-- <el-button size="mini" type="danger" @click="handleNotice(row)">
                        删除
                    </el-button> -->
                </template>
            </el-table-column>
        </el-table> 
        <pagination :total="total"
                    v-show="total > 0"
                    :page.sync="queryParams.pageNum"
                    :limit.sync="queryParams.pageSize"
                    @pagination="getList"
        />
        
        <!-- 二维码设备新增 -->
        <el-dialog title="二维码新增" :visible.sync="open" width="600px" append-to-body>
            <el-form :model="dialogForm" ref="dialogForm" size="small" :rules="rules"  label-width="120px">
                <el-form-item label="物资类型" prop="maTypeId">
                    <el-input
                        v-model="dialogForm.maTypeName"
                        placeholder="二维码物资类型" disabled
                        style="width: 100%"/>
                </el-form-item> 
                <el-form-item label="类型规格：" prop="typeId">
                    <treeselect
                        v-model="dialogForm.typeId"
                        :options="equipmentTypeList" :normalizer="normalizer"
                        :show-count="true" style="width: 100%;" :disable-branch-nodes="true"
                        noChildrenText="没有数据了" noOptionsText="没有数据" noResultsText="没有搜索结果"
                        placeholder="请选择二维码类型规格" @select="typeChange"
                    /> 
                </el-form-item>
                <el-form-item label="生产厂家：" prop="supplierId">
                    <el-select
                        v-model="dialogForm.supplierId"
                        placeholder="生产厂家" style="width: 100%;"
                        clearable filterable 
                        >
                        <el-option
                            v-for="item in supplierList"
                            :key="item.supplierId"
                            :label="item.supplier"
                            :value="item.supplierId"
                        />
                    </el-select>
                </el-form-item> 
                <el-form-item label="二维码数量：" prop="qrNum">
                    <el-input 
                        v-model.number="dialogForm.qrNum"
                        placeholder="二维码数量"
                        type="number" min="1"
                         @input="checkNum()"
                        style="width: 100%"
                    />
                </el-form-item> 
                <el-form-item label="备注：" prop="remark">
                    <el-input 
                        v-model="dialogForm.remark"
                        placeholder="备注"
                        type="textarea" maxlength="200"
                        style="width: 100%"
                    />
                </el-form-item>  
            </el-form> 
            <div slot="footer" class="dialog-footer" style="text-align: right">
                <el-button type="primary" @click="confirmAdd">确 认</el-button>
                <el-button  @click="cancelDialog">取 消</el-button>
            </div>
        </el-dialog> 

        <!-- 二维码下载对话框 -->
        <el-dialog 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> 
                </div>
                <div class="boxCode">编号：{{ rowObj.qrCode }}</div>
            </div>
            <div slot="footer" class="dialog-footer" style="text-align: center">
                <el-button type="primary" @click="downloadCode">下 载</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script> 
import { getQrCodeListApi,addQrCodeApi,downloadQrCodesApi } from '@/api/code/code'
import { downloadFile } from '@/utils/download'
import QRCode from 'qrcodejs2';
import html2canvas from 'html2canvas';
import { getListFacturer } from '@/api/ma/supplier';
import { equipmentTypeTree } from '@/api/purchase/goodsArrived';
import qrcode from 'qrcodejs2';
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
    name: 'Home',
    dicts: ['qr_box_type'],
    components: { Treeselect },
    data() {
        return {
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            statusList: [{id:"",name:"全部"},{id:"0",name:"已绑定"},{id:"1",name:"未绑定"}], 
            total: 0, //                总条数
            loading: false, //           遮罩层
            showSearch: true, //        显示搜索条件 
            tableList: [], //            列表数据源
            queryTime: [], //           日期数据源
            selectList: [], //          列表选中数据
            // 列表查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                status: '',
                endTime: '',
                keyWord: '',
                startTime: '',
                // taskStatus: 3,
            },
            //新增弹窗
            open:false,
            dialogForm:{
                maTypeName:null,
                maTypeId:null,
                typeId:null,
                supplierId:null,
                qrNum:null,
                remark:null,
            },
            rules: {
                maTypeId: [
                    {
                        required: true,
                        message: '请选择物资类型',
                        trigger: 'change', 
                    },
                ],
                typeId: [
                    {
                        required: true,
                        message: '请选择类型规格',
                        trigger: 'change', 
                    },
                ],
                supplierId: [
                    {
                        required: true,
                        message: '请选择生产厂家',
                        trigger: 'change', 
                    },
                ],
                qrNum: [
                    {
                        required: true,
                        message: '请输入二维码数量',
                        trigger: 'blur',
                    },
                ]
            },
            //物资厂家
            supplierList: [],
            equipmentTypeList: [],  
            //单个查看下载弹窗
            uploadOpen: false,
            rowObj:{},
            qrCode:""
        }
    },
    created() {
        this.getList()
        this.supplierInfoList()
        this.equipmentType()
    },
    methods: {
        // 日期change
        onTimeChange(val) {
            if (val.length > 0) {
                const [time_1, time_2] = val
                this.queryParams.startTime = time_1
                this.queryParams.endTime = time_2
            } else {
                this.queryParams.startTime = ''
                this.queryParams.endTime = ''
            }
        },
        // 获取列表
        async getList() {
            this.loading = true 
            const res = await getQrCodeListApi(this.queryParams)
            this.tableList = res.data.rows
            this.total = res.data.total
            this.loading = false
            // if(this.queryParams.pageNum==1){
            //     this.tableList = [
            //         {id:"1",qrCode:"20211220-00001",maCode:"w241111-1001",typeName:"机动角磨",typeModelName:"CMJ-5",remark:'ceshi',status:"0"},
            //         {id:"2",qrCode:"20211220-00002",maCode:"w241111-1002",typeName:"机动角磨",typeModelName:"CMJ-5",remark:'ceshi',status:"1"},
            //         {id:"3",qrCode:"20211220-00003",maCode:"w241111-1003",typeName:"机动角磨",typeModelName:"CMJ-5",remark:'ceshi',status:"0"},
            //         {id:"4",qrCode:"20211220-00004",maCode:"w241111-1004",typeName:"机动角磨",typeModelName:"CMJ-5",remark:'ceshi',status:"1"},
            //         {id:"5",qrCode:"20211220-00005",maCode:"w241111-1001",typeName:"机动角磨",typeModelName:"CMJ-5",remark:'ceshi',status:"0"},
            //         {id:"6",qrCode:"20211220-00006",maCode:"w241111-1002",typeName:"机动角磨",typeModelName:"CMJ-5",remark:'ceshi',status:"1"},
            //         {id:"7",qrCode:"20211220-00007",maCode:"w241111-1003",typeName:"机动角磨",typeModelName:"CMJ-5",remark:'ceshi',status:"0"},
            //         {id:"8",qrCode:"20211220-00008",maCode:"w241111-1004",typeName:"机动角磨",typeModelName:"CMJ-5",remark:'ceshi',status:"1"},
            //         {id:"9",qrCode:"20211220-00000",maCode:"w241111-1001",typeName:"机动角磨",typeModelName:"CMJ-5",remark:'ceshi',status:"0"},
            //         {id:"10",qrCode:"20211220-000010",maCode:"w241111-1002",typeName:"机动角磨",typeModelName:"CMJ-5",remark:'ceshi',status:"1"}, 
            //     ]
            //     this.total = 14
            // }else{
            //     this.tableList = [
            //         {id:"11",qrCode:"20211220-000011",maCode:"w241111-1001",typeName:"机动角磨",typeModelName:"CMJ-5",remark:'ceshi',status:"0"},
            //         {id:"12",qrCode:"20211220-000012",maCode:"w241111-1002",typeName:"机动角磨",typeModelName:"CMJ-5",remark:'ceshi',status:"1"}, 
            //         {id:"13",qrCode:"20211220-000013",maCode:"w241111-1003",typeName:"机动角磨",typeModelName:"CMJ-5",remark:'ceshi',status:"0"},
            //         {id:"14",qrCode:"20211220-000014",maCode:"w241111-1004",typeName:"机动角磨",typeModelName:"CMJ-5",remark:'ceshi',status:"1"},
            //     ]
            //     this.total = 14
            // }
        },
        // 搜索按钮
        handleQuery() {
            this.queryParams.pageNum = 1
            this.getList()
        },
        // 重置按钮
        resetQuery() {
            this.$refs.multipleTable.clearSelection();
            this.queryTime = []
            this.resetForm('queryForm')
            this.queryParams.pageNum = 1
            this.queryParams.endTime = ''
            this.queryParams.pageSize = 10
            this.queryParams.startTime = ''
            this.getList()
        },  
        //二维码查看
        handleView(row) { 
            this.rowObj = row
            this.uploadOpen = true 
            this.qrCode = row.qrCode
            let str = row.qrCode
            this.$nextTick(() => { 
                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.qrCode
                    alink.click()
                })
            }
        },
        /** 物资厂家-下拉选 */
        supplierInfoList() {
            let param = {
                pageNum: 1,
                pageSize: 1000,
                keyWord:undefined
            }
            getListFacturer(param).then((response) => {
                this.supplierList = response.rows
            })
        },
        /** 物资厂家-下拉选 */
        supplierInfoList() {
            let param = {
                pageNum: 1,
                pageSize: 1000,
                keyWord:undefined
            }
            getListFacturer(param).then((response) => {
                this.supplierList = response.rows
            })
        },
        /** 机具类型 */
        equipmentType() {
            equipmentTypeTree().then((response) => {
                this.equipmentTypeList = response.data;
                this.equipmentTypeList.forEach((item, index) => {
                    if (item.children && item.children.length > 0) {
                        item.children.forEach((item2, index2) => {
                            if (item2.children && item2.children.length > 0) {
                                item2.children.forEach((item3) => {
                                    if (
                                        item3.children &&
                                        item3.children.length > 0
                                    ) {
                                        item3.children.forEach((item4) => {
                                            item4.maTypeName = item3.typeName 
                                            item4.maTypeId = item3.typeId
                                        })
                                    }
                                })
                            }
                        })
                    }
                })
            })
        },
        /** 转换菜单数据结构 */
        normalizer(node) {
            if (node.children && !node.children.length) {
                delete node.children;
            }
            return {
                id: node.typeId,
                label: node.typeName,
                children: node.children,
            };
        },
        typeChange(e){
            
            // console.log(e)
            if(e.maTypeId&&e.maTypeId!=""){  
                    this.dialogForm.typeId=e.typeId;
                    this.dialogForm.maTypeId=e.maTypeId;
                    this.dialogForm.maTypeName=e.maTypeName; 
                    this.$refs.dialogForm.clearValidate()
            }else{
                this.$modal.msgError("所选类型无规格!");
                setTimeout(()=>{
                    this.dialogForm.typeId=null; 
                    this.dialogForm.maTypeId=null;
                    this.dialogForm.maTypeName=null;
                },1000)
            } 
        },
        checkNum() {   
                this.dialogForm.qrNum=Number(String(this.dialogForm.qrNum).replace(/[^\d]/g,''))  
            if (this.dialogForm.qrNum <= 1) {
                this.dialogForm.qrNum = 1;
            }
        },
        // 新增
        handleAdd() {
            this.open=true; 
            this.dialogForm={
                maTypeName:null,
                maTypeId:null,
                typeId:null,
                supplierId:null,
                qrNum:null,
                remark:null
            },
            this.resetForm('dialogForm')
        },
        cancelDialog(){
            this.open=false; 
            this.resetForm('dialogForm')
        },
        //确认新增
        confirmAdd(){
            this.$refs.dialogForm.validate(async (valid) => {
                if (!valid) {
                    return false
                } else {
                    console.log(this.dialogForm) 
                    const res = await addQrCodeApi(this.dialogForm)
                    if (res.code == 200) {
                        this.$message({ type: 'success', message: res.msg }) 
                        this.resetQuery()
                    }
                }
            })     
        },       
        // 下载
        handleExport() {
            console.log('数据导出')
            console.log(this.selectList)  
            downloadQrCodesApi({qrIds:this.selectList}).then(res => {
              downloadFile({ fileName: `二维码_${new Date().getTime()}.zip`, fileData: res, fileType: 'application/zip;charset=utf-8' })
            })
        },
        // 列表复选框
        handleSelectionChange(validSelection) {
            this.selectList = validSelection.map(item=>item.id);
            this.single = validSelection.length !== 1;
            this.multiple = !validSelection.length;
        },










        // 删除
        handleNotice(row) {
            this.$confirm('是否确定删除二维码', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => { 
                let param = {
                    boxId:row.boxId
                }
                // return delQrCodeBoxApi(param);
            }).then(() => {
                this.getList();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => {});
        }, 
    },
}
</script>
<style lang="scss" scoped>
// .qrcode{
//   height: 300px;
//   width: 300px;
// }
.uploadImg {
    padding-top: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
}
.boxCode {
    margin-top: 10px;
    padding-bottom: 20px;
    font-size: 18px;
}
::v-deep.el-table .fixed-width .el-button--mini {
    width: 60px !important;
    margin-bottom: 10px;
}
</style>