<template>
  <view class="wrap">
    <view></view>
    <view
      class="addAddress"
      @tap="toaddAddress"
      v-if="this.showAddress"
    >
      <view class="addIcon">
        <image
          src="../../static/add.png"
          mode="aspectFill"
        ></image>
      </view>
      <view class="addressText">{{addAddress}}</view>
      <image
        src="../../static/right.png"
        mode="aspectFill"
      ></image>
    </view>
    <view
      v-else
      @tap="toaddAddress"
      :class="addressInfo !== false ? 'list order-user' : 'list order-user user_address'"
    >
      <view
        class="order-user-head"
        v-if="addressInfo != false"
      >
        <view class="name">
          <view
            v-if="addressInfo.default === '1'"
            class="default"
          >
            <text>默认</text>
          </view>
          {{addressInfo.name}}
        </view>
        <text class="mobile">{{addressInfo.mobile}}</text>
      </view>
      <view
        class="order-user-body"
        v-if="addressInfo !== false"
      >
        <image src="../../static/myorder-paying-location.png"></image>
        <text class="address">{{addressInfo.address}}\n{{addressInfo.add_detail}}</text>
      </view>
      <view
        class="order_user_body_add"
        v-if="addressInfo == false"
      >
        <image
          src="../../static/add_address.png"
          mode="aspectFill"
        ></image>
        <text class="address_add">点击添加地址</text>
      </view>
      <image
        class="arrow"
        src="../../static/right.png"
        mode="aspectFill"
      ></image>
    </view>
    <view class="content">
      <view class="orderInfo">
        <view class="title">
          <image
            src="../../static/store.png"
            mode="aspectFill"
            style="width: 40rpx;height: 40rpx;"
          ></image>
          <text>非常戴镜</text>
        </view>
        <template v-if="isCart === 'true'">
          <view
            class="infoBox"
            v-for="(item, index) in checkedCartLst"
            :key="index"
          >
            <view class="infoTop">
              <image
                :src="item.img_index_url"
                mode="aspectFill"
              ></image>
              <view class="infoRight">
                <text class="goodName">{{item.p_name}}</text>
                <text class="remarks">支持7天无理由退货 顺丰发货</text>
                <view class="priceBox">
                  <view class="price">¥{{Number(item.nowPrice) }}<text class="originCost">
                      ¥{{item.oldPrice}}
                    </text></view>
                  <view class="counter">
                    <view
                      class="btn"
                      disabled="this.disabled"
                      type="default"
                      @click="counter(false,index)"
                    >-</view>
                    <text>{{checkedCartLst[index].num}}</text>
                    <view
                      class="btn"
                      type="default"
                      @click="counter(true,index)"
                    >+</view>
                  </view>
                </view>
              </view>
            </view>
            <view class="infoBottom">
              <view class="norm">规格 <text>
                  <!-- 长度超出变省略号未做 -->
                  <block>{{item.sku_name}}<block v-if="index !== current.length -1">/</block>
                  </block>
                </text></view>
              <view class="shippingMethod">使用人 <text>
                  {{item.peopleName}}
                </text></view>
              <view class="shippingMethod">配送方式 <text>快递</text></view>
              <view class="message">买家留言
                <input
                  type="text"
                  :value="note"
                  placeholder="建议提前协商(50字以内)"
                />
              </view>
            </view>
          </view>
        </template>
        <template v-else>
          <view class="infoBox">
            <view class="infoTop">
              <image
                :src="buyItem.pic"
                mode="aspectFill"
              ></image>
              <view class="infoRight">
                <text class="goodName">{{goodInfo.p_name}}</text>
                <text class="remarks">支持7天无理由退货 顺丰发货</text>
                <view class="priceBox">
                  <view class="price">¥{{buyItem.real_price}}<text class="originCost">
                      ¥{{buyItem.out_price}}
                    </text></view>
                  <view class="counter">
                    <view
                      class="btn"
                      disabled="this.disabled"
                      type="default"
                      @click="counter(false)"
                    >-</view>
                    <text>{{count}}</text>
                    <view
                      class="btn"
                      type="default"
                      @click="counter(true)"
                    >+</view>
                  </view>
                </view>
              </view>
            </view>
            <view class="infoBottom">
              <view class="norm">规格 <text>
                  <!-- 长度超出变省略号未做 -->
                  <block
                    v-for="(item, index) in current"
                    :key="index"
                  >{{attrList[index].attr[item].name}}<block v-if="index !== current.length -1">/</block>
                  </block>
                </text></view>
              <view class="shippingMethod">使用人 <text>
                  {{name}}
                </text></view>
              <view class="shippingMethod">配送方式 <text>快递</text></view>
              <view class="message">买家留言
                <input
                  type="text"
                  :value="note"
                  placeholder="建议提前协商(50字以内)"
                />
              </view>
            </view>
          </view>
        </template>

      </view>
      <view class="payWay">
        <view class="item">
          <text>支付方式</text>
          <view class="itemRight">
            <view class="rightText">
              <view class="choosePayWay">
                <image
                  src="../../static/chat_logo.png"
                  mode="aspectFill"
                ></image>
                <text>微信支付</text>
              </view>
              <!-- <view class="randomSubstraction">最高随机立减¥99</view> -->
            </view>
            <!-- <image
              src="../../static/right.png"
              mode="aspectFill"
            ></image> -->
          </view>
        </view>
        <!-- <view class="item">
          <text>优惠券</text>
          <view class="itemRight">
            <view class="rightText">
              <view class="chooseOffers">
                <text>-¥70.00</text>
              </view>
              <view class="preferentialWay">最大优惠</view>
            </view>
            <image
              src="../../static/right.png"
              mode="aspectFill"
            ></image>
          </view>
        </view> -->
        <view class="item">
          <text>运费</text>
          <view class="itemRight">
            <view class="freight">免运费</view>
          </view>
        </view>
        <view class="item">
          <text>合计</text>
          <view class="itemRight">
            <view class="total">¥{{totalPrice}}</view>
            <!-- <view class="total" v-else>¥{{Number(skuInfo.real_price) * count}}</view> -->
          </view>
        </view>
      </view>
      <!--
      <view class="checkBox">
        <checkbox-group>
          <label>
            <checkbox color="#FF6B4A" value="isAnonymous" checked="true" />匿名购买
          </label>
        </checkbox-group>
      </view> -->
    </view>
    <view class="last_zhanwei"></view>
    <view class="footer">
      <view class="footerLeft">实付金额:
        <text>¥{{totalPrice}}</text>
        <!-- <text v-else>¥{{Number(skuInfo.real_price) * count}}</text> -->
      </view>
      <view class="footerRight">
        <view
          class="paybtn"
          @tap="orderBuild"
        >立即支付</view>
      </view>
    </view>
  </view>
