import { 
    orderInfoSubmit,
    gotoMicroPay,
    gotoCashPay,
    payQuery,
    selectRegion,
    orderInfoCancel,
    factorAuth,
    selectMarketTeamBySourceApi,
   } from '@/api/windowTicketSales/ticketingSales'
   import { 
    gotoCorporatePay, 
    downOrderListXls,
    teamPayOrderUrlApi,
    balancePay as gotoBalancePay,
    creditPay as gotoQuotaPay
   } from '@/api/order/groupBuyingMr';
   import { pageList as getPrintListApi } from "@/api/device/pda";
   import { printApi } from '@/api/windowTicketSales/ticketingCollection'
   import { rebookApi } from '@/api/windowTicketSales/rebook'
   const mathM = require('mathjs')
   const https = require('https');
   const axios = require('axios');
export default {
    data(){
        return {}
    },
    methods: {
        /**  取消订单   */
        async orderInfoCancelFun(type){
            // let payStatus = this.payStatus
            // this.payStatus = null
            try {
                this.loading = true
                this.loadingText = "取消订单中..."
                orderInfoCancel({
                    orderId: this.orderId
                }).then((res)=>{
                    if(res.code==200) {
                        if(type){ // 关闭弹窗
                            if(this.codeTime) {
                                clearInterval(this.codeTime)
                            }
                            this.orderId = null
                            this.payStatus = null
                            this.$emit('clearDialogVisible')
                            this.rebookDialog = false
                        }else {
                            this.payStatus = 9
                            this.loading = false
                        }
                        
                    }else {
                        
                    }
                }).catch(()=>{
                    this.$message.error('订单关闭失败!!!');
                })
            } catch (error) {
                
            }
        },
        /**  生成订单  */
        async orderInfoSubmitFun(){
            this.loading = true
            try {
                this.orderId = null
                this.loadingText = "生成订单中..."
                let res = await rebookApi({
                    ...this.rebookForm
                })
                if(res.code == 200){
                    this.orderId = res.data.orderId
                    if(this.rebookForm.paymentType == 2) { // 现金支付
                        this.gotoCashPayFun(this.orderId)
                    }else if(this.rebookForm.paymentType == 3 || this.rebookForm.paymentType == 6) { // 对公支付
                        this.gotoCorporatePayFun(this.orderId)
                    }else if(this.rebookForm.paymentType == 4){ // 账户余额
                        this.gotoBalancePayFun(this.orderId)
                    }else if(this.rebookForm.paymentType == 5){ // 授信余额
                        this.gotoQuotaPayFun(this.orderId)
                    }else if(this.rebookForm.paymentType == 7) {
                        this.handPlaceAnOrder()
                    }
                    else {
                        // 扫码支付
                        this.loading = false
                        this.payStatus = 2
                    }
                }else{
                    this.$message.error('生成订单失败!!!');
                    this.loading = false
                    this.payStatus = 1
                }
            } catch (error) {
                console.error(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.rebookForm.realPrice,
                    payOrCredit: this.rebookForm.paymentType = 3 ? '1' : '2',
                    rePaymentTime: this.rebookForm.rePaymentTime,
                    corporate: {
                        voucherUrl: this.rebookForm.photoList.map(item => item).join(","),
                        remark: ''
                    }
                })
                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 gotoQuotaPayFun(orderId) {
            this.loading = true
            try {
                this.loadingText = "订单入库中..."
                let res = await gotoQuotaPay({
                    "orderId": orderId, // 订单编号-提交订单返回
                })
                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 gotoBalancePayFun(orderId) {
            this.loading = true
            try {
                this.loadingText = "订单入库中..."
                let res = await gotoBalancePay({
                    "orderId": orderId, // 订单编号-提交订单返回
                })
                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.rebookForm.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
            }
        },
        /**  链接支付  */
        handPlaceAnOrder() {
            this.$confirm("确认要生成该订单的支付链接吗?温馨提示：请勿随意将链接发送给陌生人", '提示', {
            confirmButtonText: '生成并复制链接',
            cancelButtonText: '取消',
            type: 'warning'
            }).then(() => {
                this.loadingText = "生成并复制链接中..."
                this.loading = true
                teamPayOrderUrlApi({ orderId: this.orderId }).then((res) => {
                    if (res.code == 200) {
                        this.$message({
                            type: 'success',
                            message: res.msg
                        });
                        this.copyToClipboard(res.data.url)
                    }
                }).catch(() => {
                    this.loading = false
                    this.payStatus = null
                })
            }).catch(() => {
                this.loading = false
                this.payStatus = null
             }).finally(() => {
            });
        },
        /**  复制内容  */
        copyToClipboard(text) {
            // 创建一个临时的textarea元素
            const tempInput = document.createElement('textarea');
            tempInput.value = text;
            document.body.appendChild(tempInput);
            tempInput.select();
            document.execCommand('copy');
            document.body.removeChild(tempInput);
            this.loading = false
            this.rebookDialog = false

        },
        // 跳转取票界面
        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.rebookForm.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.rebookForm.paymentType == 2){
                                this.$message.error('"订单入库中失败"');
                                this.loading = false
                                this.payStatus = 3
                            }else {
                                if(res.data.orderStatus == 9 || res.data.orderStatus == 4 || res.data.orderStatus == 5){
                                    this.$message.error('订单已关闭，请重新选择座位，再购买!!!');
                                    this.loading = false
                                    this.payStatus = 10
                                }else {
                                    this.$message.error('用户未支付!!!');
                                    this.loading = false
                                    this.payStatus = 7
                                }
                            }
                            
                        }else if(res.data.payStatus == 1) {
                            if(this.payTime){
                                clearInterval(this.payTime)
                            }
                            if(this.rebookForm.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()
                            }
                            this.rebookDialog = false
                            
                        }else if(res.data.payStatus == 2) {

                        }else if(res.data.payStatus == 3) {
                            if(this.payTime){
                                clearInterval(this.payTime)
                            }
                            if(this.rebookForm.paymentType == 2){
                                this.$message.error('"订单入库中失败"');
                                this.loading = false
                                this.payStatus = 3
                            }else {
                                if(res.data.orderStatus == 9 || res.data.orderStatus == 4 || res.data.orderStatus == 5){
                                    this.$message.error('订单已关闭，请重新选择座位，再购买!!!');
                                    this.loading = false
                                    this.payStatus = 10
                                }else {
                                    this.$message.error('用户支付失败!!!');
                                    this.loading = false
                                    this.payStatus = 7
                                }
                            }
                        }else if(res.data.payStatus == 4) {
                            if(this.payTime){
                                clearInterval(this.payTime)
                            }
                            
                            if(this.rebookForm.paymentType == 2){
                                this.$message.error('"订单入库中失败"');
                                this.loading = false
                                this.payStatus = 3
                            }else {
                                if(res.data.orderStatus == 9 || res.data.orderStatus == 4 || res.data.orderStatus == 5){
                                    this.$message.error('订单已关闭，请重新选择座位，再购买!!!');
                                    this.loading = false
                                    this.payStatus = 10
                                }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.code = ''
            this.websocketClear()
            this.payStatus = 5 // 连接成功
            document.addEventListener('keydown',this.keydownAdd);
            this.loading = false
        },  
        /**  连接结果 */
        websocket_open_state(message){
            console.log("连接结果 ===== ",message)
            this.codeTime = setInterval(()=>{
                console.log("检测是否连接")
                if(this.websocketData.readyState != WebSocket.OPEN) {
                    this.payStatus = 6
                }
            },3000)
            //document.getElementById('wsocket').value = "已连接";
        },
        // 拼接字符串
        keydownAdd(e){
            console.log("e=====",e)
            console.log("this.code=====",this.code)
            if( this.payStatus == 5 && e.key != 'Enter') {
                this.code = this.code + e.key
            }

            if( e.key == 'Enter') {
                document.removeEventListener('keydown',this.keydownAdd);
                let codeCopy = this.code
                this.payStatus == 5.5
                this.code = ''
                this.gotoMicroPayFun(this.orderId,codeCopy)
            }
        },
        //接收扫码完整结果处理
        websocket_decode(code){
            console.log("orderId=========",this.orderId )
            console.log("code=========",code)
            if(this.orderId && this.payStatus == 5.5 &&  regex.test(code) ) {
                this.payStatus = 5.6 // 支付中
                let codeCopy = code.replace("%%%", "").replace("%%%", "")
                this.gotoMicroPayFun(this.orderId,codeCopy)
            }else if(!code){
                this.payStatus = 5
                this.code = ''
            }
        },
        /** 关闭通讯 */
        websocketClear(){
            document.removeEventListener('keydown',this.keydownAdd);
        },
        /**  读取身份证 */
        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.rebookDialog = false
            this.loading = false
          }).catch(()=>{
            this.loading = false
            this.payStatus = 8
            // this.rebookDialog = false
            // this.loading = false
          })
          // 在 axios 请求时，选择性忽略 SSL
          // const agent = new https.Agent({  
          //   rejectUnauthorized: false
          // });
          // axios.post(
          //   url, 
          //   { httpsAgent: agent,...data }
          //   ).then(()=>{
          //   this.rebookDialog = false
          //   this.loading = false
          // })
          // .catch(()=>{
          //   this.rebookDialog = false
          //   this.loading = false
          // })
        },
        /** 获取授信余额和账户余额  */
        async selectMarketTeamBySourceFun(value) {
            console.log("value===",value)
            try {
                if(!['10','11','13','14','18','19'].includes(value)) return
                let res = await selectMarketTeamBySourceApi({
                    source: value
                })
                this.balance = res.data.balance
                if(res.data.grantQuota && res.data.grantUsed) {
                    this.grantQuota = res.data.grantQuota - res.data.grantUsed
                }else if(res.data.grantQuota) {
                    this.grantQuota = res.data.grantQuota
                }else {
                    this.grantQuota = 0
                }
                
            } catch (error) {
                this.balance = null
                this.grantQuota = null
            }
        },
    },
}