<template>
  <el-dialog title="支付结算" v-model="dialogVisible" width="1100px" @close="cancel" destroy-on-close>
      <el-form ref="form" label-width="0px">
        <div class="settlement">
          <div class="left">
              <div class="title">请选择支付方式</div>
              <div class="content">
                 <div :class="'pay-item' + (payType == 'cash' ? ' active' : '')" @click="selectPayType('cash')">
                    <img class="icon" src="@/assets/svgs/cash.svg"/>
                    <div class="name">现金支付</div>
                 </div>
                 <div :class="'pay-item' + (payType == 'yue' ? ' active' : '')" @click="selectPayType('yue')">
                    <img class="icon" src="@/assets/svgs/money2.svg" />
                    <div class="name">余额支付</div>
                 </div>
                <div :class="'pay-item' + (payType == 'weixin' ? ' active' : '')" @click="selectPayType('weixin')">
                  <img class="icon" src="@/assets/svgs/weixin.svg" />
                  <div class="name">微信支付</div>
                </div>
                <div :class="'pay-item' + (payType == 'alipay' ? ' active' : '')" @click="selectPayType('alipay')">
                  <img class="icon" src="@/assets/svgs/slipay.svg" />
                  <div class="name">支付宝支付</div>
                </div>
              </div>
          </div>
          <div class="main">
              <div class="title">结算信息</div>
              <div class="content">
                  <div class="remark-info">
                    <div>备注信息：</div>
                    <el-form-item class="form-item" prop="remark">
                      <el-input type="textarea" v-model="remark"  placeholder="请输入备注信息" clearable/>
                    </el-form-item>
                  </div>
                  <div class="discount-info">
                    <el-row>
                      <el-col :span="12">
                        <div>折扣:（折）</div>
                        <el-form-item class="form-item" prop="discount">
                          <el-input type="number" v-model="discountAmount" style="width: 200px" placeholder="请输入折扣" clearable/>
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <div>立减:（元）</div>
                        <el-form-item class="form-item" prop="reduce">
                          <el-input type="number" v-model="reduceAmount" style="width: 200px" placeholder="请输入立减金额" clearable/>
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </div>
                  <div class="amount-info">
                     <span class="discount-amount">优惠金额：￥<span class="value">{{preferentAmount}}</span></span>
                     <span class="pay-amount">应付金额：￥<span class="value">{{payPrice}}</span></span>
                  </div>
              </div>
          </div>
          <div class="right">
              <div class="title">会员信息</div>
              <div class="content">
                <div class="member-info" v-if="memberInfo.nickname">
                    <img class="avatar"  :src="memberInfo.avatar"/>
                    <div class="item"><div class="head">名称：</div><div class="value">{{memberInfo.nickname}}</div></div>
                    <div class="item"><div class="head">手机号：</div><div class="value">{{memberInfo.mobile ? memberInfo.mobile : '未绑定'}}</div></div>
                    <div class="item"><div class="head">可用余额：</div><div class="value">{{memberInfo.nowMoney}}（元）</div></div>
                    <div class="item"><div class="head">可用积分：</div><div class="value">{{memberInfo.integral}}</div></div>
                </div>
                <div class="guest" v-else>
                     <el-empty description="当前为游客" :image-size="30" />
                     <el-button calss="do-action" size="mini" type="danger" @click="chooseUser()"><Icon icon="ep:plus" class="mr-5px" /> 关联会员</el-button>
                </div>
              </div>
          </div>
        </div>
      </el-form>
      <template #footer>
        <div>
            <el-button type="primary" @click="submit()">确定收款</el-button>
            <el-button @click="cancel()">取 消</el-button>
        </div>
      </template>
  </el-dialog>
   <user-select ref="UserSelectRef" @saveUser="saveUser"/>
   <payResult ref="payResultRef" :order-id="orderId" />
   <scanPay ref="scanPayRef" />
</template>
<script  setup lang="ts" name="settlement">
import UserSelect from "@/views/mall/member/user/UserSelect.vue";
import payResult from './payResult.vue'
import scanPay from './scanPay.vue'
import * as CashierApi from '@/api/mall/cashier'
const message = useMessage() // 消息弹窗
const dialogVisible = ref(false)
const payType = ref('cash')
const discountAmount = ref(0)
const reduceAmount = ref(0)
const remark = ref('')
const memberInfo = ref({})
const orderId = ref('')
//const authCode = ref('')


const props = defineProps<{
  cartData: [],
  shopId: 0
}>()

const selectPayType = (type) => {
  payType.value = type
}

const getCartGoodsPrice = computed(() =>{ //计算购物车总价
	let price = props.cartData.reduce((acc, cur) => acc + cur.cartNum * cur.price, 0);
	return parseFloat(price).toFixed(2);
})

const preferentAmount = computed(() =>{ //计算优惠金额
  console.log('discountAmount.value:',discountAmount.value)
  let dis = 0
  if(discountAmount.value > 0){
    dis = getCartGoodsPrice.value - getCartGoodsPrice.value * (discountAmount.value/10)
  }
  let pre = Number(dis) + Number(reduceAmount.value)
 
  if(pre > getCartGoodsPrice.value){
    reduceAmount.value = 0
    discountAmount.value = 0
    return 0
  }
	return parseFloat(pre).toFixed(2);
})

const payPrice = computed(() =>{ //支付价格
	let price = getCartGoodsPrice.value - preferentAmount.value
	return parseFloat(price).toFixed(2);
})


