<template>
  <view class="container">
    <Navbar title="确认订单" canBack></Navbar>
    <!-- <u-navbar title="确认订单" autoBack :safeAreaInsetTop="true" placeholder fixed></u-navbar> -->
    <view class="orderCss">
      <!-- <view class="orderTopBarCss">
        <u-icon name="car" color="#fff" size="20"></u-icon>
        <view class="text-white">
          站内配送
        </view>
      </view> -->
      <view class="addressBarCss" @click="selectAddress">
        <view class="leftCss">
          <u-icon name="map" size="25"></u-icon>
        </view>
        <view class="centerCss w50" v-if="hasAds">
          <view class="margin-top">
            联系人：{{ adsObj.name || "" }}
          </view>
          <view class="text-gray margin-top-sm text-sm w100 overflow-one-lines">
            详细地址：{{ adsObj.address || "" }}
          </view>
        </view>
        <view class="centerCss" v-else>
          请选择地址
        </view>
        <view class="rightCss">
          <u-icon name="arrow-right" size="20"></u-icon>
        </view>
      </view>
      <view class="shopCardCss">
        <view class="flex align-center">
          <u-icon name="/static/images/home/shopTitle.png" size="20"></u-icon>
          <view class="margin-left-xs">
            {{ gasDetail.fSsqymc || "" }}
            <!-- 利民液化气供应站 -->
          </view>
        </view>
        <view class="flex justify-between margin-top">
          <view class="">
            <u-image width="80px" height="80px" :src="gasDetail.image"></u-image>
          </view>
          <view class="flex flex-direction  justify-between margin-left-sm">
            <view class="">
              {{ gasDetail.fMc }}
              <!-- 15KG 液化石油气 -->
            </view>
            <view class="text-sm text-gray">
              描述：{{ gasDetail.fMs || "" }}
            </view>
            <view class="themeColor text-lg text-bold">
              ￥{{ gasDetail.fJg }}
            </view>
          </view>
          <view class="flex align-end">
            <u-number-box v-model="gasNumber" @change="gasNumberChange"></u-number-box>
          </view>
        </view>
        <view class="flex justify-between align-center margin-top">
          <view class="">
            订单备注
          </view>
          <view class="text-gray">
            <u-input inputAlign="right" maxlength="30" v-model="orderBody.mjly" border="none" clearable
                     placeholder="请填写您的备注信息"></u-input>
          </view>
        </view>
      </view>

      <view class="moneyCardCss">
        <view class="flex justify-between">
          <view class="">
            商品总金额
          </view>
          <view class="themeColor">
            ￥{{ totalPrice }}
          </view>
        </view>
        <view class="flex justify-between margin-top">
          <view class="text-gray">
            商品金额
          </view>
          <view class="">
            ￥{{ gasDetail.fJg }}
          </view>
        </view>
        <!-- <view class="flex justify-between margin-top">
          <view class="text-gray">
            气瓶押金
          </view>
          <view class="">
            ￥0.00
          </view>
        </view> -->
      </view>
      <view class="bomBarCss">
        <view class="themeColor themeFs">
          ￥{{ totalPrice }}
        </view>
        <view class="" @click="submitOrder">
          <u-button color="#EA5504">提交订单</u-button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import {
  mergeRecursive
} from "@/utils/ruoyi";
import storage from '@/utils/storage'
import {
  mapGetters
} from 'vuex'

