<template>
    <el-dialog
    title="添加观影人"
    :visible.sync="dialogVisible"
    width="90%"
    :before-close="handleClose">
    <div
    v-loading="loading" 
    :element-loading-text="loadingText"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
    class="increase-viewers-box">
        <div class="increase-viewers-info">
            <el-table
            :data="viewerList"
            border
            style="width: 100%">
                <el-table-column
                label="序号"
                type="index"
                width="50">
                </el-table-column>
                <el-table-column
                    label="姓名"
                    width="180">
                    <template slot-scope="scope">
                        <div>
                            <span v-if="actionIndex != scope.row.id">{{ scope.row.name }}</span>
                            <el-input size="mini" v-else v-model="tableForm.name" placeholder="请输入姓名"></el-input>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column
                    label="身份证号"
                    width="250">
                    <template slot-scope="scope">
                        <div>
                            <span v-if="actionIndex != scope.row.id">{{ scope.row.idcard }}</span>
                            <el-input
                                size="mini"
                                v-else
                                v-model="tableForm.idcard"
                                placeholder="请输入身份证号"
                                clearable
                                style="width: 230px;"
                                @keyup.enter.native="handleQuery"
                            >
                                <el-button slot="append" :loading="idcardLoading" size="mini" type="primary" @click="readCert">{{ idcardLoading ? '识别中':'识别' }}</el-button>
                            </el-input>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column
                    label="座位类型">
                    <template slot-scope="scope">
                        <span>{{ scope.row.seatTypeName }}</span>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="date"
                    label="座位号">
                    <template slot-scope="scope">
                        <span>{{ scope.row.seatName }}</span>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="date"
                    label="价格(元)">
                    <template slot-scope="scope">
                        <span>{{ scope.row.salePrice }}</span>
                    </template>
                </el-table-column>
                <el-table-column
                    label="人员类别"
                    width="140">
                    <template slot-scope="scope">
                        <div>
                             <dict-tag v-if="actionIndex != scope.row.id" :options="dict.type.personnel_type" :value="scope.row.identity"/>
                            <el-select
                                size="mini"
                                v-else
                                v-model="tableForm.identity"
                                placeholder="请选择人员类别"
                                clearable
                                style="width: 100%"
                            >
                                <el-option
                                v-for="dict in dict.type.personnel_type"
                                :key="dict.value"
                                :label="dict.label"
                                :value="dict.value"
                                />
                            </el-select>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column
                    label="应收金额(元)">
                    <template slot-scope="scope">
                        <span v-if="(scope.$index!=0 && oneMany ==1 && personnelNum != 0)">{{ scope.row.realPrice }}</span>
                        <div v-else>
                            <span v-if="actionIndex != scope.row.id">{{ scope.row.realPrice }}</span>
                            <el-input-number size="mini" style="width: 120px;" v-else v-model="tableForm.realPrice" controls-position="right" label="请输入应收金额(元)"></el-input-number>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column
                    label="备注"
                    width="180">
                    <template slot-scope="scope">
                        <div>
                            <span v-if="actionIndex != scope.row.id">{{ scope.row.remark }}</span>
                            <el-input size="mini" v-else v-model="tableForm.remark" placeholder="请输入备注"></el-input>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column
                    label="操作"
                    width="80"
                    >
                    <template slot-scope="scope" v-if="(scope.$index != 0 && oneMany!=2) || scope.$index == 0">
                        <el-button
                        size="mini"
                        type="success"
                        :loading="factorAuthLoading"
                        v-if="actionIndex == scope.row.id"
                        @click="handleSeva(scope.$index, scope.row)">{{ factorAuthLoading ? '保存中....' : '保存' }}</el-button>
                        <el-button
                        :disabled="!!actionIndex"
                        size="mini"
                        type="primary"
                        v-if="actionIndex != scope.row.id"
                        @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                        <!-- <el-button
                        size="mini"
                        type="danger"
                        @click="handleDelete(scope.$index, scope.row)">删除</el-button> -->
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div style="padding: 10px 0 20px;">合计：累计观影人员{{ viewerList.length }}人,应付总额￥{{ moneyAll }}(元)</div>
        <div>
            <el-form 
            :model="ruleForm" 
            :rules="rules" 
            ref="ruleForm11" 
            label-width="120px" 
            class="demo-ruleForm"
            size="mini"
            >
                
                <div style="display: flex;">
                    <el-form-item label="用户来源 :" prop="source">
                        <el-radio-group v-model="ruleForm.source">
                            <el-radio label="7">窗口</el-radio>
                            <el-radio label="10">美团</el-radio>
                            <el-radio label="11">携程</el-radio>
                            <el-radio label="13">抖音</el-radio>
                            <el-radio label="14">猫眼</el-radio>
                            <el-radio label="18">大麦</el-radio>
                            <el-radio label="19">飞猪</el-radio>
                            <!-- <el-radio label="15">去哪儿</el-radio> -->
                            <el-radio label="16">其他</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label-width="60px" v-if="ruleForm.source && ruleForm.source == 16" label="备注 :" prop="sourceRemark">
                        <el-input style="width: 200px;" v-model="ruleForm.sourceRemark"></el-input>
                    </el-form-item>
                </div>
                <el-form-item v-if="ruleForm.source && ruleForm.source != 7" label="核销码/订单码" prop="orderIdOrQrCode">
                    <el-input style="width: 400px;" type="textarea" :rows="2" v-model="ruleForm.orderIdOrQrCode"></el-input>
                </el-form-item>
                <el-form-item label="支付方式 :" prop="paymentType">
                    <el-radio-group v-model="ruleForm.paymentType">
                        <el-radio label="1">扫码</el-radio>
                        <el-radio label="2">现金</el-radio>
                        <el-radio v-if="['10','11','13','14','18','19'].includes(ruleForm.source)" label="3">对公支付</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="应收金额 :">
                    ￥{{ moneyAll }}元
                </el-form-item>
                <el-form-item v-if="ruleForm.paymentType == 2 || ruleForm.paymentType == 3" label="实收金额 :" prop="realPrice">
                    <el-input @input="setRealPrice" style="width: 200px;" v-model="ruleForm.realPrice"></el-input>
                </el-form-item>
                <el-form-item label="找零金额 :" v-if="ruleForm.paymentType == 2">
                    ￥{{ ruleForm.small }}元
                </el-form-item>
                <el-form-item label="订单备注 :" prop="remark">
                    <el-input style="width: 400px;" type="textarea" :rows="2" maxlength="200" v-model="ruleForm.remark" show-word-limit></el-input>
                </el-form-item>
            </el-form>
        </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==6 ? '连接扫码器失败!!!' :
                    payStatus==7 ? '用户支付失败或未支付,请重新连接支付!!!' :
                    payStatus==8 ? '用户支付成功,请点击打印票!!!' :
                    payStatus==9 ? '支付超时!!!' :
                    payStatus==3 ? '现金支付记录入库失败,请重新提交' : '未知状态' }}
                </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>
                <!-- 扫码支付 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>
                <!-- 打印 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,index) 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>
            </div>
        </div>
    </div>
    
    <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose()">取 消</el-button>
        <el-button v-if="!orderId&&!payStatus" :loading="loading" type="primary" @click="submitForm('ruleForm11')">确定支付</el-button>
    </span>
    </el-dialog>