</template>

<script>
import store from '@/store'
import MD5Util from '../../utils/md5'

export default {
  data() {
    return {
      name: String,
      addAddress: '添加收货地址',
      count: 1,
      pid: 0,
      disabled: false,
      freight: 0.0,
      showAddress: false,
      note: '',
      addressInfo: {
        address: '',
      },
      isCart: Boolean,
      // isAnonymous:
      checkedCartLst: [],
    }
  },
  onShow(addressId) {
    // console.log('+-+-*-*-+-+',addressId)
    if (addressId) {
      store
        .dispatch('address/details', {
          add_id: addressId,
        })
        .then(({ code, data }) => {
          if (code === 1) {
          // console.log('code', code, data)
            this.showAddress = true
            this.addressInfo = data
          }
        })
    }
  },
  onLoad({ pid, addressId, isCart, count, name }) {
    if (isCart === 'false') {
      this.pid = pid
    //   store.dispatch('read/fetch', {
      // pid,
    //   })
    }
    this.count = count
    this.name = name
    this.isCart = isCart

    console.log('++++++++++++' + pid, addressId, isCart)
    this.checkedCartLst = this.$store.state.cart.checkedCartLst
    // console.log('++++++++++6666666666++',this.$store.state.cart.checkedCartLst)
    // 若已经选择地址
    if (addressId) {
      store
        .dispatch('address/details', {
          add_id: addressId,
        })
        .then(({ code, data }) => {
          if (code === 1) {
            // console.log('code', code, data)
            this.showAddress = true
            this.addressInfo = data
          }
        })
    } else {
      store.dispatch('address/default').then(({ code, data }) => {
        this.showAddress = true
        this.addressInfo = data
        console.log('this.addressInfo', this.addressInfo)
      })
    }
  },
  computed: {
    totalPrice() {
      if (this.isCart == 'true') {
        let total = 0
        this.$store.state.cart.checkedCartLst.map(item => {
          total += item.nowPrice * item.num
        })
        return total
      } else {
        return this.buyItem.real_price * this.count
      }
    },
    buyItem() {
      return this.$store.state.cart.buyItem
    },
    // checkedCartLst(){
    //  console.log('checkedCartLst',this.$store.state.cart.checkedCartLst)
    //  return this.$store.state.cart.checkedCartLst
    // },
    goodInfo() {
      // console.log('state', this.$store.state.read.goodInfo)
      return this.$store.state.read.goodInfo
    },
    skuInfo() {
      return this.$store.state.order.param.sk_id_arr
    },
    attrList() {
      return this.$store.state.order.param.attrList
    },
    current() {
      return this.$store.state.order.param.current
    },
  },
  methods: {
    counter(isadd, index) {
      if (isadd) {
        if (this.isCart == 'true') {
          this.checkedCartLst[index].num++
        } else {
          this.count++
        }
      } else {
        if (this.isCart == 'true') {
          this.checkedCartLst[index].num <= 1 ? (this.disabled = true) : this.checkedCartLst[index].num--
        } else {
          this.count <= 1 ? (this.disabled = true) : this.count--
        }
      }
    },
    // 跳转添加地址页面
    toaddAddress() {
      uni.navigateTo({
        url: `../address/addressList?edit=${1}`,
        success: res => {},
        fail: error => {
          console.log('跳转到地址列表页面失败====>', error)
        },
        complete: () => {},
      })
    },
    // 下单
    orderBuild() {
      if (!this.addressInfo) {
        uni.showToast({
          title: '请先添加地址',
          icon: 'none',
        })
        return
      }
      uni.showLoading({
        title: '支付中',
      })
      if (this.isCart === 'true') {
        const checkedGoods = []
        const sk_id_arr = []
        this.checkedCartLst.map(item => {
          checkedGoods.push(item.cart_id)
          sk_id_arr.push(item.sk_id)
        })
        store.dispatch('order/build', {
          uid: this.$store.state.user.userInfo.uid,
          address: JSON.stringify(this.addressInfo),
          checkedGoods: checkedGoods,
          sk_id_arr: sk_id_arr,
          totalPrice: this.totalPrice * 100,
        }).then((res) => {
          this.pay(res)
        })
      }
      if (this.isCart === 'false') {
        const { sk_id_arr: skId, mp_id: mpId } = this.$store.state.order.param
        store.dispatch('order/buyNow', {
          pid: skId.pid,
          sk_id: skId.sk_id,
          number: this.count,
          mp_id: mpId,
          address: JSON.stringify(this.addressInfo),
          totalPrice: this.totalPrice * 100,
          liuyan: this.note,
          dir: 1,
        }).then((res) => {
          this.pay(res)
        })
      }
    },
    // 支付
    pay(res) {
      console.log('pay', res)
      const { data, exKeyName: keyName } = res
      const uid = uni.getStorageSync('uid')
      const timeStamp = new Date().getTime().toString()
      const nonceStr = 'asfafasfasfasfasf'
      // 支付参数
      const fieldSet = {
        openid: this.$store.state.user.userInfo.openid,
        uid: this.$store.state.user.userInfo.uid,
        shopid: 0,
        payCate: 2020,
        payMoney: this.totalPrice * 100,
        payWoodId: `fcdj-${uid}-${keyName}`,
        payWoodDesc: '在【非常戴镜】的微信付款凭证',
        nonceStr,
        signType: 'MD5',
        app_uid: 2020,
        timeStamp,
        keyname: keyName,
        billInfo: JSON.stringify({
          address: this.addressInfo,
          list: data,
          keyname: keyName,
        }),
      }
      console.log('fieldSet', fieldSet)
      // 请求后台支付接口
      store.dispatch('order/pay', fieldSet).then(({ data, data2, pay_id: payId }) => {
        if (data.return_code === 'SUCCESS' && data.result_code === 'SUCCESS') {
          const stringA = `appId=wx115b25aa396d27ac&nonceStr=${nonceStr}&package=prepay_id=${data.prepay_id}&signType=MD5&timeStamp=${timeStamp}`
          const stringSignTemp = stringA + '&key=NewMoney2017hatemydaddy123456789'

          // 微信支付接口
          uni.requestPayment({
            appId: data.appid,
            timeStamp,
            nonceStr,
            total_fee: this.totalPrice,
            package: `prepay_id=${data.prepay_id}`,
            signType: 'MD5',
            paySign: MD5Util.MD5(stringSignTemp).toUpperCase(),
            success: (res) => {
              // 支付成功
              uni.showModal({
                content: '支付成功',
                showCancel: false,
              })
              // 跳转订单详情页->状态 待收货
              uni.reLaunch({
                url: `../myOrderPaying/myOrderPaying?payId=${payId}&status=1&isPay=1`,
              })
            },
            fail: (res) => {
              // 支付失败
              uni.showModal({
                content: '支付失败',
                showCancel: false,
              })
              // 跳转订单详情页->状态 待付款
              uni.reLaunch({
                url: `../myOrderPaying/myOrderPaying?payId=${payId}&status=0&isPay=1`,
              })
            },
            complete: () => {
              uni.hideLoading()
            },
          })
        } else {
          uni.showModal({
            content: '支付失败',
            showCancel: false,
          })
          console.log('支付失败')
          uni.hideLoading()
        }
      })
    },
  },
}
</script>

