<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
            <el-form-item 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 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>
                <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">导出数据</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row> -->
        <el-table border :data="tableList" v-loading="loading" @selection-change="handleSelectionChange">
            <!-- <el-table-column type="selection" width="55" align="center" /> -->
            <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="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="boxName" show-overflow-tooltip/>
            <el-table-column label="标准箱编码" align="center" prop="boxCode" show-overflow-tooltip/>
            <el-table-column label="标准箱机具数" align="center" prop="devNum" show-overflow-tooltip/>
            <el-table-column label="创建日期" align="center" prop="createTime" show-overflow-tooltip/>
            <el-table-column label="操作" align="center" width="400">
                <template slot-scope="{ row }">
                    <el-button size="mini" @click="handleView(row)">
                        查看
                    </el-button>
                    <el-button size="mini" type="primary" @click="downloadQrCode(row)">
                        下载
                    </el-button>
                    <el-button size="mini" type="primary" @click="handleDetail(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="1000px" append-to-body>
            <el-form :model="queryDialogForm" ref="queryDialogForm" size="small" :inline="true"  label-width="80px">
                <el-form-item prop="keyWord">
                    <el-input v-model="queryDialogForm.keyWord" placeholder="请输入关键字" clearable maxlength="20"/>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search"
                        size="mini" @click="handleQueryDialog"
                        >查询</el-button>
                    <el-button icon="el-icon-refresh"
                        size="mini" @click="resetQueryDialog"
                        >重置</el-button>
                </el-form-item>
            </el-form>
            <el-table border :data="tableListDialog">
                <el-table-column label="序号" align="center" type="index">
                    <template slot-scope="scope">
                        <span>{{ (queryDialogForm.pageNum - 1) * queryDialogForm.pageSize + scope.$index + 1 }}</span>
                    </template>
                </el-table-column>
                <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="createBy" show-overflow-tooltip/>
                <!-- <el-table-column label="操作" align="center" width="120">
                    <template slot-scope="{ row }">
                        <el-button size="mini" type="danger">
                            删除
                        </el-button>
                    </template>
                </el-table-column> -->
            </el-table>
            <pagination :total="totalDialog"
                    v-show="totalDialog > 0"
                    :page.sync="queryDialogForm.pageNum"
                    :limit.sync="queryDialogForm.pageSize"
                    @pagination="getDialogList"
            />
        </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.boxCode }}</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 { getQrCodeBoxListApi,addQrCodeBoxApi,editQrCodeBoxApi,delQrCodeBoxApi,getBoxDetailListApi } from '@/api/ma/standardBox'
import QRCode from 'qrcodejs2';
import html2canvas from 'html2canvas';
export default {
    name: 'StandardBox',
    dicts: ['qr_box_type'],
    data() {
        return {
            total: 0, //                总条数
            loading: false, //           遮罩层
            showSearch: true, //        显示搜索条件
            tableList: [], //            列表数据源
            queryTime: [], //           日期数据源
            selectList: [], //          列表选中数据
            // 列表查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                status: '',
                endTime: '',
                keyWord: '',
                startTime: '',
                boxType: 1
            },
            open:false,
            queryDialogForm:{
                keyWord: '',
                pageNum: 1,
                pageSize: 10,
            },
            totalDialog:0,
            tableListDialog:[],
            uploadOpen: false,
            rowObj:{},
            boxCode:""
        }
    },
    created() {
        this.getList()
    },
    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 getQrCodeBoxListApi(this.queryParams)
            this.tableList = res.data.rows
            this.total = res.data.total
            this.loading = false
        },
        // 搜索按钮
        handleQuery() {
            this.queryParams.pageNum = 1
            this.getList()
        },
        // 重置按钮
        resetQuery() {
            this.queryTime = []
            this.resetForm('queryForm')
            this.queryParams.pageNum = 1
            this.queryParams.endTime = ''
            this.queryParams.pageSize = 10
            this.queryParams.startTime = ''
            this.getList()
        },
        handleAdd(){
            console.log('新增')
            addQrCodeBoxApi({ boxType: 1 }).then((response) => {
            if (response.code == 200) {
              this.$modal.msgSuccess("新增成功");
            }
            this.getList()
          });
        },
        //二维码查看
        handleView(row) {
            this.rowObj = row
            this.uploadOpen = true
            this.boxCode = row.boxCode
            let str = row.boxCode
            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 = 59 // 放大文字
            const maxTextWidth = qrSize

            const qrcode = new QRCode(qrContainer, {
                text: row.boxCode,
                width: qrSize,
                height: qrSize,
                colorDark: '#000000',
                colorLight: '#ffffff',
                correctLevel: QRCode.CorrectLevel.H
            })

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

                // 计算换行
                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.boxCode
        //             alink.click()
        //         })
        //     }
        // },
        // 设备明细
        handleDetail(row) {
            this.open=true;
            this.queryDialogForm.boxId = row.boxId;
            this.resetQueryDialog()
        },
        // 获取列表数据
        async getDialogList() {
            const res = await getBoxDetailListApi(this.queryDialogForm)
            console.log('🚀 ~ getDialogList ~ res:', res)
            this.tableListDialog = res.rows
            // this.tableListDialog = [{maType:"抱杆",typeName:"10t",maCode:"bg121334343",updateBy:"张三"},{maType:"抱杆",typeName:"10t",maCode:"bg121334343",updateBy:"张三"},{maType:"抱杆",typeName:"10t",maCode:"bg121334343",updateBy:"张三"},{maType:"抱杆",typeName:"10t",maCode:"bg121334343",updateBy:"张三"}]
            this.totalDialog = res.total
        },
        //弹窗搜索
        handleQueryDialog() {
            this.queryDialogForm.pageNum = 1
            this.getDialogList()
        },
         //弹窗搜索重置
        resetQueryDialog() {
            this.resetForm('queryDialogForm')
            this.queryDialogForm.pageNum = 1
            this.getDialogList()
        },

        // 删除
        handleNotice(row) {
            this.$confirm('是否确定删除标准箱', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                let param = {
                    boxId:row.boxId
                }
                return delQrCodeBoxApi(param);
            }).then(() => {
                this.getList();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => {});
        },
        // 导出数据
        handleExport() {
            console.log('数据导出')
            // this.download(
            //     "/material/purchase_check_info/export",
            //     { ...this.queryParams},
            //     `新购到货入库_${new Date().getTime()}.xlsx`
            // );
        },
        // 列表复选框
        handleSelectionChange(list) {
            this.selectList = list
        },
    },
}
</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: 35px;
}
::v-deep.el-table .fixed-width .el-button--mini {
    width: 60px !important;
    margin-bottom: 10px;
}
</style>
