<template>
  <zj-page-layout :hasFooter="true">
    <view class="all-container">
      <view class="address-container card" @tap="chooseAddress">
        <view class="left">
          <view class="icon"><text class="iconfont icon-dingwei1"></text></view>
          <view class="nodata" v-if="!addressInfo">选择收货地址</view>
          <view class="hasdata" v-else>
            <view class="name">{{ addressInfo.name }}<text>{{ addressInfo.phone }}</text></view>
            <view class="address ellipsis-2">
              {{ addressInfo.province }}{{ addressInfo.city }}{{ addressInfo.area }}{{ addressInfo.street }}{{
                addressInfo.address }}{{ addressInfo.houseNo }}
            </view>
          </view>
        </view>
        <text class="right iconfont icon-jinru"></text>
      </view>

      <view class="card goods-container">
        <view class="item">
          <image :src="detail.imgList && detail.imgList[0].imgUrl" mode="aspectFill"></image>
          <view class="right">
            <view class="name ellipsis-2">{{ detail.goodsName }}</view>
            <view class="des">{{ detail.goodsNote }}</view>
            <view class="bottom">
              <view class="price">{{ detail.price | priceFilter2 }}</view>
              <u-number-box @tap.stop v-model="num" :min="1" :max="detail.qty" :buttonSize="26" iconStyle="font-size: 12px;">
              </u-number-box>
            </view>
          </view>
        </view>
        <view class="total">订单总金额<text>{{(detail.price * num) | priceFilter2}}</text></view>
      </view>

      <view class="card row-container" v-if="detail.price > 0">
        <view class="item">
          <view class="title">支付方式</view>
          <view class="radio-group">
            <view class="radio" @tap="payType = 1" v-if="detail.price > 0">
              <text class="iconfont" :class="payType === 1 ? 'icon-danxuan2 active' : 'icon-danxuan'"></text>
              在线支付
            </view>
            <view class="radio" @tap="payType = 2" v-if="userInfo.storePay">
              <text class="iconfont" :class="payType === 2 ? 'icon-danxuan2 active' : 'icon-danxuan'"></text>
              到店支付
            </view>
          </view>
        </view>
      </view>
    </view>

    <template slot="footer">
      <view class="bottom-container">
        <view class="left">实付款：<text>{{(detail.price * num) | priceFilter2}}</text></view>
        <view class="right">
          <u-button type="primary" text="提交订单" @click="submitOrder"></u-button>
        </view>
      </view>
    </template>
  </zj-page-layout>
</template>

