<template>
  <view class="container">
    <uv-navbar title="确认订单" placeholder autoBack></uv-navbar>
    <view
      class="topStatus u-flex-center-sb"
      v-if="isAbleSelectSelfPickupBo.ablePickup"
    >
      <view
        class="top-item"
        :class="status == 0 ? 'active-right' : ''"
        @click.stop="changeStatus(0)"
      >
        <image
          v-if="status == 0"
          class="item-icon"
          :src="$handleImageUrl('/home/icon_left.png')"
          mode=""
        >
        </image>
        <view class="item-text u-1A1A1A u-font30 mr-15">快递配送</view>
      </view>
      <view
        class="top-item"
        :class="status == 10 ? 'active-left' : ''"
        @click.stop="changeStatus(10)"
      >
        <image
          v-if="status == 10"
          class="item-icon"
          :src="$handleImageUrl('/home/icon_right.png')"
          mode=""
        >
        </image>
        <view class="item-text u-1A1A1A u-font30">上门自提</view>
      </view>
    </view>

    <view
      class="carbox"
      :class="isAbleSelectSelfPickupBo.ablePickup ? 'changeTabtwo' : ''"
    >
      <view class="addressBox">
        <view class="" v-if="status == 0">
          <ldAddress
            :value="sureDataAll.shopOrderAddress"
            :link="true"
          ></ldAddress>
        </view>
        <view class="goHome u-p30" v-if="status == 10">
          <view class="u-flex-center">
            <view class="u-mr45 u-font28 u-999 u-flex-center">
              <text class="u-333 u-bold">提货人：</text>
              <input
                style="width: 150rpx"
                type="text"
                v-model="dataJson.selfPickupBo.receiverName"
                maxlength="8"
                placeholder="提货人姓名"
                placeholder-style="font-size:30rpx;"
              />
            </view>
            <view class="u-font28 u-999 u-flex-center">
              <text class="u-mr10 iconfont u-02331F u-font30">&#xe60d;</text>
              <input
                style="width: 260rpx"
                type="number"
                v-model="dataJson.selfPickupBo.receiverPhone"
                maxlength="11"
                placeholder="提货人手机号"
                placeholder-style="font-size:30rpx;"
              />
            </view>
          </view>
          <view class="u-font28 u-999 u-flex-center" style="margin-top: 20rpx">
            <view class="u-mr45 u-font28 u-999 u-flex-center z-flex-pick-up">
              <text class="u-333 u-bold z-pick-up">自提点：</text>
              <picker
                @change="confirmPickUp"
                range-key="pointName"
                :range="shopPickUpAddressList"
              >
                <text class="u-999 u-bold" style="min-width: 200rpx">{{
                  pickUpAdress || "请选择自提点地址"
                }}</text>
              </picker>
              <!-- <uv-select
                v-if="showPickUp"
                :list="shopPickUpAddressList"
                value-name="id"
                label-name="point_name"
                @confirm="confirmPickUp"
              ></uv-select> -->
            </view>
          </view>
          <view
            class="u-font28 u-999 u-flex-center"
            style="margin-top: 20rpx"
            v-if="pickUpAdressDetail"
          >
            <view class="u-mr45 u-font28 u-999 u-flex-center z-flex-pick-up">
              <text class="u-333 u-bold z-pick-up">详细地址：</text>
              <text class="u-999 u-bold address-box">{{
                pickUpAdressDetail
              }}</text>
            </view>
          </view>
        </view>
      </view>

      <view class="shopList u-mt10">
        <view class="listText u-bold">
          <view class="u-font28 u-181818">{{
            sureDataAll.businessName || ""
          }}</view>
        </view>
        <view v-for="(item, i) in sureDataAll.shopOrderDetailBoList" :key="i">
          <ld-goods :value="item" :exchange="dataJson.exchange"></ld-goods>
        </view>
      </view>

      <view
        class="listText u-border-one-one u-p30 u-flex-center-sb"
        v-if="sureDataAll.givePoint && sureDataAll.givePoint * 1 > 0"
      >
        <view class="u-font28 u-181818">下单送积分</view>
        <view class="u-font30 c-da4f4f">
          {{ sureDataAll.givePoint || 0 }}积分
        </view>
      </view>

      <view class="listText u-p30">
        <view class="u-font28 u-181818 title">
          <span>购买备注</span>
          <span class="num"
            >{{ dataJson.buyerRemark ? dataJson.buyerRemark.length : 0 }} /
            80</span
          >
        </view>
        <textarea
          class="textarea u-mt10 u-font28 u-333"
          :auto-height="true"
          :maxlength="80"
          v-model="dataJson.buyerRemark"
          placeholder="选填，给商家留言"
        />
      </view>

      <view class="listText u-border-one-one u-p30 u-flex-center-sb">
        <view class="u-font28 u-181818"><text>运费</text></view>
        <view class="u-font30 c-da4f4f">
          {{
            sureDataAll.shippingFee && sureDataAll.shippingFee * 1 > 0
              ? "+¥" + (sureDataAll.shippingFee || 0) + "元"
              : "免运费"
          }}
        </view>
      </view>

      <view class="listText u-p30" v-if="!dataJson.exchange">
        <view class="u-flex-center-sb">
          <view class="u-font28 u-181818"><text>共减</text></view>
          <view class="u-font30 c-da4f4f">
            -¥{{ sureDataAll.totalCouponReduced || 0 }}
          </view>
        </view>
        <view
          class="u-border-one-one border"
          v-if="(sureDataAll.totalCouponReduced || 0) * 1"
        >
          <view
            class="u-flex-center-sb u-mt10 u-mb10"
            v-for="(item, i) in sureDataAll.shopOrderUseRecordBoList || []"
            :key="i"
          >
            <view class="u-font28 u-181818 u-flex1"
              ><text>{{ item.businessCouponName }}</text></view
            >
            <view
              class="u-flex-center-sb u-ml10"
              style="flex-shrink: 0"
              @click="useCoupon(item)"
            >
              <view class="u-font30 c-da4f4f">
                -¥{{ item.businessCouponFaceValue }}
              </view>
              <uv-icon
                name="arrow-right"
                :color="item.universal ? '#999999' : '#ffffff'"
                size="30rpx"
              ></uv-icon>
            </view>
          </view>
        </view>
      </view>

      <view
        class="listText u-border-one-one border u-p30 u-flex-center-sb"
        v-if="dataJson.exchange"
      >
        <view class="u-font28 u-181818"><text>需要积分</text></view>
        <view class="u-font30 c-da4f4f">
          {{ sureDataAll.paymentPoints || 0 }}积分
        </view>
      </view>
      <view class="listText u-border-one-one border u-p30" v-else>
        <view class="u-flex-center-sb">
          <view class="u-font28 u-181818"><text>积分抵扣</text></view>
          <view class="u-font30 c-da4f4f">
            <uv-switch
              v-model="usePlatformPoint"
              @change="changePlatformPoint()"
              active-color="#e93534"
            ></uv-switch>
          </view>
        </view>
        <view style="color: #808080; font-size: 24rpx"
          >共计{{ sureDataAll.paymentPoints || 0
          }}<text v-if="usePlatformPoint"
            >，可使用{{ sureDataAll.paymentPoints || 0 }}抵扣{{
              sureDataAll.pointReduced || 0
            }}元</text
          >
        </view>
      </view>
    </view>
    <!-- 底部 -->
    <view class="botfixed u-flex-center-sb">
      <view class="leftAll u-flex-center">
        <view class="u-flex-center">
          <text class="u-mr20 u-font24 u-666">共{{ totaltNum }}件</text>
          <text class="u-font28 u-333">合计：</text>
          <view class="u-FF0000 u-bold">
            <text v-if="dataJson.exchange"
              >{{ sureDataAll.paymentPoints || 0 }}积分</text
            >
            <rich-text
              v-else
              :nodes="$mUtil.priceBigSmall(sureDataAll.actualPayment)"
            ></rich-text>
          </view>
        </view>
      </view>
      <view class="rightP u-flex-center" @click="$throttle(submitOrder, 500)">
        <view class="u-btn-two btnWidth u-ml30">提交订单</view>
      </view>
    </view>

    <!-- 优惠券选择弹窗 -->
    <couponSelectPopup
      ref="couponSelectPopupRef"
      :list="couponList"
      @change="useCouponChange"
    />
  </view>
