<template>
  <div class="payStatusPopup">
    <el-dialog :visible.sync="show" width="600px" :close-on-click-modal="false" :close-on-press-escape="false" :show-close="false" append-to-body custom-class="popup_box">
      <!-- 支付成功打印小票 -->
      <div v-if="type === 1">
        <div class="icon">
          <i class="el-icon-success success"></i>
        </div>
        <div class="message">支付成功</div>
        <div class="btn_box" v-if="hidePointer">
          <div class="btn" @click="confirm">确认</div>
        </div>
        <div class="btn_box" v-else>
          <template v-if="isRecharge">
            <div class="btn" @click="setPointer(0)">打印小票</div>
          </template>
          <template v-else>
            <div class="btn" @click="setPointer(0)">打印小票</div>
            <div class="line"></div>
            <div class="btn" @click="setPointer(1)">打印条码</div>
          </template>
        
          <div class="line"></div>
          <div class="btn" @click="close">关闭</div>
        </div>
      </div>
      <!-- 未支付 -->
      <div v-if="type === 2">
        <div class="icon">

          <i class="el-icon-warning warning"></i>
        </div>
        <div class="message">请支付后取衣</div>
        <div class="cell">
          <div class="label">需支付金额</div>
          <div class="amount_box">
            <span>￥</span>
            <span>{{ orderInfo.payAmount }}</span>
          </div>
        </div>
        <div class="cell">
          <div class="label">支付方式</div>
          <el-radio-group v-model="payType" @input="changePayType">
            <el-radio-button :label="3">余额</el-radio-button>
            <el-radio-button :label="2">现金</el-radio-button>
            <el-radio-button :label="0">微信/支付宝</el-radio-button>
          </el-radio-group>
        </div>
        <el-descriptions border direction="vertical" :column="3" :labelStyle="{ width: '140px' }" v-if="payType == '3'" style="margin: 0 30px">
          <el-descriptions-item label="用户" v-if="appUserInfo">{{ appUserInfo.realName }}</el-descriptions-item>
          <el-descriptions-item label="当前余额（元）" v-if="appUserInfo">{{ appUserInfo.rechargeBalance + appUserInfo.giveBalance }}</el-descriptions-item>
          <el-descriptions-item label="支付后余额（元）" v-if="appUserInfo">{{ appUserInfo.rechargeBalance + appUserInfo.giveBalance - orderInfo.payAmount }}</el-descriptions-item>
        </el-descriptions>
        <div class="cell" v-if="payType == 0">
          <div class="label">付款码</div>
          <!-- @change="handleQuery" -->
          <el-input ref="autoFocus" v-model="authCode" clearable placeholder="请选择付款码" />
        </div>
        <div class="btn_box">
          <div class="btn" style="color: #67c23a" @click="pay">确认支付</div>
          <div class="line"></div>
          <div class="btn" @click="close">关闭</div>
        </div>
      </div>
      <!-- 支付中，请等待 -->
      <div v-if="type == 3 || type == 5">
        <div class="icon">
          <i class="el-icon-loading loading"></i>
        </div>
        <div class="message">支付确认中，请等待...</div>

        <el-button type="primary" style="width: 70%; height: 40px; margin: 20px 15%" @click="close" v-if="showPaySuccessBtn">已确认支付</el-button>
      </div>
      <!-- 支付失败 -->
      <div v-if="type == 4">
        <div class="icon">
          <i class="el-icon-error error"></i>
        </div>
        <div class="message">{{ errorMessage }}</div>
        <div class="cell" v-if="!hideUser">
          <div class="label">支付方式</div>
          <el-radio-group v-model="payType" @input="changePayType">
            <el-radio-button :label="3">余额</el-radio-button>
            <el-radio-button :label="2">现金</el-radio-button>
            <el-radio-button :label="0">微信/支付宝</el-radio-button>
          </el-radio-group>
        </div>
        <el-descriptions border direction="vertical" :column="3" :labelStyle="{ width: '140px' }" v-if="payType == '3' && !hideUser" style="margin: 0 30px">
          <el-descriptions-item label="用户" v-if="appUserInfo">{{ appUserInfo.realName }}</el-descriptions-item>
          <el-descriptions-item label="当前余额（元）" v-if="appUserInfo">{{ appUserInfo.rechargeBalance + appUserInfo.giveBalance }}</el-descriptions-item>
          <el-descriptions-item label="支付后余额（元）" v-if="appUserInfo">{{ appUserInfo.rechargeBalance + appUserInfo.giveBalance - orderInfo.payAmount }}</el-descriptions-item>
        </el-descriptions>
        <div class="cell" v-if="payType == 0 && !hideUser">
          <div class="label">付款码</div>
          <!-- @change="handleQuery" -->
          <el-input ref="autoFocus" v-model="authCode" clearable placeholder="请选择付款码" />
        </div>
        <div class="btn_box">
          <div class="btn" style="color: #67c23a" @click="pay" v-if="!hideUser">确认支付</div>
          <div class="line" v-if="!hideUser"></div>
          <div class="btn" @click="close">关闭</div>
        </div>
      </div>
      <!-- 支付成功打印小票 -->
      <div v-if="type === 6">
        <div class="icon">
          <i class="el-icon-success success"></i>
        </div>
        <div class="message">下单成功</div>
        <div class="btn_box" v-if="hidePointer">
          <div class="btn" @click="confirm">确认</div>
        </div>
        <div class="btn_box" v-else>
          <div class="btn" @click="setPointer(0)">打印小票</div>
          <div class="line"></div>
          <div class="btn" @click="setPointer(1)">打印条码</div>
          <div class="line"></div>
          <div class="btn" @click="close">关闭</div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getLodop } from '@/utils/lodopUtils'
