<template>
    <!-- 改签对话框 -->
    <el-dialog 
    title="订单升舱" 
    :visible.sync="rebookDialog" 
    width="95%" 
    append-to-body 
    class="rebook1_dialog"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :modal="false"
    :before-close="handleClose"
    center
    >
        <div class="rebook1_box" v-loading="loading">
            <div class="rebook1_from-box">
                <div class="rebook1_from">
                    <el-form :model="rebookForm" ref="rebookForm" label-width="100px" :rules="rules">
                        <el-form-item label="剧目名称：" style="margin-bottom: 0px;">
                            <span>{{ rebookForm.performName }}</span>
                        </el-form-item>    
                        <el-form-item label="票务名称：" style="margin-bottom: 0px;">
                            <span>{{ rebookForm.goodsName }}</span>
                        </el-form-item>
                        <el-form-item label="座位类型：" style="margin-bottom: 0px;">
                            <span>{{ rebookForm.seatTypeName }}</span>
                        </el-form-item>
                        <el-form-item label="订单座位数：" style="margin-bottom: 0px;">
                            <span>{{ rebookForm.touristNum }}个</span>
                        </el-form-item>
                        <el-form-item label="选择日期：" prop="performDate" style="margin-bottom: 0px;">
                            <span>{{ rebookForm.performDate }}</span>
                        </el-form-item>
                        <el-form-item label="选择场次：" prop="performTimeId" style="margin-bottom: 0px;">
                            <span>{{ rebookForm.performTimeStart }} — {{ rebookForm.performTimeEnd }} </span>
                        </el-form-item>
                        <el-form-item label="票档：" prop="seatTypeId">
                            <el-select
                                v-model="rebookForm.seatTypeId"
                                placeholder="请选择票档"
                                style="width: 100%"
                                @change="querySeatListFun"
                                >
                                    <el-option
                                    v-for="item in intervalList"
                                    :key="item.seatTypeId"
                                    :label="item.seatTypeName"
                                    :value="item.seatTypeId"
                                    />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="订单总额：">
                            <span>{{ rebookForm.realPrice || 0 }}元</span>
                        </el-form-item>
                        <el-form-item v-if="rebookForm.diffPrice < 0" label="升舱费用：">
                            <span>退费{{ Math.abs(rebookForm.diffPrice) }}元</span>
                        </el-form-item>
                        <el-form-item v-if="rebookForm.diffPrice > 0" label="升舱费用：">
                            <el-input-number 
                            v-model="rebookForm.goodsDiffAmount" 
                            controls-position="right"
                            :min="0"></el-input-number>
                        </el-form-item>
                        <el-form-item v-if="rebookForm.diffPrice > 0 && !rebookForm.timeId" label="支付方式 :" prop="paymentType">
                            <el-radio-group v-model="rebookForm.paymentType">
                                <el-radio label="1">扫码支付</el-radio>
                                <el-radio label="2">现金支付</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item v-if="rebookForm.diffPrice > 0 && rebookForm.timeId" label="支付方式 :" prop="paymentType">
                            <el-radio-group v-model="rebookForm.paymentType">
                                <el-radio label="3">对公支付</el-radio>
                                <el-radio label="6">挂账</el-radio>
                                <el-radio label="7">链接支付</el-radio>
                                <el-radio label="4">账户余额</el-radio>
                                <el-radio label="5">授信余额</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item v-if="rebookForm.diffPrice > 0 && rebookForm.paymentType == 2 " label="收取现金 :"  prop="realPrice_1">
                            <el-input @input="setRealPrice_1" style="width: 200px;" v-model="rebookForm.realPrice_1"></el-input>
                            <span>元</span>
                        </el-form-item>
                        <el-form-item label="找零金额 :" v-if="rebookForm.diffPrice > 0 && ruleForm.paymentType == 2">
                            ￥{{ rebookForm.small }}元
                        </el-form-item>
                        <el-form-item label="备注：">
                            <el-input
                                v-model="rebookForm.resubmitRemark"
                                placeholder="请输入备注"
                                clearable
                                type="textarea"
                                />
                        </el-form-item>
                    </el-form>
                    <div class="tip-box">
                        <p style="font-size: 12px;">温馨提示：仅限升舱一次，且升舱后禁止退款，确认要继续升舱吗。</p>
                    </div>
                </div>
                <div class="rebook1_seat" v-loading="seatLoading" :element-loading-text="seatLoadText">
                    <seatBox 
                    ref="seatBox" 
                    :seatTypeLimit="configStockNumObj"
                    @selectSeat="selectSeat"
                    height="100%"
                    />
                </div>
            </div>
            <div style="width: 100%;display: flex;justify-content: center;">
                <el-button @click="rebookDialog = false">取 消</el-button>
                <el-button type="primary" @click="submitRebook">确认升舱</el-button>
            </div>
            <!--  支付过程 控制  -->
            <div v-if="payStatus" class="increase-viewers-pay-status">
                <div class="increase-viewers-pay-status-info" v-if="!loading">
                    <span style="font-weight: 600;font-size: 20px;">提示</span>
                    <span style="padding: 10px 0;">
                        {{ payStatus==1 ? '生成订单失败!!!' : 
                        payStatus==2 ? '生成订单生成成功,请点击调取扫码盒子' : 
                        payStatus==4 ? '扫码支付失败!!!' :
                        payStatus==5 ? '请出示付款码!!!' :
                        payStatus==5.5 ? '扫码成功，支付中...' :
                        payStatus==5.6 ? '扫码成功，支付中...' :
                        payStatus==6 ? '连接扫码器失败!!!' :
                        payStatus==7 ? '用户支付失败或未支付,请重新连接支付!!!' :
                        payStatus==8 ? '用户支付成功,请点击打印票!!!' :
                        payStatus==9 ? '支付超时!!!' :
                        payStatus==10 ? '订单已关闭，请重新选择座位，再购买!!!' :
                        payStatus==3 ? '现金支付记录入库失败,请重新提交' : '未知状态' }}
                    </span>
                    <span v-if="payStatus==2">需支付{{ rebookForm.payAmount }}元</span>
                    <!-- 重新生成订单 1  -->
                    <div v-if="payStatus==1" style="display: flex;">
                        <el-button @click="payStatus = null" type="success">修改信息</el-button>
                        <el-button @click="orderInfoSubmitFun()" style="margin-left: 20px;" type="primary">重新生成订单</el-button>
                    </div>
                    <!--  生成订单成功 选择支付方式  -->
                    <div>
                        <!-- 扫码支付 2 -->
                        <el-button v-if="payStatus==2" @click="vbar_open(orderId)" type="success">扫码支付</el-button>
                        <!-- 扫码支付 4 -->
                        <el-button v-if="payStatus==4" @click="vbar_open(orderId)" type="success">重新扫码支付</el-button>
                        <!-- 重新支付 3 -->
                        <el-button v-if="payStatus==3" @click="gotoCashPayFun(orderId)" type="success">重新提交入库</el-button>
                        <!-- 重新支付 6  7 -->
                        <el-button v-if="payStatus==6 || payStatus==7" @click="vbar_open(orderId)" type="success">重新连接扫码支付</el-button>
                    
                        <!--   现金支付  -->
                        <el-button v-if="payStatus==2" @click="vbar_open(orderId)" type="success">扫码支付</el-button>
                        
                        <!--   现金支付  -->
                        <el-button v-if="payStatus==2" @click="vbar_open(orderId)" type="success">扫码支付</el-button>

                    </div>
                    
                    <!-- 打印 8  -->
                    <div v-if="payStatus==8">
                        <el-select v-model="printListId" placeholder="选择打印机">
                            <el-option 
                            :label="item.deviceName" 
                            :key="item.id" 
                            :value="item.id" 
                            v-for="(item) in printList"></el-option>
                        </el-select>
                        <el-button style="margin-left: 15px" @click="print" type="success">打印门票</el-button>
                        <el-button style="margin-left: 15px" @click="goTicketingCollections" type="success">跳转取票界面</el-button>
                    </div>
                    <!-- 支付超时 9  -->
                    <div v-if="payStatus==9">
                        <!-- <el-button @click="print" type="danger">取消支付</el-button> -->
                        <el-button @click="orderInfoSubmitFun()" type="primary">重新扫码</el-button>
                    </div>
                    <!-- 订单被关闭 10  -->
                    <div v-if="payStatus==10">
                        <!-- <el-button @click="print" type="danger">取消支付</el-button> -->
                        <el-button @click="handleClose()" type="primary">关闭</el-button>
                    </div>
                </div>
            </div>
        </div>
    </el-dialog>