</template>
<script>
import { 
  orderInfoSubmit,
  gotoMicroPay,
  gotoCashPay,
  gotoCorporatePay,
  payQuery,
  selectRegion,
  orderInfoCancel,
  factorAuth
 } from '@/api/windowTicketSales/ticketingSales'
 import { pageList as getPrintListApi } from "@/api/device/pda";
 import { printApi } from '@/api/windowTicketSales/ticketingCollection'
 const mathM = require('mathjs')
 const https = require('https');
 const axios = require('axios');
  export default {
    dicts: ['personnel_type'],
    data() {
      return {
        loading: false,
        loadingText: '',
        dialogVisible: false,
        actionIndex: false,
        tableForm: {
            name: '', // 姓名
            mobile: '', // 电话
            idcard: '', // 身份证
            identity: '', // 观影人身份
            remark: '', // 备注信息
            salePrice: '', // 原价
            realPrice: '', // 实收金额
            seatId: '', // 座位ID
            seatName: '', // 座位名称
            seatType: '', // 座位类型
        },
        ruleForm: {
            performId: "", // 剧目ID
            retailId: "", // 分销ID
            goodsList: [], // 商品列表
            auditoriumId: "", // 演出厅ID
            performTimeId: "1", // 场次时段ID
            seatTypeId: "", // 座位类型ID
            source: '', // 订单来源
            purchaser: {},// 购票人信息
            viewerList: [], // 观影人列表
            orderIdOrQrCode: '',
            paymentType: '', // 支付方式
            small: '',// 找零
            realPrice: '', // 实收金额
        },
        viewerList: [], // 观影人列表
        rules: {
            source: [
                { required: true, message: '请选择用户来源', trigger: ['blur','change']},
            ],
            orderIdOrQrCode: [
                { required: true, message: '请输入核销码/订单码', trigger: ['blur','change']},
            ],
            paymentType: [
                { required: true, message: '请选择支付方式', trigger: ['blur','change']},
            ],
            realPrice: [
                { required: true, message: '请输入实收金额', trigger: ['blur','change']},
            ],
            sourceRemark: [
                { required: true, message: '请输入备注', trigger: ['blur','change']},
            ],
        },
        moneyAll: '',
        payment: '',
        payStatus: null, // 支付状态
        orderId: null,
        websocket_connected: false, // 是否已连接
        websocketCtrl: null,
        websocketData: null,

        idcardLoading: false,
        payTime: null, // 支付等待时间
        payTimeNum: 0,
        printListId: null,
        printList: [],

        // 身份证校验 loading
        factorAuthLoading: false,

        ifRealUser: 0,  // 散客是否实名:0-否 1-是
        ifRealTeam: 0,   // 团购是否实名:0否 1-是
        oneMany: 1,   // 证件要求: 1一证一票，2一证多票
        personnelNum: 0,   // 人员要求:0-表示不限制 其他数字表示限制人数
      };
      
    },
    methods: {
        async initData(list,params){
            try {
                this.ifRealUser = params.ifRealUser  // 散客是否实名:0-否 1-是
                this.ifRealTeam = params.ifRealTeam   // 团购是否实名:0否 1-是
                this.oneMany = params.oneMany   // 证件要求: 1一证一票，2一证多票
                this.personnelNum = params.personnelNum   // 人员要求:0-表示不限制 其他数字表示限制人数
                this.websocketClear()
                this.idcardLoading = false
                this.ruleForm = {
                    performId: "", // 剧目ID
                    retailId: "", // 分销ID
                    goodsList: [], // 商品列表
                    auditoriumId: "", // 演出厅ID
                    performTimeId: "", // 场次时段ID
                    seatTypeId: "", // 座位类型ID
                    source: '', // 订单来源
                    purchaser: {},// 购票人信息
                    viewerList: [], // 观影人列表
                    orderIdOrQrCode: '',
                    paymentType: '', // 支付方式
                    small: '',// 实收金额
                    realPrice: '', // 实收金额
                    remark: '', // 订单备注
                    sourceRemark: '', //  来源备注
                }
                this.payStatus = null
                this.orderId = null
                this.websocket_connected = false
                this.dialogVisible = true
                this.loading = true
                this.actionIndex = null
                this.viewerList = []
                let perform = await this.selectRegionFun(params,list[0].seatTypeId)
                console.log("perform===",perform)
                // let perform = {
                //     money: 1,
                //     name: '普通票'
                // }
                let listCopy = []
                let listCopy1 = []
                list.forEach((item,index)=>{
                    listCopy.push({
                        id: index+1,
                        name: '', // 姓名
                        mobile: '', // 电话
                        idcard: '', // 身份证
                        identity: '', // 观影人身份
                        remark: '', // 备注信息
                        salePrice: this.oneMany == 2 || (this.oneMany == 1 && this.personnelNum != 0)  ? index == 0 ? perform.money  : 0 : perform.money, // 原价
                        realPrice: this.oneMany == 2 || (this.oneMany == 1 && this.personnelNum != 0)  ? index == 0 ? perform.money  : 0 : perform.money, // 实收金额
                        seatId: item.id, // 座位ID
                        seatName: item.name?item.name:'暂无命名', // 座位名称
                        seatType: perform.seatTypeId, // 座位类型
                        seatTypeId: perform.seatTypeId,
                        seatTypeName: perform.seatTypeName,
                    })
                })
                //this.goodsList = 
                this.viewerList = JSON.parse(JSON.stringify(listCopy))
                this.setMoneyAll()
                
                console.log(this.viewerList)
                this.loading = false
                this.$nextTick(()=>{
                    this.$refs.ruleForm11.clearValidate()
                })
            } catch (error) {
                console.error("error====",error)
            }
            
        },
        /**  获取票务信息  */
        async selectRegionFun(params,seatTypeId){
            try {
                this.loadingText = "获取票务信息中..."
                let res = await selectRegion({
                    "auditoriumId": params.auditoriumId, // 演艺厅ID
                    "goodsId": params.goodsId, // 商品ID
                    "performId": params.performId, // 上一界面节目ID
                    "performTimeId": params.timeId, // 时段ID
                    "retailId": "" // 分销ID
                })
                if(res.code == 200) {
                    if(res.data.regionPriceList &&res.data.regionPriceList.length>0){
                        //let obj = res.data.regionPriceList[0]
                        let obj = {}
                        res.data.regionPriceList.forEach((item,index)=>{
                            if(seatTypeId == item.seatTypeId) {
                                obj = item
                            }
                        }) 
                        if(JSON.stringify(obj) != '{}'){
                            this.ruleForm.performId = obj.performId
                            this.ruleForm.goodsList = [
                                {
                                    goodsId: obj.goodsId,
                                    salePeice: obj.salePrice,
                                    saleNum: 1,
                                }
                            ]
                            this.ruleForm.auditoriumId = obj.auditoriumId
                            this.ruleForm.performId = obj.performId
                            this.ruleForm.performTimeId = res.data.performTimeId
                            this.ruleForm.seatTypeId = obj.seatTypeId
                            return {
                                money: obj.salePrice,
                                //name: obj.goodsName,
                                seatTypeId: obj.seatTypeId,
                                seatTypeName: obj.seatTypeName,
                            }
                        }else {
                            this.$message.error('存在座位未设置价格,请选择其他票!!!');
                            this.loading = false
                            this.dialogVisible = false
                        }
                        
                    }else {
                        this.$message.error('存在座位未设置价格,请选择其他票!!!');
                        this.loading = false
                        this.dialogVisible = false
                    }
                    console.log("res====",res)
                }else {
                    this.$message.error(res.msg);
                    this.loading = false
                    this.dialogVisible = false
                }
            } catch (error) {
                console.error("error=====",error)
                this.$message.error('价格查询出错');
                this.loading = false
                this.dialogVisible = false
            }
        },
        /**  取消订单   */
        async orderInfoCancelFun(type){
            try {
                this.loading = true
                this.loadingText = "取消订单中..."
                orderInfoCancel({
                    orderId: this.orderId
                }).then((res)=>{
                    if(res.code==200) {
                        if(type){ // 关闭弹窗
                            this.$emit('clearDialogVisible')
                            this.dialogVisible = false
                        }else {
                            this.payStatus = 9
                            this.loading = false
                        }
                        
                    }
                }).catch(()=>{
                    this.$message.error('订单关闭失败!!!');
                })
            } catch (error) {
                
            }
        },
        /** 退出窗口 */
        handleClose(done) {
            // if(this.payStatus==8) {
            //     this.$message.error('请daying');
            //     return
            // }
            this.$confirm('确认关闭？')
                .then(_ => {
                    if(this.orderId){
                        this.orderInfoCancelFun(true)
                    }else {
                        this.dialogVisible = false
                    }
                })
                .catch(_ => {});
        },
        /**  保存个人信息 */
        handleSeva(index, row) {    
            if(!this.tableForm.name){
                this.$message.error('请输入姓名!!!');
                return
            }
            if(!this.tableForm.idcard){
                this.$message.error('请输入身份证号!!!');
                return 
            }
            if(this.tableForm.identity && this.tableForm.identity != 0){
                if(!this.tableForm.remark){
                    this.$message.error('请输入备注!!!');
                    return 
                }
            }
        
            //this.factorAuthFun(index,this.tableForm)
            if(this.oneMany == 2 && index==0) {
                this.$set(this.viewerList,index,JSON.parse(JSON.stringify(this.tableForm)))
                let list = JSON.parse(JSON.stringify(this.viewerList))
                list.forEach((item,index)=>{
                    item.name = this.tableForm.name
                    item.idcard = this.tableForm.idcard
                })
                this.viewerList = list
            }else {
                this.$set(this.viewerList,index,JSON.parse(JSON.stringify(this.tableForm)))
            }
            this.actionIndex = null
            this.setMoneyAll()
        },
        /**  校验 身份证 */
        async factorAuthFun(index, obj){
            try {
                this.factorAuthLoading = true
                let res = await factorAuth({
                    "name": obj.name,
                    "idcard": obj.idcard
                })
                if(res.code == 200){
                    this.factorAuthLoading = false
                    if(res.data.status != 1) {
                        this.$message.error(res.data.errReason);
                    }else {
                        this.$set(this.viewerList,index,JSON.parse(JSON.stringify(this.tableForm)))
                        this.actionIndex = null
                        this.setMoneyAll()
                    }
                }else {
                    this.$message.error(res.msg);
                    this.factorAuthLoading = false
                }
            } catch (error) {
                this.$message.error(error);
                this.factorAuthLoading = false
            }
        },
        handleEdit(index, row) {
            this.actionIndex = row.id
            this.tableForm = JSON.parse(JSON.stringify(row))
            
            console.log(index, row);
        },
        handleDelete(index, row) {
            console.log(index, row);
        },
        setMoneyAll(){
            let moneyAll = 0
            this.viewerList.forEach((item,index) => {
                console.log("item.realPrice====",item.realPrice)
                if(item.realPrice && !isNaN(Number(item.realPrice))) {
                    moneyAll = mathM.format(Number(moneyAll) + Number(item.realPrice),10) 
                }
            })
            console.log("dsfsfdsf",moneyAll)
            this.moneyAll = moneyAll? moneyAll: ''
        },
        setRealPrice(value) {
            if(value && !isNaN(value)) {
                this.$set(this.ruleForm,'small',mathM.format(Number(value) - Number(this.moneyAll),10) )
            }
        },
        /**  检查是否存在空值 */
        checkViewerList() {
            let flog = false
            for(let i = 0; i < this.viewerList.length; i++){
                let obj = this.viewerList[i]
                if(!obj.name){
                    this.$message.error('请填写观影人姓名!!!');
                    flog = true
                    break;
                }
                if(!obj.idcard){
                    this.$message.error('请填写观影人身份证号!!!');
                    flog = true
                    break; 
                }
                if(obj.identity && obj.identity != 0){
                    if(!obj.remark){
                        this.$message.error('请填写观影人备注!!!');
                        flog = true
                        break; 
                    }
                }
            }
            if(this.actionIndex){
                this.$message.error('请先保存观影影人信息!!!');
                flog = true
            }
            return flog
        },
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
            if (valid) {
                if(!this.checkViewerList()){
                    this.orderInfoSubmitFun()
                }
            } else {
                console.log('error submit!!');
                return false;
            }
            });
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
        /**  生成订单  */
        async orderInfoSubmitFun(){
            this.loading = true
            try {
                this.orderId = null
                this.loadingText = "生成订单中..."
                let res = await orderInfoSubmit({
                    ...this.ruleForm,
                    viewerList: this.viewerList
                })
                if(res.code == 200){
                    this.orderId = res.data.orderId
                    if(this.ruleForm.paymentType == 2) {
                        this.gotoCashPayFun(this.orderId)
                    }else if(this.ruleForm.paymentType == 3) { // 对公支付
                        this.gotoCorporatePayFun(this.orderId)
                    }else {
                        // 扫码支付
                        this.loading = false
                        this.payStatus = 2
                    }
                }else{
                    this.$message.error('生成订单失败!!!');
                    this.loading = false
                    this.payStatus = 1
                }
            } catch (error) {
                this.$message.error('生成订单失败!!!');
                this.loading = false
                this.payStatus = 1
            }
        },
        
         /** 调取 订单支付码支付  */
         async gotoMicroPayFun(orderId,code){
            this.loading = true
            try {
                this.loadingText = "订单支付中..."
                this.payStatus = ''
                let res = await gotoMicroPay({
                    "orderId": orderId, // 订单编号-提交订单返回
                    "authCode": code // 微信扫码支付-支付码
                })
                if(res.code == 200){
                    this.payTimeNum = 0
                    this.websocketClear()
                    if(this.payTime){
                        clearInterval(this.payTime)
                    }
                    this.payTime = setInterval(()=>{
                        this.payQueryFun(this.orderId)
                    },1500)
                }else{
                    this.$message.error('支付失败!!!');
                    this.payStatus = ''
                    this.loading = false
                    this.payStatus = 6
                }
            } catch (error) {
                this.$message.error('支付失败!!!');
                this.loading = false
                this.payStatus = 6
            }
        },
        /**  对公支付  */
        async gotoCorporatePayFun(orderId) {
            this.loading = true
            try {
                this.loadingText = "订单入库中..."
                let res = await gotoCorporatePay({
                    "orderId": orderId, // 订单编号-提交订单返回
                    "payAmount": this.ruleForm.realPrice
                })
                if(res.code == 200){
                    if(this.payTime){
                        clearInterval(this.payTime)
                    }
                    this.payTimeNum = 0
                    this.payTime = setInterval(()=>{
                        this.payQueryFun(this.orderId)
                    },1000)
                }else{
                    this.$message.error('订单入库中失败!!!');
                    this.loading = false
                    this.payStatus = 3
                }
            } catch (error) {
                this.$message.error('订单入库中失败!!!');
                this.loading = false
                this.payStatus = 3
            }
        },
         /**  订单现金支付  */
         async gotoCashPayFun(orderId){
            this.loading = true
            try {
                this.loadingText = "订单入库中..."
                let res = await gotoCashPay({
                    "orderId": orderId, // 订单编号-提交订单返回
                    "payAmount": this.ruleForm.realPrice
                })
                if(res.code == 200){
                    if(this.payTime){
                        clearInterval(this.payTime)
                    }
                    this.payTimeNum = 0
                    this.payTime = setInterval(()=>{
                        this.payQueryFun(this.orderId)
                    },1000)
                }else{
                    this.$message.error('订单入库中失败!!!');
                    this.loading = false
                    this.payStatus = 3
                }
            } catch (error) {
                this.$message.error('订单入库中失败!!!');
                this.loading = false
                this.payStatus = 3
            }
        },
        // 跳转取票界面
        goTicketingCollections(){
            this.$router.push({
                path:"/windowTicketSales/ticketingCollections",
                query:{
                    orderId: this.orderId
                }
            })
        },

         /**  查看支付 状态  */
         async payQueryFun(orderId){
            this.loading = true
            
            try {
                this.payTimeNum = this.payTimeNum + 1
                if(this.payTimeNum==15){
                    if(this.payTime){
                        clearInterval(this.payTime)
                    }
                    this.orderInfoCancelFun()
                    return
                }
                if(this.ruleForm.paymentType == 2){
                    this.loadingText = "订单入库中..."
                }else {
                    this.loadingText = "订单支付中..."
                }
                this.payStatus = ''
                let res = await payQuery({
                    orderId: orderId
                })
                if(res.code == 200){
                    if(res.data) {
                        if(res.data.payStatus == 0) {
                            if(this.payTime){
                                clearInterval(this.payTime)
                            }
                            if(this.ruleForm.paymentType == 2){
                                this.$message.error('"订单入库中失败"');
                                this.loading = false
                                this.payStatus = 3
                            }else {
                                this.$message.error('用户未支付!!!');
                                this.loading = false
                                this.payStatus = 7
                            }
                            
                        }else if(res.data.payStatus == 1) {
                            if(this.payTime){
                                clearInterval(this.payTime)
                            }
                            if(this.ruleForm.paymentType == 2){
                                this.$message({
                                    message: '订单入库成功',
                                    type: 'success'
                                });
                                this.loading = false
                                // this.payStatus = 8
                                // this.getPrintListApi()
                                this.goTicketingCollections()
                                
                            }else {
                                this.$message({
                                    message: '用户已支付成功,请打印门票',
                                    type: 'success'
                                });
                                // 开始 打印
                                this.loading = false
                                // this.payStatus = 8
                                // this.getPrintListApi()
                                this.goTicketingCollections()
                            }
                            
                            
                        }else if(res.data.payStatus == 2) {

                        }else if(res.data.payStatus == 3) {
                            if(this.payTime){
                                clearInterval(this.payTime)
                            }
                            if(this.ruleForm.paymentType == 2){
                                this.$message.error('"订单入库中失败"');
                                this.loading = false
                                this.payStatus = 3
                            }else {
                                this.$message.error('用户支付失败!!!');
                                this.loading = false
                                this.payStatus = 7
                            }
                        }else if(res.data.payStatus == 4) {
                            if(this.payTime){
                                clearInterval(this.payTime)
                            }
                            
                            if(this.ruleForm.paymentType == 2){
                                this.$message.error('"订单入库中失败"');
                                this.loading = false
                                this.payStatus = 3
                            }else {
                                this.$message.error('支付退款!!!');
                                this.loading = false
                                this.payStatus = 7
                            }
                            
                        }
                    }
                    
                }else{
                    this.$message.error('支付失败!!!');
                    this.loading = false
                    this.payStatus = 7
                }
                
            } catch (error) {
                this.$message.error('支付失败!!!');
                this.loading = false
                this.payStatus = 7
            }
        },

        /**  连接VBarServer  */
        vbar_open() {
            this.loading = true
            this.loadingText = "连接扫码盒子中!!!"
            this.payStatus =  null
            this.websocketClear()
            console.log('sdfdsfsd')
            if (!this.websocket_connected) {
                var host = "ws://localhost:2693";
                this.websocketCtrl = new WebSocket(host,'ctrl');
                this.websocketData = new WebSocket(host,'data');
                this.websocketData.onopen = (evt) => {
                    console.log('sdasdasd====',evt)
                    this.loading = false
                    this.payStatus = 5
                    this.websocket_connected = true;
                    this.websocket_open_state(evt);
                }
                this.websocketData.onerror = (evt) => {
                    console.log('sdasdasd11111====',evt)
                    this.payStatus = 6
                    //this.vbar_open()
                }

                this.websocketData.onmessage = (evt) => {
                    console.log("接受消息====",evt)
                    this.websocket_decode(evt.data);
                }
            }

            //setTimeout(this.vbar_open(), 3000);
        },
        /**  连接结果 */
        websocket_open_state(message){
            //document.getElementById('wsocket').value = "已连接";
        },
        //接收扫码结果处理
        websocket_decode(code){
            console.log()
            if(this.orderId && this.payStatus==5 &&code) {
                this.gotoMicroPayFun(this.orderId,code)
            }
        },
        /** 关闭通讯 */
        websocketClear(){
            if(this.websocketCtrl){
                this.websocketCtrl.close()
            }
            if(this.websocketData){
                this.websocketData.close()
            }
            this.websocket_connected = false
        },
        /**  读取身份证 */
        readCert(){
            this.idcardLoading = true
            var result = "";
            try {
                let xmlHttp = new XMLHttpRequest();
                let Protocol = window.location.protocol.split(':')[0];
                //获取当前协议，并且分割字符串，得到http或者https
                if (Protocol === 'https'){
                    //创建请求 第一个参数是代表以post方式发送；第二个是请求端口和地址；第三个表示是否异步
                    xmlHttp.open("POST", "http://127.0.0.1:18889/api/readCert?ReadSN=" + 0, false);	  //readCert读卡，生成正反面仿复印件	
                }else {
                    //创建请求 第一个参数是代表以post方式发送；第二个是请求端口和地址；第三个表示是否异步
                    xmlHttp.open("POST", "http://127.0.0.1:18889/api/readCert?ReadSN=" + 0, false);	  //readCert读卡，生成正反面仿复印件	
                }
                //发送请求
                xmlHttp.send();
                if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
                    result = xmlHttp.responseText;
                    xmlHttp.readyState = 1;
                }
            } catch (e) {
                console.error("e====",e)
            }
            let obj = JSON.parse(result)
            if(obj.resultContent && obj.resultContent.certNumber){
                this.$set(this.tableForm,"idcard",obj.resultContent.certNumber)
                this.$set(this.tableForm,"name",obj.resultContent.partyName)
            }else {
                this.$message.error('读取失败!!!');
            }
            
            this.idcardLoading = false
            //return result;
             console.log(result,obj)
        },
        /** 查询打印机列表 */
        getPrintListApi() {
          getPrintListApi({deviceType:5,pageNum: 1,
          pageSize: 999,})
          .then(response => {
              this.printList = response.data.rows;
          }).catch((error)=>{
            console.log("error===",error)
          }
          );
        },
        // 打印 
        async print(list = []){
            if(!this.printListId) {
                this.$message.error('请选择打印机!!');
                return
            }
            this.loading = true
              this.loadingText = '打印中...'
              this.payStatus = ''
              try {
                let res = await printApi({
                  orderId: this.orderId,
                  source: 2,
                  deviceId: this.printListId
                })
                if(res.code == 200) {
                  let url = res.data.linkIp
                  let printInfo = res.data.printInfo
                  this.connectPrint(url,printInfo)
                }else {
                  throw new Error(res)
                }
              } catch (error) {
                this.loading = false
                 this.payStatus = 8
                console.error("error=====",error)
              }
          
        },
        /**  连接打印机  */
        connectPrint(url,data){
          // 创建忽略 SSL 的 axios 实例
          const ignoreSSL = axios.create({
            httpsAgent: new https.Agent({  
              rejectUnauthorized: false
            }),
            withCredentials: true, // 跨域请求时发送Cookie
            timeout: 60000, // 请求超时
            headers: {
              "Content-Type": "application/json; charset=UTF-8;"
            }
          });
          ignoreSSL.post(url, 
            { ...data }
            ).then(()=>{
            this.dialogVisible = false
            this.loading = false
          }).catch(()=>{
            this.loading = false
            this.payStatus = 8
            // this.dialogVisible = false
            // this.loading = false
          })
          // 在 axios 请求时，选择性忽略 SSL
          // const agent = new https.Agent({  
          //   rejectUnauthorized: false
          // });
          // axios.post(
          //   url, 
          //   { httpsAgent: agent,...data }
          //   ).then(()=>{
          //   this.dialogVisible = false
          //   this.loading = false
          // })
          // .catch(()=>{
          //   this.dialogVisible = false
          //   this.loading = false
          // })
        },
        
    }
}
</script>
<style scoped lang="scss">
.increase-viewers-box {
    width: 100%;
    height: calc( 100vh - 250px );
    box-sizing: border-box;
    overflow: hidden;
    overflow-y: auto;
    position: relative;
}
.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>