const open = async () => {
  dialogVisible.value = true
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const UserSelectRef = ref()
const chooseUser = () => {
  UserSelectRef.value.open()
  
}

const saveUser =async(user) => {
  memberInfo.value = user
}
const emit = defineEmits<{
  getCartList: [shopId]
}>()
const payResultRef = ref()
const scanPayRef = ref()
const submit = async() => {
  let data = {
    uidType: 'admin',
    shopId: props.shopId,
    productId: [],
		spec: [],
		number: [],
    remark: remark.value,
    mobile: memberInfo.value.mobile,
    orderType:'takein',
    gettime: 0,
    payType: payType.value,
    deductionPrice:preferentAmount.value,
    uid:memberInfo.value.id ? memberInfo.value.id : 0,
    cartIds:[]
  }
  props.cartData.forEach((item, index) => {
		data.productId.push(item.productId);
		data.spec.push(item.sku);
		//data.spec.push(item.valueStr);
		data.number.push(item.cartNum);
    data.cartIds.push(item.id);
	})

  const res = await CashierApi.createOrder(data)
  if(res){
    orderId.value = res.orderId
    dialogVisible.value = false
    emit('getCartList', props.shopId)
    if(payType.value == 'weixin' || payType.value == 'alipay'){
      scanPayRef.value.open(orderId.value)
    }else{
      doPay('')
      payResultRef.value.open()
      
    }
     
  }


}

const cancel = () => {
  dialogVisible.value = false
}

const doPay = async(code) => {
  let payRes  = await CashierApi.pay({
        uni: orderId.value,
        from: 'scan',
        paytype: payType.value,
        uid:memberInfo.value.id ? memberInfo.value.id : 0,
        authCode: code
      });
  console.log('payRes:',payRes)
}

/** 初始化 **/
onMounted(() => {
   // 监听扫码枪按键
  let code = '';
  let lastTime, nextTime; // 上次时间、最新时间
  let lastCode, nextCode; // 上次按键、最新按键
  document.onkeypress = (e) => {
    // 获取按键
    if (window.event) { // IE
        nextCode = e.keyCode;
    } else if (e.which) { // Netscape/Firefox/Opera
        nextCode = e.which;
    }
    // 如果触发了回车事件(扫码结束时间)
    if (nextCode === 13) {
        if (code.length < 3) {
            return;
        }
       console.log('payCode:',code)
       console.log('payType.value:',payType.value)
       console.log('dialogVisible.value:',dialogVisible.value)
       //authCode.value =code;
       if(payType.value == 'weixin' || payType.value == 'alipay'){
           if(!dialogVisible.value){
              doPay(code)
           }
       }

       code = '';
       lastCode = '';
       lastTime = '';
       return true;
    }
    nextTime = new Date().getTime(); // 记录最新时间
    if (!lastTime && !lastCode) { // 如果上次时间和上次按键为空
        code += e.key; // 执行叠加操作
    }
    // 如果有上次时间及上次按键
    if (lastCode && lastTime && nextTime - lastTime > 30) {
        code = e.key;
    } else if (lastCode && lastTime) {
        code += e.key;
    }
    lastCode = nextCode;
    lastTime = nextTime;
  }
})

</script>
<style lang="scss" scoped>

 .settlement {
   border: solid 1px #ccc;
   border-radius: 2px;
   min-height: 350px;
   margin: 0 auto;
   .left {
      width: 200px;
      float: left;
      height: 350px;
      padding: 10px;
      border-right: solid 1px #ccc;
      .title {
        margin-bottom: 10px;
        font-weight: bold;
      }
      .pay-item {
         height: 65px;
         line-height: 65px;
         border-radius: 2px;
         text-align: center;
         margin-bottom: 10px;
         border: solid 2px #cccccc;
         text-align: center;
         padding-left: 35px;
         cursor: pointer;
         .icon {
           margin-top: 15px;
           float: left;
         }
         .name {
            margin-left: 2px;
            font-size: 14px;
            color: #888888;
            float: left;
         }
      }
      .active {
         border: 3px solid #F56C6C;
         background: #FDF5E6;
         color: #FFFFFF;
      }
   }
   .main {
      float: left;
      padding: 10px;
      width: 598px;
      height: 348px;
      position: relative;
      .title {
        margin-bottom: 10px;
        font-weight: bold;
      }
      .content {
        width: 100%;
        .discount-info {
           height: 40px;
        }
        .amount-info {
           text-align: right;
           position: absolute;
           width: 580px;
           bottom: 30px;
           font-size: 16px;
           .discount-amount {
              margin-right: 50px;
               .value {
                 font-size: 20px;
               }
           }
          .pay-amount {
              .value {
                font-weight: bold;
                color: #ff5b57;
                font-size: 20px;
              }
          }
        }
      }
   }
   .right {
     float: right;
     padding: 10px;
     width: 200px;
     height: 333px;
     border-left: solid 1px #ccc;
     .title {
        margin-bottom: 10px;
        font-weight: bold;
     }
     .content {
        .member-info {
           .avatar {
              width: 50px;
              height: 50px;
              border-radius: 25px;
              border: solid 2px #cccccc;
           }
           .item {
              margin-top: 10px;
              border: dashed 1px #CCCCCC;
              padding: 5px;
              .head {
                 float: left;
              }
              .value {
                 margin-top: 1px;
                 text-align: left;
              }
           }
        }
        .guest {
           text-align: center;
           .do-action {
              height: 8px;
              line-height: 8px;
           }
        }
     }
   }
 }
</style>