</template>
<script>
import { 
  querySeatListNew,
 } from '@/api/windowTicketSales/ticketingSales'
 import { rebookApi,getTimeSeatTypeAllApi,resubmitInfoApi } from '@/api/windowTicketSales/rebook'
 import { countBySeatTyp } from '@/api/ticketMr/InventoryTemplate'
 import { pageList as getSeatType } from '@/api/seatTypeMr/seatTypeMr'
 import { getSelectById } from '@/api/order/orderMr'
 import seatBox from '@/components/seatBox/index.vue';
 import payJs from "../mixins/pay"
 const mathM = require('mathjs')
export default {
    name: "RebookBox",
    components: { seatBox },
    mixins: [payJs],
    data() {
        return {
            // 改签对话框
            rebookDialog: false,
            loading: false,
            // 改签表单
            rebookForm: {
                orderId: undefined,
                performDate: undefined,
                performTimeId: undefined,
                performInterval: undefined,
                performId: undefined,
                auditoriumId: undefined
            },
            rules: {
                seatTypeId: [{ required: true, message: '请选择票档', trigger: ['blur','change'] }]
            },
            // 场次列表
            intervalList: [],
            intervalListLoading: false,
            // 支付相关
            payDialog: false,
            payStatus: null,
            code: '',
            websocketData: null,
            codeTime: null,
            // 成功对话框
            successDialog: false,
            newOrderId: '',
            printList: [],

            configStockNumObj: {},
            countBySeatTypList:[],
            seatTypeListAll: [],

            seatLoading: false,
            seatLoadText: '获取座位中...',
            setList: [],
        }
    },
    created(){
        this.getSeatTypeAllList()
    },
    methods: {
        async initData(row) {
            this.rebookDialog = true
            this.payStatus = null
            this.rebookForm = {
                resubmitType: 2,  // 改签类型: 1-改签 2-升舱 不传默认为改签
                goodsDiffAmount: undefined,
                performName: row.performName,
                goodsName: row.goodsName,
                seatTypeName: row.seatTypeName,
                seatTypeId: null,
                goodsId: row.goodsId,
                orderId: row.orderId,
                performDate: row.performDate,
                performTimeId: null,
                performId: row.performId,
                auditoriumId: row.auditoriumId,
                paymentType: "1", // 支付方式'
                touristNum: row.touristNum,
                seatList: [],
                performTimeEnd: row.performTimeEnd,
                performTimeStart: row.performTimeStart
            }
            await this.getSelectByIdApi()
            await this.handleDateChange()
            this.$nextTick(()=>{
                this.$refs.rebookForm.clearValidate()
            })
        },
        /** 获取详情 */
        async getSelectByIdApi() {
            try {
                let res = await getSelectById(this.rebookForm.orderId)
                this.rebookForm = {
                    ...this.rebookForm,
                    performTimeId: res.data.performTimeId,
                }
            } catch (error) {
                
            }

        },
        /** 获取票档  */
        async handleDateChange() {
            try {
                this.intervalListLoading = true
                this.intervalList = []
                let res = await getTimeSeatTypeAllApi({
                    orderId: this.rebookForm.orderId,
                })
                this.intervalList = res.data.list || []
                if(this.intervalList.length == 0){
                    this.$message.error('没有可升舱的票档!!!');
                }
                this.intervalListLoading = false
            } catch (error) {
                this.intervalListLoading = true
            }
        },
        /**  提交表单 */
        submitRebook() {
            this.$refs.rebookForm.validate((valid) => {
                if (valid) {
                    if(!this.rebookForm.seatList||this.rebookForm.seatList.length==0) {
                        this.$message.error('请选择座位!!!');
                        return
                    }
                    if( this.rebookForm.seatList.length < this.rebookForm.touristNum ) {
                        this.$message.error(`请选择${ this.rebookForm.touristNum }座位!!!`);
                        return
                    }
                    this.orderInfoSubmitFun()
                } else {
                    return false;
                }
            });
        },
        /** 退出窗口 */
        handleClose(done) {
            // if(this.payStatus==8) {
            //     this.$message.error('请daying');
            //     return
            // }
            this.$confirm('确认关闭？')
                .then(_ => {
                    if(this.orderId){
                        document.removeEventListener('keydown',this.keydownAdd);
                        this.orderInfoCancelFun(true)
                    }else {
                        this.$refs.seatBox.querySeatListFun(true,[],[],[])
                        this.rebookDialog = false
                    }
                })
                .catch(_ => {});
        },
        /** 
         * 
         *  获取升舱/改签信息
         * 
         */
        async resubmitInfoFun() {
            try {
                let res = await resubmitInfoApi({
                    orderId: this.rebookForm.orderId,
                    timeId: this.rebookForm.performTimeId,
                    seatTypeId: this.rebookForm.seatTypeId,
                    //goodsDiffAmount: this.rebookForm.goodsDiffAmount,
                })
                this.rebookForm = {
                    ...this.rebookForm,
                    realPrice: res.data.reSubmitInfo.realPrice,
                    diffPrice: res.data.reSubmitInfo.diffPrice
                }

                if(this.rebookForm.diffPrice <= 0) {
                    this.rebookForm.paymentType == "2"
                }
            } catch (error) {
                
            }
         },

        /**  获取座位  */
        async querySeatListFun(type){
            try {
                await this.countBySeatTypFun(this.rebookForm.auditoriumId)
                await this.resubmitInfoFun()
                let res = await querySeatListNew({
                    auditoriumId: this.rebookForm.auditoriumId,
                    timeId: this.rebookForm.performTimeId,
                    goodsId: this.rebookForm.goodsId,
                    channelType: this.rebookForm.timeId ? 'group' : 'window'
                })
                if(res.code == 200){
                    let list1 = []
                    res.data.forEach((item,index)=>{
                        list1.push({
                            ...item,
                            isSame: this.rebookForm.seatTypeId != item.seatTypeId
                        })
                    })
                    this.setList = list1;
                    let list = []
                    let list3 = []
                    this.countBySeatTypList.forEach((item,index)=>{
                        list3.push(item.seatTypeId)
                    })
                    let list4 = []
                    this.seatTypeListAll.forEach((item,index)=>{
                        if(list3.includes(item.id)) {
                            list4.push({...item})
                        }
                    })
                    this.$nextTick(() =>{
                        this.$refs.seatBox.querySeatListFun(true,this.setList,list,list4)
                    })
                }
                
                this.loading = false
            } catch (error) {
                this.loading = false
                console.error("error===",error)
            }
        },
        /** 获取座位类型  */
        async countBySeatTypFun(value) {
            try {
                if(!value) return
                let res = await countBySeatTyp({auditoriumId: value})
                this.countBySeatTypList = res.data ? res.data : []
                let obj = {}
                this.countBySeatTypList.forEach((item,index)=>{
                    obj['seatNum_'+item.seatTypeId] = {
                        stockTotal: item.stock,
                        stockSelect: item.stock,
                        stockYes: item.stock,
                        stockNo: 0,
                        isNoSelect: true,
                    }
                    if(item.seatTypeId == this.rebookForm.seatTypeId){
                        obj['seatNum_'+item.seatTypeId].stockYes = item.stock-this.rebookForm.touristNum
                        obj['seatNum_'+item.seatTypeId].isNoSelect = false
                    }
                })
                this.configStockNumObj = obj
            } catch (error) {
                console.error("error1====",error)
            }
        },
        /** 获取座位类型 说明 */
        async getSeatTypeAllList() {
            try {
                let res = await getSeatType({
                    pageNum: 1,
                    pageSize: 999,
                })
                if(res.code == 200) {
                    this.seatTypeListAll = res.data.rows || [];
                }
            } catch (error) {
                        
            }   
        },
         /** 选择座位  */
        selectSeat(list) {
            let list1 = []
            list.forEach((item)=>{
                list1.push({
                    seatId: item.id
                })
            })
            this.rebookForm.seatList = list1
            console.log("已选择的====",list)
        },
        setRealPrice_1(value) {
            if(this.rebookForm.realPrice && !isNaN(this.rebookForm.realPrice) && value && !isNaN(value)) {
                this.$set(this.rebookForm,'small',mathM.format(Number(value) - Number(this.rebookForm.realPrice),10) )
            }
        },
    }
}
</script>
<style lang="scss" scoped>
.rebook1_dialog ::v-deep .el-dialog__body {
    padding: 0 !important;
}
.rebook1_box {
    width: 100%;
    height: 100%;
    padding-bottom: 10px;
    .rebook1_from-box {
        display: flex;
        width: 100%;
        height: 80vh;
        box-sizing: border-box;
        padding: 0 20px 20px;
    }
    .rebook1_from {
        width: 100%;
        height: 100%;
        overflow: hidden;
        overflow-y: auto;
        padding: 0 20px 0 0;
        width: 400px;
        box-sizing: border-box;
        .tip-box {
            >p {
                color: red;
            }
        }
    }
    .rebook1_seat {
        width: calc( 100% - 400px );
        height: 100%;
    }
}

.increase-viewers-pay-status {
    width: 100%;
    height: 100%;
    position: absolute;
    z-index: 999;
    background-color: rgba(0,0,0,0.3);
    top: 0;
    left: 0;
    .increase-viewers-pay-status-info {
        width: 100%;
        height: 100%;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        color: #fff;
    } 
} 
</style>