</template>

<script setup>
import { ref } from "vue";
import { onLoad, onShow } from "@dcloudio/uni-app";
import { shoporderBuild_Api, shoporderCreate_Api } from "@/api/order";
import {
  businessLogisticsConfigInfo,
  businessSelfPickupAddressList,
  selectUniversal_Api,
} from "@/api/index";

import $mConfig from "@/config/global.config.js";
const totaltNum = ref(0);
const loading = ref(false);
const status = ref(0);
const sureDataAll = ref({});
const dataJson = ref({});
const type = ref(null);
const usePlatformPoint = ref(true);
const shopPickUpAddressList = ref([]);
const pickUpAdress = ref("");
const pickUpAdressDetail = ref("");
const isAbleSelectSelfPickupBo = ref({});
const couponList = ref([]); // 优惠券列表
const couponSelectPopupRef = ref(null);

// 切换优惠
const useCoupon = (item) => {
  if (item.universal) {
    couponSelectPopupRef.value.open(item.myBusinessCouponId);
  }
};

// 切换优惠卷
const useCouponChange = (item) => {
  // console.log(item);
  dataJson.value.myCouponId = item.id;
  changePlatformPoint();
};

// 收货地址或自提切换
const changePlatformPoint = () => {
  let objs = {
    ...dataJson.value,
    userUsePoint: usePlatformPoint.value,
  };
  uni.setStorageSync("dataJson", objs);
  postData(objs);
};

