<template>
  <view class="create-order" :style="{ '--primary-color': primaryColor }">
    <view class="transport-tabs">
      <view
        class="transport-tabs-item"
        :class="activeTransportKey === 4 ? 'active-tab' : ''"
        @click="handleTabClick(4)"
      >
        配送
      </view>
      <view
        class="transport-tabs-item"
        :class="activeTransportKey === 2 ? 'active-tab' : ''"
        @click="handleTabClick(2)"
      >
        自提
      </view>
    </view>
    <u-cell-group>
      <u-cell-item
        v-if="activeTransportKey === 4"
        :title="addressText"
        :label="nameAndTel"
        arrow
        @click="handleSelectAddr"
      ></u-cell-item>
      <u-cell-item
        v-if="activeTransportKey === 2"
        :title="currentPick ? currentPick.name : '请选择门店'"
        :label="currentPick.address + currentPick.location"
        arrow
        @click="gotoPickList"
      ></u-cell-item>
    </u-cell-group>
    <view class="order-store-list">
      <view v-for="(item, idx) in orderStoreArray" class="order-store-item" :key="idx">
        <u-cell-group>
          <u-cell-item :title="item.store.name" arrow></u-cell-item>
        </u-cell-group>
        <yi-goods-card
          v-for="(orderItem, ridx) in item.orderInfo"
          :key="ridx"
          :tag="orderItem.good.goods.transport === 2 ? '自提' : null"
          :num="orderItem.numBuy"
          :price="orderData.type === 'newFlash' ? orderData.price : orderItem.good.price"
          :desc="orderItem.good.name"
          :title="orderItem.good.goods.nameSpu"
          :thumb="
            orderItem.good.iconSku && orderItem.good.iconSku !== '' ? imgUrl + orderItem.good.iconSku : defaultGoodsIcon
          "
          thumb-mode="aspectFill"
        >
        </yi-goods-card>

        <u-cell-group>
          <u-cell-item
            title="商品金额"
            :arrow="false"
            v-if="orderData.type === 'newFlash'"
            :value="'¥' + orderData.price"
          ></u-cell-item>
          <u-cell-item title="商品金额" :arrow="false" v-else :value="'¥' + item.orderStorePay"></u-cell-item>
        </u-cell-group>

        <u-cell-group :border="false">
          <u-cell-item title="运费" :arrow="false" :value="'¥' + item.transportFee"></u-cell-item>
        </u-cell-group>

        <view class="order-note">
          <text class="cell-title">备注</text>
          <input
            type="text"
            placeholder="给商家留言"
            :value="item.orderInfo[0].note"
            @input="handleStoreNoteChange($event, idx)"
          />
        </view>
      </view>
    </view>
    <view class="order-pay-amount">
      <u-cell-group>
        <u-cell-item
          title="订单金额"
          :arrow="false"
          :value="orderData.type === 'newFlash' ? '¥' + orderData.price : '¥' + orderResult.payBefore"
        ></u-cell-item>
      </u-cell-group>
      <u-cell-group :border="false" v-if="orderData.type !== 'newFlash'">
        <u-cell-item
          title="优惠券"
          @click="showCouponPopup"
          :value="isUseCoupon ? '组合优惠' : '不使用优惠券'"
        ></u-cell-item>
      </u-cell-group>
      <u-cell-group :border="false">
        <u-cell-item
          title="合计"
          :arrow="false"
          :value="orderData.type === 'newFlash' ? '¥' + orderData.price : '¥' + orderResult.payAfter"
        ></u-cell-item>
      </u-cell-group>
    </view>
    <yi-submit-bar
      v-if="activeTransportKey === 4"
      :price="orderData.type === 'newFlash' ? '¥' + orderData.price : '¥' + totalPayAmount"
      :disabled="!address"
      button-text="提交订单"
      @submit="handleSubmitOrder"
    />
    <yi-submit-bar
      v-if="activeTransportKey === 2"
      :price="orderData.type === 'newFlash' ? '¥' + orderData.price : '¥' + totalPayAmount"
      :disabled="!currentPick"
      button-text="提交订单"
      @submit="handleSubmitOrder"
    />

    <!--  优惠券弹窗  -->
    <u-popup
      v-model="couponPopupVisible"
      border-radius="14"
      safe-area-inset-bottom
      mode="bottom"
      @close="closeCouponPopup"
    >
      <view class="coupon-pop-title">请选择优惠券</view>
      <u-cell-group>
        <u-cell-item :border-bottom="false" :arrow="false" title="不使用优惠券" @click="switchCoupon('isNotUseCoupon')">
          <u-checkbox
            slot="right-icon"
            shape="circle"
            :active-color="primaryColor"
            v-model="isNotUseCoupon"
            @change="switchCoupon('isNotUseCoupon')"
          >
          </u-checkbox>
        </u-cell-item>
      </u-cell-group>
      <u-cell-group>
        <u-cell-item :arrow="false" title="组合优惠" @click="switchCoupon('isUseCoupon')">
          <u-checkbox
            slot="right-icon"
            shape="circle"
            :active-color="primaryColor"
            v-model="isUseCoupon"
            @change="switchCoupon('isUseCoupon')"
          >
          </u-checkbox>
        </u-cell-item>
      </u-cell-group>
      <view v-for="(item, index) in availableList" :key="index" class="coupon-item">
        <yi-coupon-item
          :coupon-type="item.couponStore.property === 'cash' ? '红包' : '优惠券'"
          :discount-amount="item.amount"
          :discount-content="`满${item.couponStore.minCost}可用`"
          :end-time="item.expireTime"
          :coupon-name="item.couponStore.name"
        ></yi-coupon-item>
      </view>
    </u-popup>
  </view>
