<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="生成日期" prop="startTime">
                <el-date-picker
                v-model="queryParams.startTime"
                value-format="yyyy-MM-dd"
                type="date"
                placeholder="开始日期"
                @change="() => queryParams.endTime = ''"
                style="width: 130px"
                />
            </el-form-item>
            <el-form-item>-</el-form-item>
            <el-form-item prop="endTime">
                <el-date-picker
                v-model="queryParams.endTime"
                value-format="yyyy-MM-dd"
                type="date"
                placeholder="结束日期"
                :picker-options="{ disabledDate: (t) => t.getTime() < new Date(queryParams.startTime).getTime() - 86400000}"
                style="width: 130px"
                />
            </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="bindStatus">
                <el-select
                v-model="queryParams.bindStatus"
                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="qrId">
            <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="supplierName" show-overflow-tooltip/> 
            <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip/> 
              <el-table-column label="状态" align="center" prop="bindStatus" show-overflow-tooltip>
                <template slot-scope="scope">
                    <span v-if="scope.row.bindStatus==0">未绑定</span>
                    <span v-if="scope.row.bindStatus==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="650px" append-to-body>
            <el-form :model="dialogForm" ref="dialogForm" size="small" :rules="rules"  label-width="120px" style="min-height: 350px;">
                <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" v-if="uploadOpen">
                <div class="uploadImg">
                    <div id="qrcode" class="qrcode" ref="codeItem"></div> 
                </div>
                <div class="boxCode">{{ rowObj.maCode }}</div>
            </div>
            <div slot="footer" class="dialog-footer" style="text-align: center">
                <el-button type="primary" @click="downloadQrCode(rowObj)">下 载</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: 'Code',
    dicts: ['qr_box_type'],
    components: { Treeselect },
    data() {
        return {
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            statusList: [{id:"",name:"全部"},{id:"1",name:"已绑定"},{id:"0",name:"未绑定"}], 
            total: 0, //                总条数
            loading: false, //           遮罩层
            showSearch: true, //        显示搜索条件 
            tableList: [], //            列表数据源
            queryTime: [], //           日期数据源
            selectList: [], //          列表选中数据
            // 列表查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                bindStatus: '',
                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.rows
            this.total = res.total
            this.loading = false 
        },
        // 搜索按钮
        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 = "http://ahjj.jypxks.com:9988/imw/backstage/machine/qrCodePage?qrcode="+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)
        },
        //二维码下载
        downloadQrCode(row) {
            const qrContainer = document.createElement('div')
            document.body.appendChild(qrContainer)

            const qrSize = 512 // 放大二维码
            const padding = 20 // 边距也放大
            const fontSize = 68 // 放大文字
            const maxTextWidth = qrSize

            const qrcode = new QRCode(qrContainer, {
                text: 'http://ahjj.jypxks.com:9988/imw/backstage/machine/qrCodePage?qrcode=' + row.qrCode,
                width: qrSize,
                height: qrSize,
                colorDark: '#000000',
                colorLight: '#ffffff',
                correctLevel: QRCode.CorrectLevel.H
            })

            setTimeout(() => {
                const img = qrContainer.querySelector('img') || qrContainer.querySelector('canvas')
                const text = row.maCode || ''

                // 计算换行
                const ctxMeasure = document.createElement('canvas').getContext('2d')
                ctxMeasure.font = `${fontSize}px Arial`
                const words = text.split('')
                let line = ''
                const lines = []
                for (let i = 0; i < words.length; i++) {
                const testLine = line + words[i]
                if (ctxMeasure.measureText(testLine).width > maxTextWidth) {
                    lines.push(line)
                    line = words[i]
                } else {
                    line = testLine
                }
                }
                lines.push(line)

                // 动态计算画布高度
                const lineHeight = fontSize + 10
                const qrCanvas = document.createElement('canvas')
                qrCanvas.width = qrSize + padding * 2
                qrCanvas.height = qrSize + padding * 2 + lines.length * lineHeight

                const ctx = qrCanvas.getContext('2d')
                ctx.fillStyle = '#fff'
                ctx.fillRect(0, 0, qrCanvas.width, qrCanvas.height)

                ctx.drawImage(img, padding, padding, qrSize, qrSize)

                // 绘制文字
                ctx.fillStyle = '#000'
                ctx.font = `${fontSize}px Arial`
                ctx.textAlign = 'center'
                lines.forEach((ln, index) => {
                ctx.fillText(ln, qrCanvas.width / 2, qrSize + padding + fontSize / 1.2 + index * lineHeight)
                })

                // 下载
                const a = document.createElement('a')
                a.href = qrCanvas.toDataURL('image/png')
                a.download = text + '.png'
                a.click()

                document.body.removeChild(qrContainer)
            }, 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({manageType:"0"}).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,index4) => { 
                                                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: "新增成功" }) 
                        this.open=false; 
                        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' })
                this.$refs.multipleTable.clearSelection();
            })
        },
        // 列表复选框
        handleSelectionChange(validSelection) {
            this.selectList = validSelection.map(item=>item.qrId);
            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: 33px;
    font-weight: bold;
    color: #000;
}
::v-deep.el-table .fixed-width .el-button--mini {
    width: 60px !important;
    margin-bottom: 10px;
}
</style>