<script>
  import { weixinPay, mini_env } from '@/common/utils/util.js';

  export default {
    data() {
      return {
        id: null,
        detail: {},
        userInfo: {},
        addressInfo: null, // 收货地址信息
        num: 1,
        payType: 1,
        orderId: null, // 订单id
      }
    },

    async onLoad({id}) {
      this.id = id;
      this.getDetail();
      this.getAddress();
      this.userInfo = await this.$getUserInfo();

      // 接收地址信息
      this.crossPage.$on('chooseAddress', result => {
        this.addressInfo = result;
        // this.getOrderInfo();
      })
    },

    onUnload() {
      this.crossPage.$off('chooseAddress');
    },

    methods: {
      getDetail() {
        this.$api.post('/es/goods/detail', {
          id: this.id
        }).then(res => {
          this.detail = res.data;
          // 面议默认到店支付
          if(this.detail.price <= 0) {
            this.payType = 2;
          }
        })
      },

      // 获取地址信息
      async getAddress() {
        return new Promise((resolve, reject) => {
          this.$api.get('/user/address/list', {
            pageNum: 1,
            pageSize: 100,
            userId: this.$store.state.user.userId
          }).then(res => {
            let item = res.data.records.find(o => o.defaultAddr);
            this.addressInfo = item || null;
            resolve();
          })
        })
      },

      // 去选择地址
      chooseAddress() {
        this.$navToPage({
          url: '/packageMine/pages/address/list?isChoose=' + true
        })
      },

      submitOrder() {
        if (!this.addressInfo) return this.$toast('请先选择收货地址');

        let that = this;
        mini_env((bool) => {
          this.$api.postJson('/es/orderPay/buy', {
            esGoodsId: this.id,
            num: this.num,
            userAddressId: this.addressInfo.userAddressId,
            payType: this.payType == 1 ? 'WECHAT' : 'CASH',
            ...(() => {
              if (bool) {
                return {
                  miniPay: true,
                  openId: this.$store.state.user.miniOpenId
                }
              }
              return {}
            })()
          }).then(res => {
            if (res.code === 1100) {
              return that.$tips(res.message);
            }
            // 不需要支付
            if (res.data.isPay === false) {
              that.$successToast('购买成功');
              that.orderId = res.data.id;
              that.crossPage.$emit('refreshRecycleList');
              that.crossPage.$emit('refreshRecycleDetail');
              that.crossPage.$emit('refreshRecycleSearch');
              setTimeout(() => {
                that.$navToPage({
                  url: `/packageHome/pages/recycle/order/list?id=${that.orderId}`
                }, 'reLaunch');
              }, 1000)
            }
            // 需要支付
            else {
              // 小程序环境
              if (bool) {
                uniWebview.navigateTo({
                  url: `/pages/pay/recycle?${Object.entries({
                    ...res.data,
                    payPackage: res.data.payPackage.split("=")[0] || "",
                    payPackageVal: res.data.payPackage.split("=")[1] || ""
                  }).map(item => item.join("=")).join("&")}`
                })
              }
              // h5环境
              else {
                weixinPay(res.data, function (res) {
                  that.$successToast('购买成功');
                  that.orderId = res.data.id;
                  that.crossPage.$emit('refreshRecycleList');
                  that.crossPage.$emit('refreshRecycleDetail');
                  that.crossPage.$emit('refreshRecycleSearch');
                  setTimeout(() => {
                    that.$navToPage({
                      url: `/packageHome/pages/recycle/order/list?id=${that.orderId}`
                    }, 'reLaunch');
                  }, 1000)
                })
              }
            }
          })
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
.all-container {
  padding: 0 20rpx 20rpx;
}

.card {
  @include zj-card;
  background: #FFFFFF;
  border-radius: 20rpx;
  margin-top: 20rpx;
  padding: 0 20rpx;
}

.address-container {
  background: #FFFFFF;
  border-radius: 20rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 150rpx;
  padding: 0 20rpx;

  .right {
    font-size: 32rpx;
    color: $sec-font;
    flex-shrink: 0;
  }

  .left {
    display: flex;
    align-items: center;
    margin-right: 20rpx;

    .icon {
      width: 52rpx;
      height: 52rpx;
      border-radius: 50%;
      background: $theme-color;
      display: flex;
      flex-shrink: 0;
      justify-content: center;
      align-items: center;
      margin-right: 20rpx;

      .iconfont {
        font-size: 36rpx;
        color: #ffffff;
      }
    }

    .nodata {
      font-size: 28rpx;
      color: #999999;
    }

    .hasdata {
      .name {
        font-size: 32rpx;
        color: #333333;

        text {
          color: #999999;
          font-size: 28rpx;
          margin-left: 16rpx;
        }
      }

      .address {
        font-size: 28rpx;
        color: #666666;
        line-height: 34rpx;
        margin-top: 10rpx;
      }
    }
  }
}

.goods-container {
  .item {
    padding: 20rpx 0;
    display: flex;
    align-items: center;
    background: #FFFFFF;
    border-bottom: 1px solid #eaeaea;
    image {
      width: 140rpx;
      height: 140rpx;
      display: block;
      margin-right: 20rpx;
      flex-shrink: 0;
    }
    .right {
      flex: 1;
      .name {
        font-size: 28rpx;
        color: #333333;
        line-height: 36rpx;
      }
      .des {
        font-size: 24rpx;
        color: #999999;
        margin-top: 8rpx;
      }
      .bottom {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 12rpx;
        .price {
          display: flex;
          flex-direction: column;
          font-size: 32rpx;
          color: $minor-color;
        }
      }
    }
  }
  .total {
    height: 80rpx;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    font-size: 28rpx;
    text {
      font-size: 32rpx;
      color: $minor-color;
      font-weight: 500;
      margin-left: 8rpx;
    }
  }
}

.row-container {
  .item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    min-height: 88rpx;
    border-bottom: 1px solid #eaeaea;
    &:last-child {
      border: none;
    }
    .title {
      font-size: 28rpx;
      color: #333333;
      text {
      	color: #999999;
      	margin-left: 20rpx;
      }
    }
    .right {
      font-size: 28rpx;
    }
    .radio-group {
      display: flex;
      height: 48rpx;
      align-items: center;

      .radio {
        display: flex;
        align-items: center;
        margin-left: 30rpx;
        font-size: 28rpx;

        .iconfont {
          font-size: 36rpx;
          color: #999999;
          margin-right: 10rpx;

          &.active {
            color: $theme-color;
          }
        }
      }
    }
  }
}

.bottom-container {
  padding: 20rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  .left {
    font-size: 28rpx;
    text {
      font-size: 32rpx;
      color: $minor-color;
      font-weight: 500;
      margin-left: 8rpx;
    }
  }

  .right {
    display: flex;
    ::v-deep .u-button {
      width: 170rpx;
      border-radius: 80rpx;
    }
  }
}
</style>
