<template>
  <view class="create-order">
    <view class="top-wrapper">
      <!-- 地址 -->
      <address-display
        :waybillAddress="defaultAddress"
        :storeAddress="storeAddress"
        :onlyShow="form.isSelf?true:false"
      ></address-display>
      <view class="pd-wrapper">
        <!-- 配送时间选择 -->
        <view
          class="date-time"
          @click="openTimePick"
          v-if="!isMaterial"
        >
          <left-right-cell >
            <template v-slot:left>
              <view>{{!form.isSelf?'指定时间':'预计取货时间'  }}</view>
            </template>
            <template v-slot:right>
              <view v-show="form.deliveryTime.date">{{form.deliveryTime.viewTime==='立即送出' && form.isSelf?form.deliveryTime.date + ' ' + '立即自取':form.deliveryTime.date + ' ' + form.deliveryTime.viewTime}}</view>
            </template>
          </left-right-cell>
        </view>
        <!-- 是否自提 -->
        <view class="isSelfBox">
          <view  class="is-self" v-if="!isMaterial">
            <!-- <ZySwitch v-model="form.isSelf" @on-change="onChange" size="50" class="isSelf-switch"></ZySwitch> -->

            <!-- #ifdef MP-TOUTIAO -->
            <!-- :disabled="true" -->
            <!-- <switch :checked="form.isSelf" color="#4EB331"  @change="onChange" class="isSelf-switch" /> -->
            <!-- #endif -->

            <!-- #ifndef MP-TOUTIAO -->
            
            <!-- #endif -->
            <switch :checked="form.isSelf" color="#4EB331" @change="onChange" class="isSelf-switch" :style="isSelfSwitch"/>
          </view>
        </view>
       
        <!-- 商品列表 -->
        <!-- :class="form.isSelf?'active-self':''" style="margin-top:120rpx"-->
        <view class="list">
          <goods-group
            v-for="(val, key) in groupList"
            :key="key"
            :storeID="key"
            :skuList="val"
            :storeName="storeID[0] === 666666 ? '物料店' : '' "
          ></goods-group>
        </view>
        <!-- 费用 -->
        <view class="other-price">
          <left-right-cell noClick>
            <template v-slot:left>
              <view>商品总价</view>
            </template>
            <template v-slot:right>
              <view v-if="preCreateData.orderPrice">￥{{$filters.toFixed2(preCreateData.orderPrice)}}</view>
              <view v-else>￥{{$filters.toFixed2((totalPay || 0))}}</view>
            </template>
          </left-right-cell>
          <left-right-cell noClick>
            <template v-slot:left>
              <view >总重量</view>
            </template>
            <template v-slot:right>
              <view >{{totalWeight}}</view>
          </template>
          </left-right-cell>
          <left-right-cell noClick>
            <template v-slot:left>
                <view >配送费</view>
              </template>
              <template v-slot:right>
                <view>￥{{$filters.toFixed2((preCreateData.freightPrice || 0))}}</view>
            </template>
          </left-right-cell>
        </view>
        <!-- 
                <template v-slot:left>

</template>
<template v-slot:right>

</template>
        -->

        <!-- 费用 -->
        <!-- 可用积分 -->
        <!-- 备注 -->
        <div class="btn-comment" @click="goComment" >
          <left-right-cell>
            <template v-slot:left>
              <view>备注</view>
            </template>
            <template v-slot:right>
              <view class="comment">{{form.note || '可输入备注要求'}}</view>
            </template>
          </left-right-cell>
        </div>
        <!-- #ifdef MP-KUAISHOU -->
        <!-- <payment-list @change="handlePaymentSelect" @error="handleError" style="margin-top:10px;"/> -->
        <!-- #endif -->
      </view>
    </view>
    <!-- 合计 -->
    <div class="total-pay">
      <left-right-cell noClick>
        <template v-slot:left>
          <div class="order-totalPay">
            <span class="order-num">共{{validCarList.length}}件</span>
            <span >合计:</span>
            <good-price :price="preCreateData.actualPayPrice?preCreateData.actualPayPrice:totalPay"></good-price>
            <span class="order-freight" v-if="preCreateData.freightPrice!==0">（含运费￥{{$filters.toFixed2((preCreateData.freightPrice || 0))}}元）</span>
          </div>
        </template>
        <template v-slot:right>
          <div class="comment">
            <div class="btn-pay" style="font-size: 26rpx;opacity:0.5" v-if="!inRange && defaultAddress && defaultAddress.length>0 && defaultAddress[0].id" >不在配送范围内</div>
            <div class="btn-pay" @click="handlePay" v-else  
              :style="{'opacity': form.isSelf ? 1 : (defaultAddress && defaultAddress.length>0 && defaultAddress[0].id ? 1:0.5 )}">
              去支付</div>
          </div>
        </template>
      </left-right-cell>
    </div>
    <!-- 弹出时间选择 -->
    <PopTab
      v-if="timePickShow"
      :list="deliverTimeList"
      :props="{
        title: 'date',
        list: 'timeList'
      }"
      :isSelf="form.isSelf"
      :currentValue="form.deliveryTime.unixTime"
      @on-close="handleClose"
    ></PopTab>
    <!-- loading -->
    <zy-loading></zy-loading>
  </view>
