/**
 * @description 支付状态弹窗组件
 */
<template>
    <div class="pay-status-popup">
        <el-dialog
            :visible.sync="show"
            width="30%"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            :show-close="false"
            custom-class="pay-dialog">

            <!-- 支付成功状态 -->
            <template v-if="status === PAY_STATUS.SUCCESS">
                <div class="status-icon">
                    <i class="el-icon-success success"></i>
                </div>
                <div class="status-message">支付成功</div>

                <!-- 打印选项 -->
                <div class="action-buttons" v-if="!hidePointer">
                    <el-button type="primary" @click="handlePrint(PRINT_TYPE.RECEIPT)">
                        <i class="el-icon-printer"></i> 打印小票
                    </el-button>
                    <el-button type="primary" @click="handlePrint(PRINT_TYPE.BARCODE)">
                        <i class="el-icon-document"></i> 打印条码
                    </el-button>
                    <el-button @click="handleClose">关闭</el-button>
                </div>
                <div class="action-buttons" v-else>
                    <el-button type="primary" @click="handleConfirm">确认</el-button>
                </div>
            </template>

            <!-- 未支付状态 -->
            <template v-if="status === PAY_STATUS.UNPAID">
                <div class="status-icon">
                    <i class="el-icon-warning warning"></i>
                </div>
                <div class="status-message">请支付后取衣</div>

                <!-- 支付金额 -->
                <div class="payment-info">
                    <div class="info-label">需支付金额</div>
                    <div class="amount">
                        <span class="currency">￥</span>
                        <span class="value">{{ orderInfo.payAmount }}</span>
                    </div>
                </div>

                <!-- 支付方式选择 -->
                <div class="payment-method">
                    <div class="info-label">支付方式</div>
                    <el-radio-group v-model="payType" @change="handlePayTypeChange">
                        <el-radio-button
                            v-if="!hideUser"
                            :label="PAY_TYPE.BALANCE">
                            余额支付
                        </el-radio-button>
                        <el-radio-button :label="PAY_TYPE.CASH">现金支付</el-radio-button>
                        <el-radio-button :label="PAY_TYPE.SCAN">扫码支付</el-radio-button>
                    </el-radio-group>
                </div>

                <!-- 余额支付信息 -->
                <div v-if="payType === PAY_TYPE.BALANCE && !hideUser" class="balance-info">
                    <el-descriptions
                        border
                        direction="vertical"
                        :column="3"
                        :label-style="{ width: '140px' }">
                        <el-descriptions-item label="用户">
                            {{ appUserInfo.realName }}
                        </el-descriptions-item>
                        <el-descriptions-item label="当前余额（元）">
                            {{ calculateTotalBalance }}
                        </el-descriptions-item>
                        <el-descriptions-item label="支付后余额（元）">
                            {{ calculateBalanceAfterPay }}
                        </el-descriptions-item>
                    </el-descriptions>
                </div>

                <!-- 扫码支付输入框 -->
                <div v-if="payType === PAY_TYPE.SCAN" class="scan-input">
                    <div class="info-label">付款码</div>
                    <el-input
                        ref="scanInput"
                        v-model="authCode"
                        clearable
                        placeholder="请扫描付款码"
                        @keyup.enter.native="handlePay">
                        <i slot="prefix" class="el-icon-camera"></i>
                    </el-input>
                </div>

                <!-- 操作按钮 -->
                <div class="action-buttons">
                    <el-button
                        type="primary"
                        :loading="paying"
                        @click="handlePay">
                        确认支付
                    </el-button>
                    <el-button @click="handleClose">取消</el-button>
                </div>
            </template>

            <!-- 支付中状态 -->
            <template v-if="status === PAY_STATUS.PAYING || status === PAY_STATUS.WAITING">
                <div class="status-icon">
                    <i class="el-icon-loading"></i>
                </div>
                <div class="status-message">支付确认中，请等待...</div>
                <div class="action-buttons" v-if="showPaySuccessBtn">
                    <el-button type="primary" @click="handlePaySuccess">
                        已确认支付
                    </el-button>
                </div>
            </template>

            <!-- 支付失败状态 -->
            <template v-if="status === PAY_STATUS.FAILED">
                <div class="status-icon">
                    <i class="el-icon-error error"></i>
                </div>
                <div class="status-message error-message">{{ errorMessage }}</div>

                <!-- 重试支付方式选择 -->
                <div v-if="!hideUser" class="payment-method">
                    <div class="info-label">重选支付方式</div>
                    <el-radio-group v-model="payType" @change="handlePayTypeChange">
                        <el-radio-button :label="PAY_TYPE.BALANCE">余额支付</el-radio-button>
                        <el-radio-button :label="PAY_TYPE.CASH">现金支付</el-radio-button>
                        <el-radio-button :label="PAY_TYPE.SCAN">扫码支付</el-radio-button>
                    </el-radio-group>
                </div>

                <!-- 操作按钮 -->
                <div class="action-buttons">
                    <el-button
                        v-if="!hideUser"
                        type="primary"
                        @click="handleRetry">
                        重试支付
                    </el-button>
                    <el-button @click="handleClose">关闭</el-button>
                </div>
            </template>

            <!-- 定价成功状态 -->
            <template v-if="status === PAY_STATUS.PRICE_SUCCESS">
                <div class="status-icon">
                    <i class="el-icon-success success"></i>
                </div>
                <div class="status-message">定价成功</div>
                <div class="action-buttons">
                    <el-button type="primary" @click="handleConfirm">确认</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import { getLodop } from '@/utils/lodopUtils'