let submitLoading = false;
const orderCreated = () => {
  if (submitLoading) return;
  submitLoading = true;
  uni.showLoading({
    title: "正在创建订单",
    mask: true,
  });
  shoporderCreate_Api({
    ...dataJson.value,
    userUsePoint: usePlatformPoint.value,
  })
    .then((res) => {
      submitLoading = false;
      uni.hideLoading();
      if (res && res.code == 200) {
        let target = res.data;
        if (target.paymentStatus == 10) {
          uni.showToast({
            title: "下单成功",
            icon: "success",
          });
          setTimeout(() => {
            uni.redirectTo({
              url: `/pages/order/mallOrder/orderList?orderType=0`,
            });
          }, 100);
          return false;
        } else {
          // console.log("支付时间：" + new Date(target.expiredTime).getTime());
          let expiredTime = new Date(target.expiredTime).getTime();
          uni.redirectTo({
            url:
              "/pages/order/pay?orderNo=" +
              target.orderNo +
              "&total_amount=" +
              target.actualPayment +
              "&expired_pay_time=" +
              expiredTime +
              "&orderId=" +
              target.orderId,
          });
        }
      }
    })
    .catch(() => {
      submitLoading = false;
      // uni.hideLoading();
      setTimeout(() => {
        uni.navigateBack();
      }, 500);
    });
};