</template>

<script>
import ZyLoading from "@/components/Loading/loading";
import { mapGetters, mapActions, mapMutations, Store } from "vuex";
import AddressDisplay from "./address-display/address-display.vue";
import LeftRightCell from "@/components/layout/left-right-cell.vue";
import GoodsGroup from "../orderCmp/goods-group/goods-group.vue";
import { errToast, alert, toast,modal,openWeixinMiniprogram,jumpPage,queryEleInfo } from "@/utils/uniapi.js";
import PopTab from "../popTab/popTab.vue";
import GoodPrice from '@/components/goodCmp/good-price/good-price';
// import {store} from "@/store";
import { groupByStore } from '@/utils'
import { handleCreatePay } from '@/utils/uniapi.js'


import orderPage from '@/apis/orderPage'
import apiStore from '@/apis/apiStore'

const debug = false;
export default {
  components: {
    ZyLoading,
    AddressDisplay,
    LeftRightCell,
    GoodsGroup,
    PopTab,
    // ZySwitch,
    GoodPrice
  },
  data() {
    return {
      form: {
        address: {},
        deliveryTime: {
          unixTime: 0,
        },
        isSelf: true,   // 默认自提
        note: "",
      },
      // price: {
      //   totalPrice: 0, // 订单总价
      //   freightPrice: 0, // 配送费
      //   orderPrice: 0, // 订单商品价格
      //   actualPayPrice: 0 // 顾客实际支付
      // },
      groupList: {},
      deliverTimeList: [],
      timePickShow: false,
      preCreateData: {},
      weight: 0,
      storeAddress: {},
      inRange: false,
      payment: {
          provider: '',
          provider_channel_type: '',
      },
      isSelfSwitch:'transform:scale(1);margin-right: 20px;'
    }
  },
  computed: {
    ...mapGetters({
      defaultAddress: "addressVue/defaultAddress",
      addressList: "addressVue/addressList",
      storeID: "indexPage/storeID",
      isMaterial: "indexPage/isMaterial",
      isPurchase: "indexPage/isPurchase",
      waybillSLG: "indexPage/waybillSLG",
      storeMap: "indexPage/storeMap",
      myLocation: "indexPage/myLocation",
      fromStoreID: "indexPage/fromStoreID",
      validCarList: "cartPage/validCarList",
      totalWeight: "cartPage/totalWeight",
      buyerNote: "cartPage/buyerNote",
      selfInfo: "login/selfInfo",
      iosOrAndroid: "iosOrAndroid"
    }),
    totalPay() {
      let list = this.validCarList;
      // console.log(list);
      let total = 0;
      list.forEach((item) => {
        total += item.curPrice;
      });
      return total;
    }
  },
  watch: {
    // defaultAddress(val, oldVal) {
    //   // #ifdef MP-KUAISHOU || MP-ALIPAY
    //   if (oldVal && oldVal.length > 0) {
    //     if (val && val.length > 0 && val[0].id && oldVal[0].id !== val[0].id) {
    //       this.isInRange(this.storeID[0], val[0].id)
    //     }
    //   } else {
    //     if (val && val.length > 0 && val[0].id) {
    //       this.isInRange(this.storeID[0],val[0].id)
    //     }
    //   }
    //   // #endif

    //   // #ifndef MP-KUAISHOU || MP-ALIPAY
    //   if (val && val.length > 0 && val[0].id) {
    //     this.isInRange(this.storeID[0],val[0].id)
    //   }
    //   // #endif
      
    // },
  },
  onShow() {
    // let pages = getCurrentPages()
    // let curPage = pages[pages.length - 1]
    // console.log(curPage.data.note)
    // if (curPage.data.note) this.form.note = curPage.data.note
    this.form.note = this.buyerNote;
  },
  async created() {
    // #ifdef MP-TOUTIAO
      // this.form.isSelf = true
      // this.storeAddress = this.storeMap[this.storeID[0]].address
      // this.inRange = true;
      // 不校验地址信息
      // 创建一个门店地址
      // if(!(this.$store.state.address.list && this.$store.state.address.list.length>0)){
      //   await this.createStoreAdress()
      // } 
    // #endif
    try {
      this.showLoad();
      
      this.groupList = groupByStore(this.validCarList)
      
      if (!this.isMaterial) {

        if (this.form.isSelf) {
          this.storeAddress = this.storeMap[this.storeID[0]].address
          this.inRange = true
        }

        if (this.addressList && this.addressList.length === 0 && this.isMaterial) await this.createStoreAdress()  // 创建一个门店地址
        
        if (this.defaultAddress && this.defaultAddress.length > 0 && !this.form.isSelf) await this.isInRange(this.storeID[0],this.defaultAddress[0].id)

        this.deliverTimeList = await apiStore.getDeliverTime(this.storeID[0]) //获取配送时间

        // 设置默认立即送出
        let firstOne = this.deliverTimeList[0]  

        this.form.deliveryTime = {
          date: firstOne.date,
          ...firstOne.timeList[0],
        }

      } else {
        this.form.isSelf = false

        // 物料   物料店设置立即送出
        this.form.deliveryTime = {
          date: "立即送出",
          unixTime: 0,
        }

        this.inRange = true
      }

      await this.handleCreateOrder() // 创建预订单
      // this.hideLoad();
    } catch (e) {
      this.$alertBack(e);
    } finally {
      this.hideLoad();
    }
    

   
  },
  mounted() {
    // 获取自提栏在页面中的信息
	  if (!this.isMaterial && !this.storeID.includes(666666)) {
      queryEleInfo(this, '.isSelfBox').then((res) => {
        // 缩放比例尺 res.height / 60
        // 向右移 (20 *(res.width -5)) / 370
        this.isSelfSwitch = `transform:scale(${res.height / 60});` + `margin-right: ${(20 *(res.width -5)) / 370}px;`
      })
	  }
  },
  methods: {
    ...mapActions({
      removeSkuName: "cartPage/removeSkuName",
      addAddressList: 'addressVue/addListItem'
    }),
    ...mapMutations({
      updateBuyerNote: "cartPage/updateBuyerNote",
    }),
    // 预创建订单
    async handleCreateOrder(type = 0) {
      // #ifdef MP-WEIXIN
      // 如果是物料，创建地址
      // if (this.isMaterial) {
      //   // 申请物料时，默认创建门店地址，，，，，暂时不删，如果后续有需要，可以继续优化，目前每进一次页面就会创建一次，感觉很多余
      //   if (!this.addressList.findIndex(item => item.tag.includes("门店地址")) !== -1 ) {
      //     // const fromStoreInfo = this.fromStoreInfo;
      //     // await this.addAddressList({
      //     //   consigneeName: fromStoreInfo.payeeName,
      //     //   consigneeMobile: fromStoreInfo.tel1,
      //     //   address: fromStoreInfo.address,
      //     //   detailAddress: fromStoreInfo.address,
      //     //   lng: fromStoreInfo.lng,
      //     //   lat: fromStoreInfo.lat,
      //     //   tag: "门店地址",
      //     //   isDefault: 0,
      //     // });
      //   }
      // }
      // #endif

      let orderType = this.isMaterial ? (this.isPurchase ? 2 : 1) : 0

      try {
        const skus = this.validCarList.map((item) => ({
          skuID: item.id,
          count: item.count,
        }));
        // 没有地址列表的用户，初次进入这个页面时，addressID为空，会导致这个订单的其余信息无法展示，
        // 因此，给一个默认值，在去支付的时候，必须要有一个属于用户自己的addressID，要不然无法识别这个订单是谁创建的464
        let addressID = this.defaultAddress && this.defaultAddress.length > 0 ? this.defaultAddress[0].id :
          (this.addressList && this.addressList.length>0 && this.form.isSelf ? this.addressList[0].id : 464)
        let obj = {
          jxOrder: JSON.stringify({
            storeID: this.storeID[0],   // this.validCarList[0].storeID
            expectedDeliveredTimestamp: this.form.deliveryTime.unixTime
              ? this.form.deliveryTime.unixTime
              : null,
            skus,
            orderType: orderType,
          }),
          addressID,
          createType: type,
          fromStoreID: this.fromStoreID,
          isDeliverySelf: this.form.isSelf,
        };
        if (!this.isMaterial) {
          delete obj.fromStoreID;
        }

        let res = await orderPage.createOrder(obj)

        if (typeof res !== 'string') {
          this.preCreateData = res;
          this.checkOrder();
        }
      } catch (e) {
        throw e;
      }
    },
    // 检查订单信息
    checkOrder() {
      let { preCreateData, groupList } = this;
      let arr = [];
      let curList = this.groupList[preCreateData.storeID];
      preCreateData.skus.forEach((sku) => {
        let findSku = curList.find((item) => item.id === sku.skuID);
        arr.push({
          ...findSku,
          count: sku.count,
          curPrice: sku.salePrice,
        });
      });
      this.$set(this.groupList, [preCreateData.storeID], arr);
    },
    async openTimePick() {
      try {
        this.showLoad();
        if(this.deliverTimeList && this.deliverTimeList.length === 0) this.deliverTimeList = await apiStore.getDeliverTime(this.storeID[0])
        // console.log('deliverTimeList',this.deliverTimeList)
        this.timePickShow = true;
      } catch (e) {
        errToast(e);
      } finally {
        this.hideLoad();
      }
    },
    // 选择配送时间
    async handleClose(time) {
      this.timePickShow = false;
      if (time) {
        try {
          this.showLoad();
          this.form.deliveryTime = {
            ...time,
          };
          // 请求预创建
          await this.handleCreateOrder();
        } catch (e) {
          errToast(e);
        } finally {
          this.hideLoad();
        }
      }
    },
    // 跳转到备注
    goComment() {
      console.log("跳转到备注");
      jumpPage('navigateTo',"/pagesOrders/add-note/index")
    },
    // 支付
    async handlePay() {
      console.log(this.form);
      if (!(this.defaultAddress && this.defaultAddress.length > 0) && !this.form.isSelf) {
        toast('请填写收获地址')
        return
      }
      const { preCreateData } = this;
      try {
        this.showLoad();
        // 先创建订单
        let orderType = 0;
        if (this.isMaterial) orderType = this.isPurchase ? 2 : 1
        let obj = {
          jxOrder: JSON.stringify({
            ...preCreateData,
            buyerComment: this.form.note,
            orderType: orderType,
          }),
          // addressID: this.form.isSelf?464:this.defaultAddress[0].id,
          addressID:this.defaultAddress && this.defaultAddress.length>0 ?this.defaultAddress[0].id:464,
          createType: 1,
          fromStoreID: this.fromStoreID,
          isDeliverySelf: this.form.isSelf,
        };
        if (!this.isMaterial) delete obj.fromStoreID;
        if (this.form.isSelf && this.defaultAddress && this.defaultAddress.length === 0 &&  this.defaultAddress[0]) obj.addressID = this.addressList[0].id
        let orderInfo = await orderPage.createOrder(obj)

        // 订单创建成功，从购物车移除下单商品
        await this.removeSkuName(this.validCarList)
        // 订单创建成功，从购物车移除下单商品
        // return false
        // 获取支付信息

        // #ifdef APP-PLUS || APP
        // console.log('跳转支付，订单信息',this.orderInfo)
        let res = await modal("温馨提示", '为了保证您的账户安全，即将跳转到微信进行支付');
        if (res) {
          let jxParams = {
          "origin": "weixinappcs",
          "vendorOrderID": orderInfo.orderID,
          "storeID": this.storeID[0],
          "name": this.storeMap[this.storeID].name,
          "totalPrice":this.preCreateData.actualPayPrice?preCreateData.actualPayPrice:totalPay
        }
          // console.log('打印jxParams', JSON.stringify(jxParams))

          openWeixinMiniprogram(`pagesPay/JX-pay/JX-pay?jxParams=${JSON.stringify(jxParams)}`)
        }
        // return

        // #endif


        let payInfo = {}

        // #ifdef MP-WEIXIN
        payInfo = await orderPage.pay4Order({
          vendorOrderID: orderInfo.orderID,
          payType: 2,
          vendorPayType: 'W06',
          subAppID: "wx4b5930c13f8b1170",
        });
        await handleCreatePay(
          payInfo.vendorOrderID,
          payInfo.prepayID,
          JSON.parse(payInfo.codeURL)
        );
        // #endif

        // #ifdef MP-TOUTIAO
        payInfo = await orderPage.pay4Order({
          vendorOrderID: orderInfo.orderID,
          payType: 3,
          vendorPayType: 'tt',
          // subAppID: "tta6a1d01c399f264201",  // 京西菜市
          subAppID: "tta6a1d01c399f264201",   // 京西到家
        });
        await handleCreatePay(
          payInfo.vendorOrderID,
          payInfo.prepayID,
          payInfo.codeURL,
          payInfo
        );
        // #endif

        // #ifdef MP-KUAISHOU
        payInfo = await orderPage.pay4Order({
          vendorOrderID: orderInfo.orderID,
          payType: 4,
          vendorPayType: 'ks',
          subAppID: "ks680887971696897880",   // 京西到家
        });
        // return payInfo
        await handleCreatePay(
          payInfo.vendorOrderID,
          payInfo.prepayID,
          payInfo.codeURL,
          payInfo
        );
        // #endif

        // #ifdef MP-ALIPAY
        payInfo = await orderPage.pay4Order({
          vendorOrderID: orderInfo.orderID,
          payType: 2,
          vendorPayType: 'A02',
        });
        await handleCreatePay(
          payInfo.vendorOrderID,
          payInfo.prepayID,
          payInfo.codeURL
        );
        // #endif

        // console.log(payInfo);
        // return false

        // 支付成功，跳转到待收货订单
        uni.redirectTo({ url: `/pagesOrders/my-order/index?name=waitReceive` });
        toast("支付成功");
      } catch (e) {
        console.error(e);
        if ("errKey" in e) {
          if (e.errKey === "createOrder") {
            // 创建订单失败
            errToast("订单创建失败，请稍后重试");
          } else if (e.errKey === "pay4Order") {
            // 下单失败，跳转到订单详情，待支付页面
            uni.redirectTo({ url: `/pagesOrders/my-order/index?name=waitPay` });
          } else if (e.errKey === "requestPayment") {
            // 支付失败，跳转到订单详情，待支付页面
            uni.redirectTo({ url: `/pagesOrders/my-order/index?name=waitPay` });
          } else {
          }
        } else {
          errToast(e);
        }
      } finally {
        this.hideLoad();
        this.updateBuyerNote("");
      }
    },
    async onChange(e) {
      try {
        this.showLoad();
        let val = e.detail.value
        this.form.isSelf = val
        if (val) {
          this.storeAddress = this.storeMap[this.storeID[0]].address
          
          this.inRange = true // 不校验地址信息

          if(!(this.addressList && this.addressList.length>0)) await this.createStoreAdress() // 创建一个门店地址
        } else {
          // 校验地址信息的配送范围297 66
          let id = this.defaultAddress.length>0 && this.defaultAddress && this.defaultAddress[0].id? this.defaultAddress[0].id:464
          await this.isInRange(this.storeID[0], id)
        }
        await this.handleCreateOrder();
      } catch (e) {
        if(!this.inRange){
          this.$alertBack(e, "错误", {
            complete() { },
          })
        }
      } finally {
        this.hideLoad();
      }
    },
    // 判断当前地址是否在配送范围内
    async isInRange(storeID, addressID) {
      try {
        let res = await orderPage.createOrder({
          jxOrder: JSON.stringify({
            storeID,
          }),
          addressID,
        })

        this.inRange = typeof res === 'string' ? false : true
      } catch (e) {
        throw e
      }
    },
    // 为用户创建一个门店地址
    async createStoreAdress() {
      
      // let userInfo = uni.getStorageSync('aldstat_user_info')
      let consigneeName = this.selfInfo.name
      let consigneeMobile = this.selfInfo.mobile
      let address = this.storeMap[this.storeID[0]].address.address
      let detailAddress = '自提订单：详细地址'
      let lng = this.storeMap[this.storeID[0]].lng ? this.storeMap[this.storeID[0]].lng : this.myLocation.lng
      let lat = this.storeMap[this.storeID[0]].lat ? this.storeMap[this.storeID[0]].lat : this.myLocation.lat
      let isDefault = 0

      await this.addAddressList({
        consigneeName,
        consigneeMobile,
        address,
        detailAddress,
        lng,
        lat,
        tag:'自提地址',
        isDefault
      })
   }
  },
};
</script>

<style lang="scss">
@import "./create-order.scss";
page {
  background: #f4f4f4;
}
</style>