export default {
  components: {},
  props: {},
  data() {
    return {
      orderBody: {
        // fBz: "",
        // fDdje: "",
        // fPsdz: "",
        // fQyid: "",
        // fCzid: "",
        ddly: "线上下单",
        zffs: "",
        psfs: "配送",
        mjly: "",
        hydzId: "",
        ddlx: "配送",
        sfhy: "是",
        xqList: [],
      },
      adsObj: {
        name: "",
        address: ""
      },
      qplist: {
        qplxId: "",
        sl: 1
      },
      totalPrice: 0,
      qpid: "",
      gasDetail: {},
      gasNumber: 1,
      hasAds: false,
      adsId: ""
    }
  },
  onLoad(data) {
    if (data.qpid) {
      this.qpid = data.qpid;
      this.qplist.qplxId = data.qpid;
    }
    if (data.adsId) {
      this.adsId = data.adsId;
    }
  },
  async onShow() {
    await this.getGasDetail();
    await this.getAdsDetail();
    // this.$store.dispatch('GetDefaultAds').then(async (res) => {
    // 	console.log("是否默认地址",res);
    // 	if(res === 'Default'){
    // 	}
    // }).catch(e => {
    // 	console.log("查询地址错误", e);
    // });
  },
  computed: {
    // ...mapGetters({
    // 	adsId: 'adsId'
    // })
  },
  methods: {
    async getGasDetail() {
      let query = {
        id: this.qpid
      }
      const result = await this.$api.memberApi.getwQplxDetail(query);
      let {
        code,
        value
      } = result;
      if (code === 200) {
        this.gasDetail = value;
        // this.orderBody.fCzid = this.gasDetail.fSsczid;
        // this.orderBody.fQyid = this.gasDetail.fSsqyid;
        // this.orderBody.fDdje = this.gasDetail.fJg;
        this.totalPrice = this.gasDetail.fJg;
        let JsonParse = JSON.parse(this.gasDetail.fTp);
        this.gasDetail.image = await this.$getPhotoUrl(JsonParse[0].response.fileId);
        this.gasDetail = {
          ...this.gasDetail
        };
        console.log('气瓶详情', JSON.parse(JSON.stringify(this.gasDetail)));
      }
    },
    async getAdsDetail() {
      let that = this;
      let formData = {
        current: 1,
        size: 99
      }
      const result = await this.$api.memberApi.getwHydzList(formData);
      let {
        code,
        value
      } = result;
      if (code === 200) {
        let data = value.records;
        const defaultAddress = data.find(item => item.fSfmrdz === 'y' || item.id === that.adsId);
        if (defaultAddress) {
          console.log("默认地址", defaultAddress);
          let area = defaultAddress.fLxrsf + defaultAddress.fLxrs + defaultAddress.fLxrq + defaultAddress
              .fLxrjd
          that.$set(that.orderBody, "hydzId", defaultAddress.id);
          that.$set(that.adsObj, "name", defaultAddress.fLxr);
          that.$set(that.adsObj, "address", area);
          // that.orderBody.hydzId = defaultAddress.id;
          // that.adsObj.name = defaultAddress.fLxr;
          // that.adsObj.address = area;
          that.hasAds = true;
        } else {
          that.orderBody.hydzId = "";
          that.adsObj.name = "";
          that.adsObj.address = "";
          that.hasAds = false;
        }
      }
    },
    gasNumberChange(e) {
      let number = e.value;
      let price = this.gasDetail.fJg;
      this.qplist.sl = number;
      this.totalPrice = this.$calcUtil.ride(price, number)
    },
    selectAddress() {
      uni.navigateTo({
        url: '/pages/mine/appList/addressManagement/addressManagement?qpid=' + this.qpid
      })
    },
    async submitOrder() {
      this.orderBody.xqList[0] = this.qplist;
      console.log("提交数据", this.orderBody);
      if (!this.orderBody.hydzId) {
        uni.$u.toast('未选择配送地址');
        return false
      }
      this.$modal.confirm('确认提交订单？', '提示').then(async () => {
        // console.log("提交数据", this.orderBody);
        // uni.navigateTo({
        // 	url:"/pages/home/orderSuccessful"
        // })
        const result = await this.$api.memberApi.savewDd({...this.orderBody, zffs: '微信', zflx: 'JSAPI'});
        let {
          code,
          value
        } = result;
        if (code === 200) {
          console.log('value--->',value);
          //在这里唤起支付
          this.handlePayment(value); // 处理支付逻辑
        }
      }).catch(() => {
        console.log("取消");
      });
    },
    handlePayment(paymentData) {
      // 支付参数对象
      const paymentParams = {
        appId: paymentData.payment.appId,
        timeStamp: paymentData.payment.timeStamp,
        nonceStr: paymentData.payment.nonceStr,
        package: paymentData.payment.packageValue,
        signType: paymentData.payment.signType,
        paySign: paymentData.payment.paySign
      };
      // 调用微信支付
      this.initWechatPay(paymentParams,paymentData);
    },
    initWechatPay(paymentParams,paymentData) {
      if (typeof WeixinJSBridge == "undefined") {
        if (document.addEventListener) {
          document.addEventListener('WeixinJSBridgeReady', () => {
            this.onBridgeReady(paymentParams,paymentData);
          }, false);
        } else if (document.attachEvent) {
          document.attachEvent('WeixinJSBridgeReady', this.onBridgeReady(paymentParams,paymentData));
          document.attachEvent('onWeixinJSBridgeReady', this.onBridgeReady(paymentParams,paymentData));
        }
      } else {
        this.onBridgeReady(paymentParams,paymentData);
      }
    },
    onBridgeReady(paymentParams,paymentData) {
      WeixinJSBridge.invoke(
          'getBrandWCPayRequest',
          paymentParams,
          res => {
            if (res.err_msg == "get_brand_wcpay_request:ok") {
              // 支付成功
              console.log('支付成功',paymentParams);
              // 可以跳转到支付成功的页面
              uni.navigateTo({
                url: "/pages/home/orderSuccessful?datas=" +  JSON.stringify({ddid:paymentData.ddid})
              });
            } else {
              // 支付失败
              console.error('支付失败', res.err_msg);
            }
          }
      );
    }
  }
}
</script>

<style lang="scss" scoped>
.orderCss {
  // margin: 10px;

  .orderTopBarCss {
    background: #EA5504;
    height: 40px;
    border-radius: 10px 10px 0 0;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .addressBarCss {
    position: relative;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-radius: 0 0 10px 10px;
    background: #ffffff;
    padding: 10px 10px 20px 10px;

    .leftCss {
      width: 10%;
    }

    .centerCss {
      width: 80%;
      min-height: 50px;
      margin-left: 5px;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: flex-start;
    }

    .rightCss {
      width: 10%;
    }
  }

  .addressBarCss {
    background-color: #fff;
    position: relative;
  }

  .addressBarCss:before {
    position: absolute;
    right: 0;
    bottom: 0;
    left: 0;
    height: 5px;
    background: repeating-linear-gradient(-45deg, #A82831, #A82831 20%, transparent 0, transparent 25%, #254A81 0, #254A81 45%, transparent 0, transparent 50%);
    background-size: 200px;
    content: "";
  }

  .shopCardCss {
    margin: 10px;
    margin-top: 10px;
    padding: 20px 10px;
    border-radius: 15px;
    background: #ffffff;
  }

  .moneyCardCss {
    margin: 10px;
    padding: 20px 10px;
    border-radius: 15px;
    background: #ffffff;
  }

  .bomBarCss {
    position: absolute;
    width: 100%;
    bottom: 0;
    left: 0;
    padding: 0 20px;
    background: #fff;
    height: 50px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  /deep/ .bomBarCss .u-button {
    border-radius: 10px !important;
    width: 120px;
  }
}
</style>