<style lang="scss">
.wrap {
  height: 100vh;
  background-color: #f2f2f2;
  font-family: PingFangSC-Regular;
  letter-spacing: -0.23px;
  position: absolute;
}
.addAddress {
  background-color: #ffffff;
  box-sizing: border-box;
  height: 124rpx;
  width: 100%;
  display: flex;
  align-items: center;
  padding: 0 40rpx;
  .addIcon {
    background-color: #f2f2f2;
    height: 56rpx;
    width: 60rpx;
    border-radius: 4rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-right: 40rpx;
  }
  image {
    height: 28rpx;
    width: 30rpx;
  }
  .addressText {
    font-size: 28rpx;
    color: #333333;
    margin-right: 364rpx;
  }
}
.content {
  background-color: #f2f2f2;
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 40rpx;
  box-sizing: border-box;
  .orderInfo {
    width: 670rpx;
    min-height: 488rpx;
    background-color: #ffffff;
    border-radius: 20rpx;
    box-sizing: border-box;
    padding: 0 40rpx 40rpx 40rpx;
    .title {
      display: flex;
      align-items: center;
      font-size: 28rpx;
      color: #333333;
      height: 60rpx;
      line-height: 40rpx;
      padding: 10rpx 10rpx 10rpx 0rpx;
      image {
        margin-right: 20rpx;
      }
    }
    .infoBox {
      margin-top: 42rpx;
      .infoTop {
        display: flex;
        flex-direction: row;
        image {
          height: 188rpx;
          width: 188rpx;
          margin-right: 24rpx;
        }
        .infoRight {
          width: 374rpx;
          display: flex;
          flex-direction: column;
          align-items: flex-start;
          justify-content: space-between;
          .goodName {
            font-size: 28rpx;
            color: #333333;
          }
          .remarks {
            font-size: 20rpx;
            color: #999999;
          }
          .priceBox {
            display: flex;
            justify-content: space-between;
            align-items: center;
            width: 100%;
            .price {
              color: #ff6b4a;
              font-size: 28rpx;
              text {
                margin-left: 10rpx;
              }
            }
            .originCost {
              text-decoration: line-through;
              color: #999999;
              font-size: 20rpx;
            }
            .counter {
              display: flex;
              flex-direction: row;
              justify-content: space-between;
              font-size: 28rpx;
              color: #333333;
              width: 122rpx;
              .btn {
                display: flex;
                justify-content: center;
                line-height: 32rpx;
                height: 32rpx;
                width: 32rpx;
                background-color: #f2f2f2;
                color: #cfcfcf;
              }
            }
          }
        }
      }
      .infoBottom {
        display: flex;
        flex-direction: column;
        justify-content: flex-start;
        font-size: 24rpx;
        color: #333333;
        text {
          color: #999999;
          margin-left: 20rpx;
        }

        .norm {
          margin-top: 28rpx;
        }
        .shippingMethod {
          margin-top: 12rpx;
        }
        .message {
          display: flex;
          flex-direction: row;
          align-items: center;
          margin-top: 18rpx;
          input {
            margin-left: 20rpx;
            width: 75%;
          }
        }
      }
    }
  }
  .payWay {
    height: 464rpx;
    width: 670rpx;
    background-color: #ffffff;
    color: #333333;
    font-size: 24rpx;
    border-radius: 20rpx;
    box-sizing: border-box;
    padding: 0 52rpx 0rpx 40rpx;
    margin-top: 20rpx;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: flex-start;
    .item {
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      align-items: center;
      width: 100%;
      height: 115rpx;
      .itemRight {
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;
        image {
          height: 24rpx;
          width: 12rpx;
        }
        .rightText {
          margin-right: 20rpx;
          text-align: right;
          .choosePayWay {
            display: flex;
            align-items: center;
            text {
              color: #333333;
            }
            image {
              height: 36rpx;
              width: 40rpx;
              margin-right: 8px;
            }
          }
          .randomSubstraction {
            color: #ff6b4a;
          }
          .preferentialWay {
            color: #999999;
          }
        }
        .freight,
        .total {
          margin-right: 32rpx;
        }
        text {
          color: #ff6b4a;
        }
      }
    }
  }
  // .checkBox {
  //   height: 58rpx;
  //   line-height: 58rpx;
  //   width: 100%;
  //   margin-top: 36rpx;
  //   margin-left: 40rpx;
  //   font-size: 12px;
  //   color: #999999;
  // }
}
.footer {
  height: 112rpx;
  width: 100%;
  background-color: #fff;
  font-size: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: fixed;
  bottom: 0;
  z-index: 9999;
  .footerLeft {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 50%;
    color: #333333;
    text {
      color: #ff6b4a;
    }
  }
  .footerRight {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    width: 50%;
    margin-right: 26rpx;
    .paybtn {
      display: flex;
      justify-content: center;
      align-items: center;
      background: #ff6b4a;
      border-radius: 20px;
      border-radius: 20px;
      color: #ffffff;
      width: 204rpx;
      height: 80rpx;
    }
  }
}
// 地址信息样式
.order-user {
  width: 670rpx;
  height: 228rpx;
  background: #ffffff;
  border-radius: 14rpx;
  margin: 0 auto;
  margin-top: 20rpx;
  position: relative;
  .order-user-head {
    display: flex;
    height: 108rpx;
    width: 100%;
    align-items: center;
    padding-left: 126rpx;
    box-sizing: border-box;
    .name {
      display: flex;
      justify-content: space-between;
      font-size: 14px;
      color: #333333;
      letter-spacing: -0.26px;
      margin-right: 20rpx;
      .default {
        height: 40rpx;
        width: 80rpx;
        background-color: #4a90e2;
        border-radius: 13px;
        border-radius: 13px;
        text-align: center;
        margin-right: 20rpx;
        text {
          display: flex;
          justify-content: center;
          align-items: center;
          font-size: 12px;
          color: #ffffff;
          letter-spacing: -0.23px;
        }
      }
    }
    .mobile {
      font-size: 14px;
      color: #999999;
      letter-spacing: -0.26px;
    }
  }
  .order-user-body {
    display: flex;
    width: 100%;
    image {
      width: 24px;
      height: 28px;
      margin: 12rpx 32rpx 0 40rpx;
    }
    .address {
      font-weight: bold;
      font-size: 14px;
      color: #333333;
      letter-spacing: -0.26px;
    }
  }

  .arrow {
    width: 12px;
    height: 12px;
    position: absolute;
    right: 40rpx;
    bottom: 104rpx;
  }
}

.user_address {
  height: 62px;
  .order_user_body_add {
    display: flex;
    align-items: center;
    image {
      background: #f2f2f2;
      border-radius: 2px;
      border-radius: 2px;
      width: 30px;
      height: 28px;
      margin: 0 20px;
    }
    .address_add {
      font-family: PingFangSC-Regular;
      font-size: 14px;
      color: #333333;
      letter-spacing: -0.26px;
      line-height: 62px;
    }
  }
  .arrow {
    bottom: 46rpx;
  }
}
.last_zhanwei {
  background: #f2f2f2;
  height: 60px;
}
</style>