</template>

<script>
import cloneDeep from 'lodash.clonedeep';
import { Setting } from '../../index';
import { newOrderIndexBunch, fetchCouponUserList, tryOrderCoupon, queryPickList, newFlash } from '../../mall/api';
import { mapState } from 'vuex';

export default {
  name: 'createOrder',
  props: {
    orderData: {
      type: Object,
      default: () => null,
    },
    // 配送方式为2: 自提的时候, 取货点/门店id
    selectPid: {
      type: String,
      default: null,
    },
    // 选择的自提点
    selectPick: {
      type: Object,
      default: () => null,
    },
    // 商品默认图片
    defaultGoodsIcon: {
      type: String,
      default: null,
    },
  },
  data() {
    return {
      checkboxActiveColor: '#ee0a24',
      imgUrl: Setting.getImgPath(),
      address: null,
      addressText: '请选择配送地址',
      addressPickText: '请选择自提地址',
      nameAndTel: null,
      orderResult: null,
      orderStoreArray: [],
      orderStoreArrayIdx: null,
      orderForm: [],
      orderFormOriginal: [], // 最原始的订单参数信息
      goodArr: [],
      totalPayAmount: 0,
      transport: 0, // 配送方式 0:无配送方式 1: 邮寄 2: 自提 3:邮寄+自提
      payMethodPick: 0, // 支付方式 0: 现金支付; >0: 混合支付,由商品支付方式决定
      activeTransportKey: 4,
      currentPick: null, // 当前自提点信息
      // 卡券参数
      availableList: [],
      selectedAvailableList: [],
      selectedCouponList: [],
      couponArr: [],
      discountAmount: 0,
      couponPopupVisible: false,
      isNotUseCoupon: false,
      isUseCoupon: false,
    };
  },
  computed: {
    ...mapState({
      primaryColor: state => (state.primaryColor ? state.primaryColor : '#ee0a24'),
    }),
  },
  watch: {
    selectPick: {
      immediate: true,
      handler: function (v) {
        if (v) {
          console.log('%c [watch selectPick]: ', 'color:#f33;', v);
          this.currentPick = v;
        }
      },
    },
  },
  mounted() {
    console.log('%c [createOrder mounted]: ', 'color:#1989fa;', this.orderData);
    const { type, aid, price, orderForm } = this.orderData;
    const orderDataCp = cloneDeep(orderForm);
    orderDataCp.forEach(item => {
      item.transport = this.activeTransportKey;
    });
    this.orderForm = orderDataCp;
    this.orderFormOriginal = orderForm;

    this.goodArr = orderDataCp.map(item => ({
      gid: item.gid,
      numBuy: item.numBuy,
      transport: item.transport,
    }));
    console.log('%c [this.goodArr]: ', 'color:#1989fa;', this.goodArr);
    if (type === 'newOrderIndexBunch') {
      this.getCouponUserList();
    }
    this.preNewOrderBunch();
    this.getLocationInfo();
  },
  methods: {
    // 选择收货地址
    handleSelectAddr() {
      // console.log('%c [handleSelectAddr]: ', 'color:#1989fa;');
      const _this = this;
      uni.chooseAddress({
        success(res) {
          console.log('chooseAddress success', res);
          // 收货地址
          _this.address = `${res.userName} ${res.telNumber} ${res.provinceName} ${res.cityName} ${res.countyName} ${res.detailInfo}`;
          _this.addressText = `${res.provinceName} ${res.cityName} ${res.countyName} ${res.detailInfo}`;
          _this.nameAndTel = res.userName + ' ' + res.telNumber;
          // eslint-disable-next-line no-return-assign
          _this.orderForm.forEach(item => (item.address = _this.address));
        },
      });
    },
    // 预下单
    async preNewOrderBunch() {
      try {
        const goodArr = cloneDeep(this.orderForm);
        goodArr.forEach(gItem => {
          delete gItem.acc;
        });
        const params = {
          form: {
            goodArr: goodArr,
            isNew: false,
            transport: this.activeTransportKey,
          },
        };
        // 使用优惠券
        if (this.isUseCoupon === true) {
          params.form.couponArr = this.selectedCouponList;
        } else {
          delete params.form.couponArr;
        }
        const res = await newOrderIndexBunch(params);
        this.orderResult = res;
        this.orderResult.payBefore = JSON.parse(res.payMapBefore).cash;
        this.orderResult.payAfter = JSON.parse(res.payMapAfter).cash;
        console.log('%c [预下单 ok]: ', 'color:#1989fa;', res);
        console.log('%c [预下单 ok 2]: ', 'color:#1989fa;', goodArr);
        this.orderStoreArray = res.storeArray;

        this.orderStoreArray.forEach(item => {
          console.log('%c [orderStoreArray item]: ', 'color:#198933;', item);
          // 商品金额
          item.orderStorePay = JSON.parse(item.payMapBefore).cash;
        });
        this.totalPayAmount = JSON.parse(res.payMapAfter).cash;
        console.log('%c [预下单 orderStoreArray]: ', 'color:#1989fa;', this.orderStoreArray);
        console.log('%c [预下单 totalPayAmount]: ', 'color:#1989fa;', this.totalPayAmount);
      } catch (e) {
        console.log('%c [预下单 error]: ', 'color:#1989fa;', e);
        throw e;
      }
    },
    // 真下单
    async handleNewOrder() {
      if (this.activeTransportKey === 4 && this.address === null) {
        uni.showToast({
          icon: 'error',
          title: '请选择收货地址',
        });
        return;
      }
      if (this.activeTransportKey === 2 && this.selectPid === null) {
        uni.showToast({
          icon: 'error',
          title: '请选择门店地址',
        });
        return;
      }
      try {
        const goodArr = cloneDeep(this.orderForm);
        goodArr.forEach(gItem => {
          // gItem.comment = 'nfcp';
          delete gItem.acc;
        });
        const params = {
          form: {
            goodArr: goodArr,
            isNew: true,
            transport: this.activeTransportKey,
          },
        };
        if (this.activeTransportKey === 2 && this.selectPid !== null) {
          params.form.pid = this.selectPid;
        }
        // 使用优惠券
        if (this.isUseCoupon === true) {
          params.form.couponArr = this.selectedCouponList;
        } else {
          delete params.form.couponArr;
        }
        console.log('%c [真下单 参数]: ', 'color:#1989fa;', goodArr);
        console.log('%c [真下单 this.orderForm]: ', 'color:#1989fa;', this.orderForm);
        const res = await newOrderIndexBunch(params);
        const accArr = this.orderFormOriginal.map(item => item.acc);
        // await this.updateCartList(accArr);
        console.log('%c [真下单 ok]: ', 'color:#1989fa;', res);
        // uni.redirectTo({
        //   url: `/demo/packageMall/orderPay?xid=${res.xid}&payAmount=${this.totalPayAmount}`,
        // });
        this.$emit('payOrder', { totalPayAmount: this.totalPayAmount, xid: res.xid });
        this.$emit('updateCartList', accArr);
      } catch (e) {
        console.log('err', e);
        throw e;
      }
    },
    formatOrderForm() {
      let orderForm = [];
      this.orderStoreArray.forEach(item => {
        item.orderInfo.forEach(oItem => {
          orderForm.push({
            address: this.address,
            gid: oItem.good.gid,
            note: oItem.note,
            numBuy: oItem.numBuy,
            payMethodPick: 1,
            transport: this.activeTransportKey,
          });
        });
      });
      this.orderForm = orderForm;
      return orderForm;
    },
    // 选择配送方式
    // onSelectTransport(index) {
    //   // console.log('%c [选择配送方式]: ', 'color:#1989fa;', e.$wx.detail);
    //   // console.log('%c [选择配送方式]2: ', 'color:#1989fa;', this.orderStoreArrayIdx);
    //   // console.log('%c [选择配送方式]3: ', 'color:#1989fa;', this.orderStoreArray);
    //   this.showActionSheet = false;
    //   this.orderStoreArray[this.orderStoreArrayIdx].orderInfo.forEach(oItem => {
    //     if (oItem.good.goods.transport === 3) {
    //       // 商品原始的配送是自提+邮寄的商品(transport === 3) 更改其配送方式
    //       oItem.transportSelect = this.transportActions[index].value;
    //     }
    //   });
    //   console.log('%c [重新预下单]: ', 'color:#1989fa;', this.orderStoreArray);
    //   // 选择配送方式以后重新预下单
    //   const orderForm = this.formatOrderForm();
    //   console.log('%c [重新预下单 orderForm]: ', 'color:#1989fa;', orderForm);
    //   this.preNewOrderBunch();
    // },
    // 给商家留言
    handleStoreNoteChange(e, idx) {
      // console.log('%c [给商家留言]00: ', 'color:#1989fa;', e, idx);
      // console.log('%c [给商家留言]: ', 'color:#1989fa;', e.$wx.detail);
      // const { idx } = e.$wx.currentTarget.dataset;
      const { value } = e.detail;
      this.orderStoreArray[idx].orderInfo.forEach(oItem => {
        oItem.note = value;
      });
      this.formatOrderForm();
    },
    // todo 金额合计 优惠券的使用
    // 获取券列表
    async getCouponUserList(page = 0) {
      const params = {
        query: {
          limit: 100,
          page,
          keyJson: JSON.stringify({ status: 3 }),
        },
        cate: 'buy',
      };

      console.log('%c [getCouponUserList 000]: ', 'color:#1989fa;');
      const { data } = await fetchCouponUserList(params);
      this.list = data;
      const couponArr = this.list.map(item => ({ acc: item.acc }));
      const form = {
        isSort: true,
        couponArr,
        goodArr: this.goodArr,
      };
      console.log('%c [getCouponUserList ok]: ', 'color:#1989fa;', this.list);
      // this.availableList = this.list;
      await this.getAvailableCoupon(form);
    },
    // 获取可用/不可用优惠券
    // todo 优惠券超过100张的逻辑
    async getAvailableCoupon(form, init = true) {
      const tryCouponList = await tryOrderCoupon({ form });
      this.availableList = [];
      this.notAvailableList = [];
      this.list.forEach(item => {
        tryCouponList.forEach(cItem => {
          if (cItem.acc === item.acc) {
            item['$fid'] = cItem.fid;
            item['$comment'] = cItem.comment;
          }
        });
      });
      // console.log('%c [this.list]: ', 'color:#1989fa;', this.list);
      const availableCoupon =
        tryCouponList.length === 0 ? [] : this.list.filter(item => item['$fid'] !== null && item['$fid'] !== '');
      const discountArray = availableCoupon.map(item => item.amount);
      console.log(' discountArray -->', discountArray);
      this.discountAmount = discountArray.length === 0 ? 0 : discountArray.reduce((pre, cur) => pre + cur);
      this.availableList = availableCoupon;
      // this.notAvailableList = notAvailableCoupon;
      console.log('this.availableList -->', this.availableList);
      if (init) {
        this.selectedAvailableList = cloneDeep(this.availableList);
      }
      // selectedCouponList
      const selectedCouponList = [];
      availableCoupon.forEach(item => {
        if (item['$fid']) {
          selectedCouponList.push({ acc: item.acc });
        }
      });
      this.selectedCouponList = selectedCouponList;
      return tryCouponList;
    },
    // 隐藏优惠券弹窗
    closeCouponPopup() {
      this.couponPopupVisible = false;
    },
    // 显示优惠券弹窗
    showCouponPopup() {
      this.couponPopupVisible = true;
    },
    // 切换优惠券的使用
    switchCoupon(type) {
      console.log('%c [切换优惠券的使用]: ', 'color:#1989fa;', type);
      this.couponPopupVisible = false;
      if (type === 'isUseCoupon') {
        this.isUseCoupon = true;
        this.isNotUseCoupon = false;
      }
      if (type === 'isNotUseCoupon') {
        this.isUseCoupon = false;
        this.isNotUseCoupon = true;
      }
      this.preNewOrderBunch();
    },
    // 下单成功删除购物车对应的商品
    updateCartList(accArr) {
      // eslint-disable-next-line no-undef
      // let pages = getCurrentPages();
      // let prePage = pages[pages.length - 2];
      // if (prePage.route === 'packageMall/cart/cartList') {
      //   console.log('%c [prePage]: ', 'color:#1989fa;', prePage);
      //   prePage.$wepy.$options.methods.onDelCartBunch(accArr);
      // }
    },

    handleTabClick(key) {
      console.log('%c [handleTabClick]: ', 'color:#1989fa;', key);
      this.activeTransportKey = key;
      // 选择配送方式以后重新预下单
      const orderForm = this.formatOrderForm();
      console.log('%c [重新预下单 orderForm]: ', 'color:#1989fa;', orderForm);
      this.preNewOrderBunch();
    },

    // 跳转到门店列表
    gotoPickList() {
      this.$emit('gotoPickList');
    },
    // 获取当前位置
    getLocationInfo() {
      let _this = this;
      uni.getLocation({
        type: 'wgs84',
        success(res) {
          const { latitude, longitude } = res;
          console.log('%c [getLocation]: ', 'color:#1989fa;', res);
          _this.getPickList(0, latitude, longitude);
        },
      });
    },
    async getPickList(page = 0, latitude = null, longitude = null) {
      const params = {
        query: {
          limit: 100,
          page,
        },
      };
      if (latitude && longitude) {
        params.location = {
          latitude: latitude,
          longitude: longitude,
        };
      }
      const { data, meta } = await queryPickList(params);
      console.log('%c [queryPickList]: ', 'color:#1989fa;', data, meta);
      this.currentPick = data[0];
    },
    // 秒杀
    async handleNewFlash() {
      if (this.activeTransportKey === 4 && this.address === null) {
        uni.showToast({
          icon: 'error',
          title: '请选择收货地址',
        });
        return;
      }
      if (this.activeTransportKey === 2 && this.selectPid === null) {
        uni.showToast({
          icon: 'error',
          title: '请选择门店地址',
        });
        return;
      }
      try {
        const goodArr = cloneDeep(this.orderForm);
        goodArr.forEach(gItem => {
          delete gItem.acc;
        });
        const params = {
          form: {
            goodArr: goodArr,
            isNew: true,
            aid: this.orderData.aid,
            transport: this.activeTransportKey,
          },
        };
        console.log('%c [秒杀 参数]: ', 'color:#1989fa;', params);
        console.log('%c [秒杀 this.orderForm]: ', 'color:#1989fa;', this.orderForm);
        const res = await newFlash(params);
        const accArr = this.orderFormOriginal.map(item => item.acc);
        console.log('%c [秒杀 ok]: ', 'color:#1989fa;', res);
        const totalPayAmount = this.orderData.price;
        this.$emit('newFlashResolve', { totalPayAmount, id: res.id });
      } catch (e) {
        console.log('handleNewFlash err', e);
        throw e;
      }
    },

    handleSubmitOrder() {
      if (this.orderData.type === 'newOrderIndexBunch') {
        this.handleNewOrder();
      }
      if (this.orderData.type === 'newFlash') {
        this.handleNewFlash();
      }
    },
  },
};
</script>

<style scoped lang="scss">
$primary-color: var(--primary-color);
.create-order {
  background-color: #fafafa;
  .transport-tabs {
    display: flex;
    flex-direction: row;
    .transport-tabs-item {
      flex: 1;
      text-align: center;
      padding: 20rpx;
      background-color: #fff;
    }
    .active-tab {
      color: $primary-color;
      border-bottom: 1px solid $primary-color;
    }
  }
  .order-store-list {
    margin-bottom: 10px;
  }
  .order-store-item {
    margin-top: 10px;
  }
  .order-note {
    display: flex;
    flex-direction: row;
    align-items: center;
    padding: 16px;
    background-color: #fff;
    .cell-title {
      color: #333;
      margin-right: 5px;
      font-size: 28rpx;
    }
    input {
      flex: 1;
      font-size: 28rpx;
      color: #999;
      background-color: #fff;
    }
  }
  .order-pay-amount {
    margin-bottom: 60px;
    padding-bottom: env(safe-area-inset-bottom);
  }
  .coupon-pop-title {
    width: 100vw;
    text-align: center;
    margin-top: 10px;
  }
  .coupon-item {
    width: 100vw;
    background-color: #fff;
    padding: 10px;
  }
}
</style>