const submitOrder = () => {
  if (status.value == 0) {
    //快速配送
    // dataJson.value.selfPickupBo = null;
    // console.log(dataJson.value);
    if (
      dataJson.value.addressBo.userAddressId == null &&
      !sureDataAll.value.addressBo.userAddressId
    ) {
      uni.$uv.toast("请填写收货地址");
      return false;
    }
  } else {
    //自提
    if (!dataJson.value.selfPickupBo.receiverName) {
      uni.$uv.toast("请填写提货人姓名");
      return false;
    }
    if (!dataJson.value.selfPickupBo.receiverPhone) {
      uni.$uv.toast("请填写提货人手机号");
      return false;
    }
    if (!dataJson.value.selfPickupBo.receiverPhone.match($mConfig.telRegex)) {
      uni.$uv.toast("请输入正确手机号");
      return false;
    }
    if (!dataJson.value.selfPickupBo.selfPickupId) {
      uni.$uv.toast("请选择自提点地址");
      return false;
    }
  }
  orderCreated();
};

// 获取可使用优惠卷列表
const getSelectUniversal_Api = (totalAmountDecShopCoupon) => {
  selectUniversal_Api({
    totalAmountDecShopCoupon,
    businessId: dataJson.value.businessId,
    marketingType: 0, // 活动字段0：无活动，5：秒杀， 10：拼团
  }).then((res) => {
    if (res.code == 200) {
      couponList.value = res.data || [];
    }
  });
};

// 构建订单
const postData = (dataJsons) => {
  if (dataJsons) {
    loading.value = true;
    shoporderBuild_Api(
      {
        ...dataJsons,
      },
      {
        hideToast: true,
      }
    )
      .then((res) => {
        if (res && res.code == 200) {
          getSelectUniversal_Api(res.data.totalProductAmount);
          try {
            loading.value = false;
            // uni.setStorageSync("sureData", res.data);
            if (res.data) {
              sureDataAll.value = res.data;
              totaltNum.value = res.data.productNumber;
            }
            dataJson.value.addressBo = res.data.shopOrderAddress || {};
            usePlatformPoint.value = res.data.userUsePoint;
          } catch (error) {
            console.log(error);
          }
        }
      })
      .catch(() => {
        // uni.hideLoading();
        setTimeout(function () {
          uni.navigateBack();
        }, 1500);
      });
  }
};

// 切换取货方式
const changeStatus = (val) => {
  if (val == 10 && !shopPickUpAddressList.value.length) {
    uni.$uv.toast("暂无自提点，请联系商家");
    return;
  }
  dataJson.value.shippingMethod = val;
  status.value = val;
  pickUpAdress.value = "";
  pickUpAdressDetail.value = "";
  postData(dataJson.value);
};

// 自提点选择触发
const confirmPickUp = (e) => {
  // console.log(e.detail.value);
  if (!shopPickUpAddressList.value.length) {
    uni.$uv.toast("暂无自提点，请联系商家");
    return;
  }
  const objs = shopPickUpAddressList.value[e.detail.value];
  pickUpAdress.value = objs.pointName;
  pickUpAdressDetail.value = objs.address;
  dataJson.value.selfPickupBo.selfPickupId = objs.id;
};

// 获取自提点
const getPickUpList = () => {
  businessSelfPickupAddressList(dataJson.value.businessId).then((res) => {
    if (res && res.code == 200) {
      shopPickUpAddressList.value = res.data || [];
    }
  });
};
// 获取商家物流配置信息
const getBusinessLogisticsConfigInfo = () => {
  businessLogisticsConfigInfo(dataJson.value.businessId).then((res) => {
    if (res && res.code == 200) {
      console.log(res.data);
      isAbleSelectSelfPickupBo.value = res.data || {};
      if (isAbleSelectSelfPickupBo.value.ablePickup) {
        dataJson.value.selfPickupBo = {};
        getPickUpList();
      }
    }
  });
};

onLoad((options) => {
  loading.value = true;
  let dataJson1 = uni.getStorageSync("dataJson");
  console.log(dataJson1);
  if (dataJson1) {
    dataJson.value = dataJson1;
  }
  if (options.type) {
    type.value = options.type;
  }
  if (dataJson.value.businessId) getBusinessLogisticsConfigInfo();
});