import { getClothItem, listOrderClothItem } from '@/api/order/clothItem'
import { getMemberInfoById } from '@/api/app/user'
import { clothOrderPay, getOrderPayResult } from '@/api/order/cloth'
import { PAY_STATUS, PAY_TYPE, PRINT_TYPE } from '../constants/payStatus'

export default {
    name: 'PayStatusPopup',

    props: {
        hidePointer: {
            type: Boolean,
            default: false
        },
        hideUser: {
            type: Boolean,
            default: false
        }
    },

    data() {
        return {
            show: false,
            status: PAY_STATUS.UNPAID,
            orderInfo: {},
            // 打印相关
            printerList: [],
            printData: null,
            // 支付相关
            payType: PAY_TYPE.BALANCE,
            paying: false,
            appUserInfo: {},
            authCode: '',
            // 支付结果查询
            payResultTimer: null,
            showPaySuccessBtn: false,
            resultQueryCount: 0,
            errorMessage: '',
            // 常量
            PAY_STATUS,
            PAY_TYPE,
            PRINT_TYPE
        }
    },

    computed: {
        // 计算总余额
        calculateTotalBalance() {
            if (!this.appUserInfo) return 0
            return this.appUserInfo.rechargeBalance + this.appUserInfo.giveBalance + this.appUserInfo.welfareBalance
        },

        // 计算支付后余额
        calculateBalanceAfterPay() {
            return this.calculateTotalBalance - (this.orderInfo.payAmount || 0)
        }
    },

    mounted() {
        // 初始化打印机
        this.initPrinter()
    },

    beforeDestroy() {
        // 清理定时器
        this.clearPayResultTimer()
    },

    methods: {
        /**
         * 初始化打印机
         */
        initPrinter() {
            // 获取打印机配置
            this.printerList = JSON.parse(this.$cache.local.get('printerSeting') || '[]')
        },

        /**
         * 打开弹窗
         */
        open(status, orderInfo, userInfo = null) {
            this.orderInfo = orderInfo
            this.status = status
            this.errorMessage = ''
            this.showPaySuccessBtn = false
            this.paying = false

            // 根据状态处理
            switch (status) {
                case PAY_STATUS.SUCCESS:
                    if (orderInfo.id && !this.hidePointer) {
                        this.fetchPrintData(orderInfo)
                    }
                    break

                case PAY_STATUS.UNPAID:
                    this.initPayment(orderInfo, userInfo)
                    break

                case PAY_STATUS.PAYING:
                    this.handlePayProcess(orderInfo, userInfo)
                    break

                case PAY_STATUS.FAILED:
                    this.errorMessage = orderInfo.payMsg
                    break
            }

            this.show = true
        },

        /**
         * 初始化支付
         */
        initPayment(orderInfo, userInfo) {
            this.authCode = ''
            this.appUserInfo = {}

            if (this.hideUser) {
                this.payType = PAY_TYPE.CASH
            } else {
                this.payType = PAY_TYPE.BALANCE
                if (orderInfo.appUserId) {
                    this.fetchUserInfo(orderInfo.appUserId)
                }
            }
        },

        /**
         * 获取用户信息
         */
        async fetchUserInfo(userId) {
            try {
                const response = await getMemberInfoById({ appUserId: userId })
                this.appUserInfo = response.data
            } catch (error) {
                this.$message.error('获取用户信息失败')
            }
        },

        /**
         * 获取打印数据
         */
        async fetchPrintData(orderInfo) {
            try {
                const res = await getClothItem(orderInfo.id)
                if (res) {
                    this.printData = res.data
                    // 获取订单衣物列表
                    const clothList = await listOrderClothItem({
                        pageSize: 99999,
                        pageNum: 1,
                        orderNo: orderInfo.orderNo
                    })
                    this.printData.orderClothDetails = clothList.data.records
                }
            } catch (error) {
                this.$message.error('获取打印数据失败')
            }
        },

        /**
         * 处理支付方式变更
         */
        handlePayTypeChange(value) {
            this.payType = value
            this.authCode = ''

            if (value === PAY_TYPE.SCAN) {
                this.$nextTick(() => {
                    this.$refs.scanInput?.focus()
                })
            }
        },

        /**
         * 处理支付
         */
        async handlePay() {
            // 验证支付条件
            if (!this.validatePayment()) return

            this.paying = true
            try {
                const res = await clothOrderPay({
                    appUserId: this.orderInfo.appUserId,
                    payType: this.payType,
                    authCode: this.authCode,
                    orderNo: this.orderInfo.orderNo,
                    payAmount: this.orderInfo.payAmount
                })

                if (res) {
                    this.handlePayResult(res.data)
                }
            } catch (error) {
                this.handlePayError(error)
            } finally {
                this.paying = false
            }
        },

        /**
         * 验证支付条件
         */
        validatePayment() {
            if (this.payType === PAY_TYPE.SCAN && !this.authCode) {
                this.$message.warning('请先扫描付款码')
                return false
            }

            if (this.payType === PAY_TYPE.BALANCE) {
                if (this.calculateTotalBalance < this.orderInfo.payAmount) {
                    this.$message.warning('余额不足')
                    return false
                }
            }

            return true
        },

        /**
         * 处理支付结果
         */
        handlePayResult(result) {
            switch (result.payResult) {
                case 100: // 需要查询结果
                    this.status = PAY_STATUS.WAITING
                    this.startPayResultQuery()
                    break

                case 101:
                case 0: // 支付失败
                    this.status = PAY_STATUS.FAILED
                    this.errorMessage = result.payMsg
                    break

                case 200: // 支付成功
                    this.status = PAY_STATUS.SUCCESS
                    this.$emit('paySuccess')
                    break
            }
        },

        /**
         * 处理支付错误
         */
        handlePayError(error) {
            this.status = PAY_STATUS.FAILED
            this.errorMessage = error.data?.msg || '支付失败，请重试'
            this.authCode = ''
        },

        /**
         * 开始查询支付结果
         */
        startPayResultQuery() {
            this.resultQueryCount = 0
            this.queryPayResult()
        },

        /**
         * 查询支付结果
         */
        async queryPayResult() {
            try {
                const res = await getOrderPayResult({
                    orderNo: this.orderInfo.orderNo
                })

                if (res) {
                    this.handlePayResult(res.data)

                    // 继续查询
                    if (res.data.payResult === 100) {
                        this.resultQueryCount++
                        if (this.resultQueryCount >= 6) {
                            this.showPaySuccessBtn = true
                        }
                        this.payResultTimer = setTimeout(() => {
                            this.queryPayResult()
                        }, 5000)
                    }
                }
            } catch (error) {
                this.handlePayError(error)
            }
        },

        /**
         * 清理支付结果查询定时器
         */
        clearPayResultTimer() {
            if (this.payResultTimer) {
                clearTimeout(this.payResultTimer)
                this.payResultTimer = null
            }
        },

        /**
         * 处理打印
         */
        handlePrint(type) {
            const LODOP = getLodop(null, null, true)
            if (!LODOP) {
                return // 如果获取不到打印对象，getLodop 已经显示了错误信息
            }

            const printer = this.printerList.find(p => p.printType === type)
            if (!printer) {
                this.$message.error('未找到对应打印机配置')
                return
            }

            if (type === PRINT_TYPE.RECEIPT) {
                this.printReceipt(printer.printName)
            } else {
                this.printBarcode(printer.printName)
            }

            this.handleClose()
        },

        /**
         * 打印小票
         */
        printReceipt(printerName) {
            if (!this.printData) {
                this.$message.error('打印数据不完整')
                return false
            }

            try {
                const LODOP = getLodop(null, null, true)
                if (!LODOP) return false

                LODOP.SET_PRINT_PAGESIZE(3, 580, 40, "")
                LODOP.SET_PRINTER_INDEX(printerName)

                // 设置打印内容
                let printContent = this.generateReceiptContent()
                LODOP.ADD_PRINT_HTM(0, 0, "100%", "100%", printContent)

                // 直接打印
                if (!LODOP.PRINT()) {
                    this.$message.error('打印失败')
                    return false
                }

                return true
            } catch (err) {
                console.error('打印小票出错:', err)
                this.$message.error('打印过程出现错误')
                return false
            }
        },

        /**
         * 生成小票内容
         */
        generateReceiptContent() {
            const { printData } = this
            if (!printData) return ''

            const styles = `
                <style>
                    .receipt-wrapper {
                        font-family: Arial, sans-serif;
                        font-size: 12px;
                        width: 100%;
                        text-align: center;
                    }
                    .shop-info {
                        margin-bottom: 10px;
                    }
                    .shop-name {
                        font-size: 14px;
                        font-weight: bold;
                    }
                    .divider {
                        border-top: 1px dashed #000;
                        margin: 5px 0;
                    }
                    .order-info {
                        text-align: left;
                        margin: 5px 0;
                    }
                    .cloth-item {
                        margin: 5px 0;
                        padding: 5px 0;
                        border-bottom: 1px dashed #ccc;
                    }
                    .cloth-name {
                        font-weight: bold;
                    }
                    .total-info {
                        margin-top: 10px;
                        text-align: right;
                    }
                    .qrcode {
                        margin: 10px auto;
                        width: 100px;
                        height: 100px;
                    }
                </style>
            `

            const content = `
                <div class="receipt-wrapper">
                    ${styles}
                    <div class="shop-info">
                        <div class="shop-name">${printData.shopName || '洗衣店'}</div>
                        <div>${printData.shopAddress || ''}</div>
                        <div>电话：${printData.shopPhone || ''}</div>
                    </div>

                    <div class="divider"></div>

                    <div class="order-info">
                        <div>订单号：${printData.orderNo}</div>
                        <div>下单时间：${this.$parseTime(printData.createTime)}</div>
                        <div>客户：${printData.customerName}</div>
                        <div>电话：${printData.customerPhone}</div>
                    </div>

                    <div class="divider"></div>

                    <div class="cloth-list">
                        ${this.generateClothListHtml()}
                    </div>

                    <div class="divider"></div>

                    <div class="total-info">
                        <div>衣物总数：${printData.orderClothDetails?.length || 0}件</div>
                        <div>合计金额：￥${printData.totalAmount || 0}</div>
                        <div>实付金额：￥${printData.payAmount || 0}</div>
                    </div>

                    <div class="divider"></div>

                    <div>
                        <div>预计取衣时间：${this.$parseTime(printData.expectedPickTime)}</div>
                        <div>注意事项：</div>
                        <div>1. 请妥善保管此小票，取衣时请出示</div>
                        <div>2. 超过30天未取的衣物，本店不负责保管</div>
                    </div>

                    <div class="qrcode">
                        <!-- 这里可以添加二维码图片 -->
                    </div>
                </div>
            `

            return content
        },

        /**
         * 生成衣物列表HTML
         */
        generateClothListHtml() {
            const { orderClothDetails = [] } = this.printData

            return orderClothDetails.map((item, index) => `
                <div class="cloth-item">
                    <div class="cloth-name">${index + 1}. ${item.clothName}</div>
                    <div>
                        颜色：${item.orderClothColorDTOS?.map(c => c.clothColorName).join('/')}
                        品牌：${item.clothBrandName || '无'}
                    </div>
                    <div>
                        洗涤方式：${item.clothWashModeName || '普通洗涤'}
                        ${item.orderClothFlawDTOS?.length ? `瑕疵：${item.orderClothFlawDTOS.map(f => f.clothFlawName).join('/')}` : ''}
                    </div>
                    <div style="text-align: right;">
                        单价：￥${item.defaultPrice}
                        ${item.specialPrice ? `特殊处理费：￥${item.specialPrice}` : ''}
                    </div>
                </div>
            `).join('')
        },

        /**
         * 打印条码
         */
        printBarcode(printerName) {
            if (!this.printData?.orderNo) {
                this.$message.error('订单号不能为空')
                return false
            }

            try {
                const LODOP = getLodop(null, null, true)
                if (!LODOP) return false

                LODOP.SET_PRINT_PAGESIZE(1, 800, 400, "")
                LODOP.SET_PRINTER_INDEX(printerName)

                // 设置条码打印内容
                const barcodeContent = this.generateBarcodeContent()
                LODOP.ADD_PRINT_HTM(0, 0, "100%", "100%", barcodeContent)

                // 直接打印
                if (!LODOP.PRINT()) {
                    this.$message.error('打印失败')
                    return false
                }

                return true
            } catch (err) {
                console.error('打印条码出错:', err)
                this.$message.error('打印过程出现错误')
                return false
            }
        },

        /**
         * 生成条码内容
         */
        generateBarcodeContent() {
            const { printData } = this
            if (!printData) return ''

            const styles = `
                <style>
                    .barcode-wrapper {
                        font-family: Arial, sans-serif;
                        font-size: 12px;
                        width: 100%;
                        text-align: center;
                    }
                    .barcode-info {
                        margin: 5px 0;
                    }
                    .order-no {
                        font-size: 14px;
                        font-weight: bold;
                    }
                </style>
            `

            const content = `
                <div class="barcode-wrapper">
                    ${styles}
                    <div class="barcode-info">
                        <div class="order-no">${printData.orderNo}</div>
                        <div>${printData.customerName} ${printData.customerPhone}</div>
                        <div>${this.$parseTime(printData.createTime)}</div>
                    </div>

                    <!-- 这里可以添加条码图片 -->
                </div>
            `

            return content
        },

        /**
         * 处理确认
         */
        handleConfirm() {
            this.show = false
            this.$emit('confirm', this.orderInfo)
        },

        /**
         * 处理支付成功
         */
        handlePaySuccess() {
            this.show = false
            this.clearPayResultTimer()
            this.$emit('paySuccess')
        },

        /**
         * 处理重试
         */
        handleRetry() {
            this.handlePay()
        },

        /**
         * 处理关闭
         */
        async handleClose() {
            let confirmMessage = ''
            switch (this.status) {
                case PAY_STATUS.SUCCESS:
                    confirmMessage = '是否关闭打印操作？'
                    break
                case PAY_STATUS.UNPAID:
                    confirmMessage = '是否取消支付操作？'
                    break
                case PAY_STATUS.PAYING:
                case PAY_STATUS.WAITING:
                    confirmMessage = '请确认客户已完成付款再关闭？'
                    break
                default:
                    this.show = false
                    return
            }

            try {
                await this.$confirm(confirmMessage)
                this.show = false
                if (this.status === PAY_STATUS.PAYING || this.status === PAY_STATUS.WAITING) {
                    this.clearPayResultTimer()
                    this.$emit('paySuccess')
                }
            } catch (error) {
                // 用户取消关闭
            }
        }
    }
}
</script>

<style lang="scss" scoped>
.pay-dialog {
    .status-icon {
        font-size: 100px;
        text-align: center;
        margin-bottom: 20px;

        .success { color: #67c23a; }
        .warning { color: #e6a23c; }
        .error { color: #f56c6c; }
        .loading { color: #409EFF; }
    }

    .status-message {
        font-size: 20px;
        text-align: center;
        margin-bottom: 30px;
        color: #606266;

        &.error-message {
            color: #f56c6c;
        }
    }

    .payment-info,
    .payment-method,
    .scan-input {
        padding: 0 40px 20px;

        .info-label {
            font-size: 14px;
            color: #606266;
            margin-bottom: 10px;
        }
    }

    .amount {
        .currency {
            font-size: 16px;
            color: #f56c6c;
        }

        .value {
            font-size: 24px;
            font-weight: bold;
            color: #f56c6c;
        }
    }

    .balance-info {
        padding: 0 30px 20px;
    }

    .action-buttons {
        text-align: center;
        padding: 20px;
        border-top: 1px solid #EBEEF5;

        .el-button {
            min-width: 120px;
            margin: 0 10px;
        }
    }
}
</style>
