<template>
  <view class="create-order">
    <u-cell-group>
      <u-cell-item :title="addressText" :label="nameAndTel" arrow @click="handleSelectAddr"></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="orderItem.good.price"
          :desc="orderItem.good.nameSku"
          :title="orderItem.good.goods.nameSpu"
          :thumb="imgUrl + orderItem.good.iconSku"
        >
        </yi-goods-card>

        <u-cell-group>
          <u-cell-item title="商品金额" :arrow="false" :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>

        <u-cell-group v-if="item.showTransportActionSheet" :border="false">
          <u-cell-item title="配送" arrow :value="item.transportName" @click="onShowActionSheet(idx)"></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="orderResult.payBefore"></u-cell-item>
      </u-cell-group>
      <u-cell-group :border="false">
        <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="orderResult.payAfter"></u-cell-item>
      </u-cell-group>
    </view>
    <yi-submit-bar :price="totalPayAmount" :disabled="!address" button-text="提交订单" @submit="handleNewOrder" />
    <!--  配送方式弹窗  -->
    <u-action-sheet
      :tips="tips"
      cancel-btn
      mask-close-able
      v-model="showActionSheet"
      :list="transportActions"
      @click="onSelectTransport"
      @close="hideActionSheet"
      @cancel="hideActionSheet"
    />
    <!--  优惠券弹窗  -->
    <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="checkboxActiveColor"
            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="checkboxActiveColor"
            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 } from '../../mall/api';

export default {
  name: 'createOrder',
  props: {
    orderData: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      checkboxActiveColor: '#f33',
      imgUrl: Setting.getImgPath(),
      address: null,
      addressText: '请选择收货地址',
      nameAndTel: null,
      orderResult: null,
      orderStoreArray: [],
      orderStoreArrayIdx: null,
      orderForm: [],
      orderFormOriginal: [], // 最原始的订单参数信息
      goodArr: [],
      totalPayAmount: 0,
      transport: 0, // 配送方式 0:无配送方式 1: 邮寄 2: 自提 3:邮寄+自提
      payMethodPick: 0, // 支付方式 0: 现金支付; >0: 混合支付,由商品支付方式决定
      transportActions: [
        {
          text: '邮寄',
          value: 1,
        },
        {
          text: '到店自提',
          value: 2,
        },
        {
          text: '同城配送',
          value: 4,
        },
      ],
      tips: { text: '请选择配送方式', color: '#666', fontSize: 28 },
      showActionSheet: false,
      // 卡券参数
      availableList: [],
      selectedAvailableList: [],
      selectedCouponList: [],
      couponArr: [],
      discountAmount: 0,
      couponPopupVisible: false,
      isNotUseCoupon: false,
      isUseCoupon: false,
    };
  },
  mounted() {
    console.log('%c [createOrder mounted]: ', 'color:#1989fa;', this.orderData);
    this.orderForm = this.orderData;
    this.orderFormOriginal = this.orderData;

    this.goodArr = this.orderForm.map(item => ({ gid: item.gid, numBuy: item.numBuy, transport: item.transport }));
    this.preNewOrderBunch();
    this.getCouponUserList();
  },
  methods: {
    // 显示选择的配送方式  todo
    handleTransportName(item) {
      let transportName = '请选择';
      const existMixTransport = item.orderInfo.some(oItem => oItem.transport === 3);
      console.log('%c [existMixTransport]: ', 'color:#1989fa;', existMixTransport);
      const mixTransportIndex = item.orderInfo.findIndex(oItem => oItem.good.goods.transport === 3);
      console.log('%c [mixTransportIndex]: ', 'color:#1989fa;', mixTransportIndex);
      if (existMixTransport) {
        transportName = '请选择';
      } else if (!existMixTransport && mixTransportIndex !== -1) {
        if (mixTransportIndex !== -1 && item.orderInfo[mixTransportIndex].transport === 1) {
          transportName = '邮寄';
        }
        if (mixTransportIndex !== -1 && item.orderInfo[mixTransportIndex].transport === 2) {
          transportName = '自提';
        }
      }
      return transportName;
    },
    // 选择收货地址
    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,
          },
        };
        // 使用优惠券
        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);
        this.orderStoreArray = res.storeArray;
        this.orderStoreArray.forEach(item => {
          console.log('%c [orderStoreArray item]: ', 'color:#198933;', item);
          // 商品金额
          item.orderStorePay = JSON.parse(item.payMapBefore).cash;
          // 商品原始的配送是自提+邮寄(transport === 3)，才需要显示 '选择配送方式'
          if (
            item.orderInfo.findIndex(
              oItem =>
                oItem.good.goods.transport !== 1 &&
                oItem.good.goods.transport !== 2 &&
                oItem.good.goods.transport !== 4,
            ) !== -1
          ) {
            item.showTransportActionSheet = true;
          } else {
            item.showTransportActionSheet = false;
          }
          item.transportName = this.handleTransportName(item);
        });
        this.totalPayAmount = JSON.parse(res.payMapAfter).cash;
        console.log('%c [预下单 totalPayAmount]: ', 'color:#1989fa;', this.totalPayAmount);
      } catch (e) {
        console.log('%c [预下单 error]: ', 'color:#1989fa;', e);
        throw e;
      }
    },
    // 真下单
    async handleNewOrder() {
      if (this.address === 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,
          },
        };
        // 使用优惠券
        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', this.totalPayAmount);
        this.$emit('updateCartList', accArr);
      } catch (e) {
        console.log('err', e);
        throw e;
      }
    },
    // 显示配送方式选择弹窗
    onShowActionSheet(idx = null) {
      if (idx !== null) {
        this.orderStoreArrayIdx = idx;
      }
      this.showActionSheet = true;
    },
    // 隐藏配送方式选择弹窗
    hideActionSheet() {
      this.showActionSheet = false;
    },
    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: oItem.transportSelect ? oItem.transportSelect : oItem.transport,
          });
        });
      });
      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);
      // }
    },
  },
};
</script>

<style scoped lang="scss">
.create-order {
  background-color: #fafafa;
  .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;
  }
  .coupon-pop-title {
    width: 100vw;
    text-align: center;
    margin-top: 10px;
  }
  .coupon-item {
    width: 100vw;
    background-color: #fff;
    padding: 10px;
  }
}
</style>