onShow(() => {
  let orderreminder = uni.getStorageSync("orderreminder");
  if (orderreminder) {
    uni.$uv.toast("已生成待付款订单");
    uni.removeStorageSync("orderreminder");
  }
  let dataJson = uni.getStorageSync("dataJson");
  postData(dataJson);
});
</script>

<style lang="scss" scoped>
:deep(.input-placeholder) {
  font-size: 26rpx;
}
</style>
<style lang="scss">
page {
  background-color: #f5f5f5;
  box-sizing: border-box;
}
.c-da4f4f {
  color: #da4f4f;
}
.border {
  border-bottom: 3rpx solid #e7e7e7;
}

.textarea {
  width: 100%;
  height: 80rpx;
  background-color: #fafafa;
  padding: 22rpx 20rpx;
  box-sizing: border-box;
  border: 1px solid #ededed;
  border-radius: 20rpx;
}

.topStatus {
  height: 100rpx;
  background-color: #fdeee9;
  position: fixed;
  z-index: 9;

  width: 100%;
  box-sizing: border-box;

  .item-text {
    line-height: 100rpx;
    position: relative;
    z-index: 2;
    text-align: center;
    border-radius: 30rpx 30rpx 0 0;
    color: #010101;
  }
  .top-item {
    position: relative;
    flex: 1;
    box-sizing: border-box;
    height: 100rpx;
    .item-icon {
      width: 420rpx;
      height: 114rpx;
      position: absolute;
      top: -4rpx;
      left: 0;
      z-index: 1;
    }
  }
  .top-item.active-right,
  .top-item.active-left {
    font-weight: bold;
    width: 420rpx;
    flex-shrink: 0;
  }
  .active-left {
    padding-left: 64rpx;
  }
  .active-right {
    padding-right: 64rpx;
  }
}

.courierAddress {
  background-color: #fff;
  padding: 36rpx 30rpx;
}

.goHome,
.listText {
  background-color: #fff;

  .title {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .num {
      color: #808080;
      font-size: 26rpx;
    }
  }

  .freight {
    padding: 30rpx;

    .u-border-one-one {
      padding: 30rpx 0;
    }
  }

  .consumption_value-icon {
    font-size: 60rpx;
    color: #ff9651;
  }

  .consumption_value span {
    color: #ff6600;
  }
}

.btnview {
  width: 300rpx;
  margin: 30rpx auto 0;
}

.shopList {
  background-color: #fff;
  padding: 30rpx 30rpx 0;

  &:deep(.textWidth) {
    $font-size: 28rpx; // scss 变量
    height: $font-size * 1.5 * 2; // 计算出两行文本的高度
    line-height: 1.5;
    font-size: $font-size;
  }
}

.changeTabtwo {
  padding: 130rpx 0 160rpx 0;
}

.rightText {
  justify-content: space-between;
  // height: 200rpx;
}

.bottext,
.botPrice {
  width: 100%;
  box-sizing: border-box;
}

.bottext {
  margin-top: 36rpx;
}

.rightAddRes {
  width: 172rpx;
  height: 50rpx;
  border-radius: 8rpx;
  border: 1px solid #e5e5e5;

  .centertext {
    text-align: center;
  }

  .btnTag {
    width: 50rpx;
    height: 50rpx;
    line-height: 50rpx;
    text-align: center;
    background-color: #dedede;
    font-size: 46rpx;
    color: #888;
  }
}

.btnWidth {
  width: 340rpx;
  background: #e93534;
}

.botfixed {
  position: fixed;
  background-color: #fff;
  width: 100%;
  height: 138rpx;
  bottom: 0;
  left: 0;
  z-index: 9;
  padding: 0 30rpx;
  box-sizing: border-box;
}

.z-flex-pick-up {
  align-items: start;

  .z-pick-up {
    flex-shrink: 0;
  }

  .address-box {
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 3;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}
</style>