import { getClothItem, listOrderClothItem, printCloth } from '@/api/order/clothItem'
import { getMemberInfoById } from '@/api/app/user'
import { clothOrderPay, getOrderPayResult } from '@/api/order/cloth'
import { getUserProfile } from "@/api/system/user";
import { getStore } from '@/api/system/store'

export default {
  props: {
    hidePointer: {
      type: Boolean,
      default: false
    },
    hideUser: {
      type: Boolean,
      default: false
    },
    isRecharge: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      show: false,
      type: 1,
      orderInfo: {},
      number: 1,
      // 打印机设置
      LODOP: null,
      pointerList: [],
      // 打印收衣订单的数据
      pointerInfo: null,
      payType: 3,
      appUserInfo: {},
      authCode: '',
      time: '',
      showPaySuccessBtn: false,
      resultCount: 0,
      errorMessage: ''
    }
  },

  mounted() {
    this.number = 1
    const printerTime = setInterval(() => {
      this.LODOP = getLodop()
      this.number++
      if (this.number == 25) {
        clearInterval(printerTime)
      }
      if (this.LODOP) {
        clearInterval(printerTime)
      }
    }, 200)

    this.pointerList = JSON.parse(this.$cache.local.get('printerSeting'))
  },

  methods: {
    openSelected(info) {
      console.log()
      this.orderInfo = info
      this.type = 2
      if (this.hideUser) {
        this.payType = 2
      } else {
        this.payType = 2
        this.getUserInfoData(info.appUserId)
      }
      this.show = true
    },
    open(type, info, appUserInfo = null) {
      console.log(JSON.stringify(info))
      this.orderInfo = info
      this.type = type
      this.showPaySuccessBtn = false
      // this.pointerInfo = info
      if (info.id && !this.hidePointer) {
        this.getClothItemInfo(info)
      }
      console.log(this.type, appUserInfo)
      if (appUserInfo) {
          this.appUserInfo = appUserInfo
        }
      if (type == 0) {
        //微信支付宝支付
        this.payType = 0
        this.authCode = info.authCode
        this.showPaySuccessBtn = false
       
        console.log('aasss', this.appUserInfo)
        this.pay()
      }
      if (type == 1) {
       
      }
      if (type == 2) {
        //现金支付
        this.appUserInfo = {}
        this.authCode = ''
        this.showPaySuccessBtn = false
        if (this.hideUser) {
          this.payType = 2
        } else {
          this.payType = 2
          this.getUserInfoData(info.appUserId)
        }
        this.pay()

      }
      if (type == 3) {
        //会员支付
        this.payType = 3
        this.showPaySuccessBtn = false
        if (appUserInfo) {
          this.appUserInfo = appUserInfo
        }
        console.log('aasss', this.appUserInfo)
        this.pay()
      }
      if (type == 4) {
        this.errorMessage = info.payMsg
      }
      if (type == 5) {
        // this.getPayResult()
      }
      if (type == 6) {

      }
      this.show = true
    },

    close() {
      const _ = this
      if (this.type == 1 || this.type == 6) {
        // this.$confirm('是否关闭打印操作？')
        //   .then(() => {
            _.show = false
            _.$emit('close')
          // })
          // .catch(() => { })
      }
      if (this.type == 2) {
        this.$confirm('是否取消支付操作？')
          .then(() => {
            _.show = false
          })
          .catch(() => { })
      }
      if (this.type == 3 || this.type == 5) {
        this.$confirm('请确认客户已完成付款再关闭？')
          .then(() => {
            _.show = false
            _.clearTimeOut(_.time)
            _.$emit('paySuccess')
          })
          .catch(() => { })
      }
      if (this.type == 4) {
        _.show = false
      }
      // if (this.type == 6) {
      //   // if (!this.hidePointer) {
      //   //   this.$confirm('是否关闭打印操作？')
      //   //   .then(() => {
      //       _.show = false
      //       _.$emit('close')
      //     // })
      //   //   .catch(() => { })
      //   // } else {
      //   //   _.show = false
      //   // }
      // }
    },

    confirm() {
      this.show = false
      this.$emit('confirm', this.orderInfo)
    },

    setPointer(type) {
      if (!this.LODOP) {
        this.$modal.msgError('请安装打印机软件')
        return
      }

      let p_name = ''

      this.pointerList.forEach((pointer) => {
        if (pointer.printType == type) {
          p_name = pointer.printName
        }
      })
      if (this.isRecharge) {
        this.$emit('pointer', {
          id: this.orderInfo.orderId,
          appUserInfo: this.appUserInfo,
          LODOP: this.LODOP,
          p_name: p_name
        })
        return 
      }
      console.log(this.pointerList, p_name)
      

        if (type == 0) {
          this.collectClothPrinter(this.LODOP, this.pointerInfo, p_name)
        } else {
          this.barCodePrinter(this.LODOP, this.pointerInfo, p_name)
        }

        // this.show = false CL1108946378974957568

     
    },

    // 获取打印数据
    getClothItemInfo(data) {
      // getClothItem
      printCloth(data.id).then((res) => {
        if (res) {
          console.log('打印数据', res)
          if (this.getUserInfo().userType == '02') {
                const obj = {
                    name: this.getUserInfo().storeName,
                    contactPhone: this.getUserInfo().phonenumber,
                    user: this.getUserInfo().nickName,
                }
                // row.sysOrg = obj
                res.data.sysOrg = obj
            }
          this.pointerInfo = res.data
         
          // getStore(this.pointerInfo.orgId).then(res => {
            // console.log("AAA", res,  this.pointerInfo)
            // this.pointerInfo.sysOrg = res.data
          // })
          // listOrderClothItem({ pageSize: 99999, pageNum: 1, orderNo: data.orderNo }).then((res) => {
          //   console.log(res)
          //   this.pointerInfo.orderClothDetails = res.rows
          // })
        }
      })
    },

    // 获取用户信息
    getUserInfoData(id) {
      getMemberInfoById({
        appUserId: id
      }).then((response) => {
        this.appUserInfo = response.data
      })
    },

    changePayType() {
      if (this.payType == 0) {
        this.$nextTick((_) => {
          this.$refs.autoFocus.focus()
        })
      }
    },

    handleQuery(e, event) {
      console.log(event)
      console.log(this.authCode)
    },

    pay() {
      if (this.payType == 0 && !this.authCode) {
        this.type = 4
        this.errorMessage = '请先扫码'
        this.authCode = ''
        this.changePayType()
        return
      }
      if (this.payType == 3 && this.appUserInfo.rechargeBalance + this.appUserInfo.giveBalance < this.orderInfo.payAmount) {
        this.errorMessage = '余额不足'
        this.type = 4
        this.authCode = ''
        this.changePayType()
        return
      }
      this.type = 3
      clothOrderPay({
        appUserId: this.orderInfo.appUserId,
        payType: this.payType,
        authCode: this.authCode,
        orderNo: this.orderInfo.orderNo,
        payAmount: this.orderInfo.payAmount
      })
        .then((res) => {
          console.log('支付结果', res)
          if (res) {
            if (res.data.payResult == 100) {
              this.getPayResult()
            }
            if (res.data.payResult == 101 || res.data.payResult == 0) {
              this.errorMessage = res.data.payMsg
              this.type = 4
              this.authCode = ''
              this.changePayType()
            }
            if (res.data.payResult == 200) {
              this.type = 1
              this.$emit('paySuccess')
            }
          }
        })
        .catch((e) => {
          console.log('支付报错', e)
          this.type = 4
          this.authCode = ''
          this.changePayType()
          this.errorMessage = e
          // this.$message.error(e.data.msg)
        })
    },

    getPayResult() {
      getOrderPayResult({
        orderNo: this.orderInfo.orderNo
      })
        .then((res) => {
          console.log('支付结果1', res)
          if (res) {
            if (res.data.payResult == 100) {
              this.time = setTimeout(() => {
                if (this.resultCount == 6) {
                  this.showPaySuccessBtn = true
                } else {
                  this.resultCount++
                }
                this.getPayResult()
              }, 5000)
            }
            if (res.data.payResult == 101 || res.data.payResult == 0) {
              this.errorMessage = res.data.payMsg
              this.type = 4
              this.authCode = ''
              this.changePayType()
            }
            if (res.data.payResult == 200) {
              this.type = 1
              this.$emit('paySuccess')
            }
          }
        })
        .catch((e) => {
          this.type = 4
          this.authCode = ''
          this.errorMessage = e.data.msg
        })
    }
  }
}
</script>
<style>
.popup_box .el-dialog__body {
    padding: 0;
}
</style>
<style scoped lang="scss">
.icon {
    font-size: 100px;
    text-align: center;

    .success {
        color: #67c23a;
    }

    .warning {
        color: #e6a23c;
    }

    .loading {
        color: #e4e7ed;
    }

    .error {
        color: #f56c6c;
    }
}

.btn_box {
    display: flex;
    align-items: center;
    margin-top: 20px;
    font-size: 16px;
    font-weight: 500;
    border-top: 1px solid #ebeef5;

    .btn {
        flex: 1;
        text-align: center;
        line-height: 60px;
        cursor: pointer;
    }

    .line {
        width: 1px;
        height: 60px;
        background: #ebeef5;
    }
}

.del_btn {
    position: absolute;
    top: 20px;
    right: 20px;
    font-size: 20px;
    cursor: pointer;
}

.cell {
    display: flex;
    align-items: center;
    padding: 0 40px 20px;

    .label {
        margin-right: 20px;
        min-width: 80px;
    }
}

.amount_box {
    span {
        color: #f56c6c;
        font-weight: bold;
        font-size: 20px;
        &:first-child {
            font-size: 16px;
        }
    }
}

.message {
    font-size: 20px;
    text-align: center;
    padding: 10px 0 20px;
    color: #606266;
}
</style>
