<!--
  Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

  https://www.mall4j.com/

  未经允许，不可做商业用途！

  版权所有，侵权必究！
-->

<template>
  <view class="Mall4j page-order-shipping">
    <view class="select-prod order-shipping-item">
      <view class="title">
        {{ $t('xuanZeFaHuoShangPin') }}
      </view>
      <view
        v-for="(prod, index) in orderInfo.orderItems"
        :key="index"
        class="prod-item"
      >
        <view class="item">
          <view
            class="check"
            :class="{ select: queryProd(prod.orderItemId), disable: prod.prodCount < 1 || !(prod.status !== 0 && (!prod.returnMoneySts || prod.returnMoneySts < 0 || prod.returnMoneySts > 5) && ![1, 2, 5].includes(prod.platformInterventionStatus))}"
            @tap="selectProd(prod.orderItemId, prod.prodCount > 0 && (prod.status !== 0 && (!prod.returnMoneySts || prod.returnMoneySts < 0 || prod.returnMoneySts > 5)) && ![1, 2, 5].includes(prod.platformInterventionStatus))"
          />
        </view>
        <view class="img">
          <view class="prod-img-image">
            <img-show :src="prod.pic" />
          </view>
        </view>
        <view class="info">
          <view class="prod-name">
            {{ prod.prodName }}
            <span
              v-if="prod.skuName"
              class="prod-sku"
            >
              &nbsp;&nbsp;{{ prod.skuName }}
            </span>
          </view>
          <view
            v-if="prod.returnMoneySts && prod.returnMoneySts > 0"
            class="prod-stutus-item"
          >
            {{ orderStatus[prod.returnMoneySts < 5 ? 1 : prod.returnMoneySts + ''] }}
          </view>
          <view class="shipping-num">
            <text>{{ $t('keFaHuoShuProdprodcountFaHuoShuLiang').replace['prodCount', prod.prodCount] }}</text>
            <view class="operation">
              <view
                class="item"
                :class="{disable:prod.changeNum === 1 }"
                @tap="handleChangeProdCount(index, -1)"
              >
                -
              </view>
              <view class="num">
                <input
                  v-model="prod.changeNum"
                  class="num-input"
                  :disabled="prod.prodCount < 1"
                  :class="{disable:prod.prodCount < 1 }"
                  type="number"
                  :max="prod.prodCount"
                  :min="1"
                  @blur="checKCount($event, index)"
                >
              </view>
              <view
                class="item"
                :class="{disable: prod.prodCount < 1 || prod.prodCount === prod.changeNum }"
                @tap="handleChangeProdCount(index, 1)"
              >
                +
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <view class="delivery-info order-shipping-item">
      <view class="title">
        <text class="text">
          {{ $t('peiSongXinXi') }}
        </text>
        <image
          v-if="orderInfo.dvyType === 1 || orderInfo.dvyType === 4"
          class="img"
          src="/static/images/editor.png"
          @tap="addrEditor"
        />
      </view>
      <view class="delivery-info-item">
        <view class="delivery-info-item-title">
          {{ $t('peiSongFangShi-0') }}
        </view>
        <view class="text">
          {{ orderInfo.dvyType === 1 ? $t('kuaiDiPeiSong') : $t('tongChengPeiSong') }}
        </view>
      </view>
      <view class="delivery-info-item">
        <view class="delivery-info-item-title">
          {{ $t('shouHuoXinXi') }}
        </view>
        <view class="text">
          {{ userAddrOrder.receiver }} {{ userAddrOrder.mobile }}
        </view>
      </view>
      <view class="delivery-info-item">
        <view class="delivery-info-item-title">
          {{ $t('shouHuoDiZhi-0') }}
        </view>
        <view
          class="text"
        >
          {{
            `${userAddrOrder.province || ''} ${userAddrOrder.city || ''} ${userAddrOrder.area || ''} ${userAddrOrder.addr || ''}`
          }}
        </view>
      </view>
    </view>
    <view
      v-if="orderInfo.remarks"
      class="buyer-remarks order-shipping-item"
    >
      <view class="buyer-remarks-title">
        {{ $t('maiJiaBeiZhu-1') }}
      </view>
      <view class="buyer-remarks-content">
        {{ orderInfo.remarks }}
      </view>
    </view>
    <view class="order-shipping-item courier-info">
      <view
        class="courier-info-item"
        @tap="selecMode"
      >
        <view class="title">
          {{ $t('faHuoFangShi') }}
        </view>
        <view class="text">
          {{ shippingMethods[findDeliveryMethod].name }}
        </view>
        <view class="icon" />
      </view>
      <view
        v-if="deliveryMethod === 4"
        class="courier-info-item"
      >
        <view class="title">
          {{ $t('peiSongFangShi') }}
        </view>
        <view class="text">
          <radio-group @change="deliveryWay=$event.detail.value/1">
            <label class="radio"><radio
              value="0"
              :checked="deliveryWay === 0"
              color="#082ba6"
              style="transform:scale(0.8)"
            />{{ $t('selfDeliver') }}</label>
            &nbsp;&nbsp;
            <label class="radio">
              <radio
                value="1"
                color="#082ba6"
                :checked="deliveryWay === 1"
                :disabled="stationDeliveryType !== 1 || isDisableDadaDelivery"
                style="transform:scale(0.8)"
              />{{ $t('dadaDeliver') }}
            </label>
          </radio-group>
        </view>
      </view>
      <view
        v-if="deliveryMethod === 1"
        class="courier-info-item"
      >
        <view class="title">
          {{ $t('peiSongFangShi') }}
        </view>
        <view class="text">
          <radio-group @change="deliveryType=$event.detail.value/1">
            <label class="radio"><radio
              value="0"
              :checked="deliveryType == 0"
              color="#082ba6"
              style="transform:scale(0.8)"
              :disabled="isPrint!==1"
            />{{ $t('xianShangFaHuo') }}</label>
            &nbsp;&nbsp;
            <label
              class="radio"
            >
              <radio
                value="1"
                color="#082ba6"
                :checked="deliveryType == 1"
                style="transform:scale(0.8)"
              />{{ $t('xianXiaFaHuo') }}
            </label>
          </radio-group>
        </view>
      </view>
      <view
        v-if="deliveryMethod === 1"
        class="courier-info-item"
        @tap="toSelecteDelivery"
      >
        <view class="title">
          {{ $t('wuLiuGongSi') }}
        </view>
        <view
          v-if="deliveryType===1"
          :class="['text', selectedDelivery.dvyName ? '' : 'logistics']"
        >
          {{ selectedDelivery.dvyName || $t('qingXuanZeWuLiuGongSi') }}
        </view>
        <view
          v-if="deliveryType===0"
          :class="['text', deliveryCompanyTypeConfig?.deliveryCompanyName ? '' : 'logistics']"
        >
          {{ deliveryCompanyTypeConfig?.deliveryCompanyName || $t('qingXuanZeWuLiuGongSi') }}
        </view>
        <view class="icon" />
      </view>
      <view
        v-if="deliveryMethod === 1 && deliveryType!==0"
        class="courier-info-item"
      >
        <view class="title">
          {{ $t('kuaiDiDanHao-0') }}
        </view>
        <view class="text">
          <input
            v-model="dvyFlowId"
            maxlength="20"
            type="text"
            class="input-text"
            :placeholder="$t('qingShuRuKuaiDiDanHao')"
          >
        </view>
      </view>

      <!-- 线上发货 -->
      <template v-if="deliveryMethod === 1 && deliveryType===0 && deliveryCompanyTypeConfig.isConfig===1">
        <view
          class="courier-info-item min-height"
          @tap="onSelectShopAddr"
        >
          <view class="title">
            {{ $t('faHuoDiZhi') }}
          </view>
          <view :class="['text', selectShopAddr?.printAddr ? '' : 'logistics']">
            {{ selectShopAddr?.printAddr || $t('qingXuanZeFaHuoDiZhi') }}
          </view>
          <view class="icon" />
        </view>
        <view
          class="courier-info-item"
        >
          <view class="title">
            {{ $t('faHuoLeiXing') }}
          </view>
          <view :class="['text']">
            <radio-group @change="isPrint=$event.detail.value/1">
              <label class="radio"><radio
                label="1"
                :checked="isPrint === 1"
                color="#082ba6"
                style="transform:scale(0.8)"
              />{{ $t('daYinMianDan') }}</label>
            </radio-group>
          </view>
        </view>
        <view
          class="courier-info-item min-height"
          @tap="onSelectPrinter"
        >
          <view class="title">
            {{ $t('daYinJi') }}
          </view>
          <view :class="['text', selerctPrinter?.printerName ? '' : 'logistics']">
            {{ selerctPrinter?.printerName || $t('qingXuanZe') }}
          </view>
          <view class="icon" />
        </view>
      </template>
      <!-- end 线上发货 -->
    </view>
    <view class="order-shipping-footer">
      <common-btn
        :btn-config="shippingBtnConfig"
        @handle-click-btn="handleShipping"
      />
    </view>
    <select-popup
      v-if="showSelecMode"
      :value="deliveryMethod"
      :data="shippingMethods"
      @submit-data="getDeliveryMethod"
      @cancal="cancal"
    />
    <!-- 发货地址 -->
    <select-popup
      v-if="showShopAdd && deliveryCompanyTypeConfig.shopAddrList"
      :value="selectShopAddr?.outletConfigId "
      :data="computedShopAddrList"
      @submit-data="getShopAddr"
      @cancal="showShopAdd=false"
    />
    <!-- 打印机选择 -->
    <select-popup
      v-if="showPrinter"
      :value="printerId"
      :data="computedPrinterList"
      @submit-data="getPrinter"
      @cancal="showPrinter=false"
    />
  </view>
</template>

<script setup>
import { computed, nextTick, reactive } from 'vue'

const Data = reactive({
  showSelecMode: false,
  shippingMethods: [
    {
      name: $t('kuaiDiPeiSong-0'),
      value: 1
    },
    {
      name: $t('wuXuKuaiDi'),
      value: 3,
      ishidden: 1
    },
    {
      name: $t('tongChengPeiSong'),
      value: 4,
      ishidden: 1
    }
  ],
  deliveryMethod: 1,
  prodIds: [],
  orderNumber: '',
  orderId: '',
  orderInfo: {},
  userAddrOrder: {},
  // 当前选择的物流公司信息
  selectedDelivery: {},
  // 输入的运单号
  dvyFlowId: '',
  shippingBtnConfig: {
    btnText: $t('faHuo')
  },
  orderStatus: { 1: $t('tuiKuanShenQingZhong'), 5: $t('tuiKuanChengGong-0'), 6: $t('maiJiaCheHuiShenQing'), 7: $t('shangJiaJuJue'), '-1': $t('tuiKuanGuanBi') }
})

const {
  showSelecMode,
  shippingMethods,
  deliveryMethod,
  orderInfo,
  userAddrOrder,
  selectedDelivery,
  dvyFlowId,
  shippingBtnConfig,
  orderStatus
} = toRefs(Data)

const findDeliveryMethod = computed(() => {
  const index = Data.shippingMethods.findIndex(
    (item) => item.value === Data.deliveryMethod
  )
  return index
})

onLoad((options) => {
  Data.orderNumber = options.orderNumber
  Data.orderId = options.orderId
  // 订单详情
  getOrderInfoById()
  nextTick(() => {
    onGetOutletConfigList()
    onGetPrinterList()
    onGetQuick100()
  })
})

onShow(() => {
  const _bbcSelectedDelivery = uni.getStorageSync('bbcSelectedDelivery')

  if (_bbcSelectedDelivery?.isOnlineDelivery) { // 线上发货地址
    deliveryCompanyTypeConfig.value = _bbcSelectedDelivery || {
      deliveryCompanyType: null,
      deliveryCompanyName: null,
      isConfig: null,
      isDefault: null,
      shopAddrList: []
    }
  } else { // 线上发货
    Data.selectedDelivery = _bbcSelectedDelivery || {}
  }
  uni.setNavigationBarTitle({
    title: $t('faHuo')
  })
})

/**
 * 发货
 */
const deliveryWay = ref(0) // 同城配送配送方式 0-自行配送 1-达达配送
const handleShipping = () => {
  const endShipOrder = Data.orderInfo.orderItems.filter(x => {
    return x.prodCount > 0 && (x.status !== 0 && (!x.returnMoneySts || x.returnMoneySts < 0 || x.returnMoneySts > 5))
  })
  if (!Data.prodIds.length) {
    uni.showToast({
      title: $t('qingXuanZeYaoFaHuoDeShangPin'),
      icon: 'none'
    })
    return
  }
  Data.dvyFlowId = Data.dvyFlowId.trim()
  if (Data.deliveryMethod === 1 && deliveryType.value === 1 && (!Data.selectedDelivery.dvyId || !Data.dvyFlowId)) {
    uni.showToast({
      title: $t('qingWanShanWuLiuXinXi'),
      icon: 'none'
    })
    return
  }
  const reg = /^[a-zA-Z0-9]{4,30}$/
  if (Data.deliveryMethod === 1 && deliveryType.value === 1) {
    if (!reg.test(Data.dvyFlowId)) {
      uni.showToast({
        title: $t('qingShuRuZhengQueDeKuaiDiDanHao'),
        icon: 'none'
      })
      return
    }
  }
  if (Data.deliveryMethod === 1 && deliveryType.value === 0) {
    if (deliveryCompanyTypeConfig.value.isConfig === 0) {
      uni.showToast({
        title: $t('qingDaoShangJiaPcDuanWangDianPeiZhiChuKaiTongXiangGuanWuLiuPeiZhi'),
        icon: 'none'
      })
      return
    }
    if (!selectShopAddr.value) {
      uni.showToast({
        title: $t('qingXuanZeFaHuoDiZhi'),
        icon: 'none'
      })
      return
    }
    if (!selerctPrinter.value) {
      uni.showToast({
        title: $t('qingXuanZeDaYinJi'),
        icon: 'none'
      })
      return
    }
  }
  uni.showLoading({
    mask: true
  })

  http.request({
    url: '/order/delivery/orderItemsDelivery',
    method: 'PUT',
    hasCatch: true,
    data: {
      deliveryType: Data.deliveryMethod !== 1 ? Data.deliveryMethod : deliveryType.value,
      dvyId: Data.selectedDelivery.dvyId,
      dvyFlowId: Data.dvyFlowId ? Data.dvyFlowId : null,
      orderNumber: Data.orderNumber,
      selectOrderItems: Data.orderInfo.orderItems.filter(el => Data.prodIds.includes(el.orderItemId)),
      outletConfigId: outletConfigId.value,
      printerId: printerId.value,
      deliveryCompanyType: deliveryCompanyTypeConfig.value.deliveryCompanyType,
      deliveryWay: deliveryWay.value // 配送方式 0 自行配送 1 达达配送
    }
  }).then(() => {
    uni.hideLoading()
    uni.showToast({
      title: $t('caoZuoChengGong-1'),
      icon: 'none',
      mask: true
    })
    setTimeout(() => {
      if (Data.prodIds.length === endShipOrder.length) {
        // #ifdef H5
        history.back()
        // #endif
        // #ifndef H5
        uni.navigateBack()
        // #endif
      } else {
        uni.removeStorageSync('bbcSelectedDelivery')
        uni.redirectTo({
          url: `/package-order/pages/order-shipping/order-shipping?orderNumber=${Data.orderInfo.orderNumber}`
        })
      }
    }, 1200)
  }).catch((e) => {
    if (e.code === 'A00001' || e.code === 'A00002') {
      const msg = (e.code === 'A00001' && e.msg?.includes($t('gaiSheBeiBianMaBuCunZaiQingJianChaShiFouZhengQue'))) ? $t('gaiDaYinJiSheBeiBianMaBuCunZaiQingDaoShangJiaPcDuanYingJianSheBeiChuJianCha') : e.msg
      uni.showToast({
        title: msg,
        icon: 'none',
        duration: 1500
      })
    }
  }).finally(() => {
    uni.hideLoading()
  })
}

/**
 * 修改商品数量
 * @param {Number} index 商品项索引
 * @param {Number} changeCount 变更数量
 */
const handleChangeProdCount = (index, changeCount) => {
  // 当前设置的发货数量
  const changeNum = +Data.orderInfo.orderItems[index].changeNum
  // 可发货数量
  const prodCount = Data.orderInfo.orderItems[index].prodCount
  let count = 1
  if (prodCount === 0) return

  // 增加
  if (changeCount > 0) {
    count = (changeNum + changeCount) > prodCount ? prodCount : changeNum + changeCount
  } else {
    // 减少
    count = changeNum > 1 ? changeNum - 1 : 1
  }
  Data.orderInfo.orderItems[index].changeNum = count
  resetShippingMethods()
}

const isDisableDadaDelivery = ref(false)
watch(isDisableDadaDelivery, (val) => {
  if (deliveryWay.value === 1 && val) {
    deliveryWay.value = 0
  }
})
const resetShippingMethods = () => {
  let isDisableDadaDeliveryTemp = false
  let flag = 0
  const tempList = Data.orderInfo.orderItems.filter(el => (el.returnMoneySts && el.returnMoneySts != 5) || !el.returnMoneySts)
  if (Data.orderInfo.dvyType === 4 || Data.prodIds.length !== tempList.length) {
    isDisableDadaDeliveryTemp = Data.prodIds.length !== tempList.length
    flag = 1
    Data.deliveryMethod = Data.orderInfo.dvyType !== 1 ? 4 : Data.orderInfo.dvyType
  }
  for (let i = 0; i < tempList.length; i++) {
    const item = tempList[i]
    if (item.changeNum !== item.prodCount || item.status !== -1) {
      flag = 1
      isDisableDadaDeliveryTemp = true
      break
    }
  }
  isDisableDadaDelivery.value = isDisableDadaDeliveryTemp
  Data.shippingMethods[1].ishidden = flag || undefined
  if (flag && Data.deliveryMethod === 3) {
    Data.deliveryMethod = Data.orderInfo.dvyType !== 1 ? 4 : Data.orderInfo.dvyType
  }
}

/**
 * 输入框失焦
 */
const checKCount = ($event, index) => {
  if (+$event.detail.value < 1) {
    Data.orderInfo.orderItems[index].changeNum = 1
  }
  if (+$event.detail.value > Data.orderInfo.orderItems[index].prodCount) {
    Data.orderInfo.orderItems[index].changeNum = Data.orderInfo.orderItems[index].prodCount
  }
  resetShippingMethods()
}

/**
 * 获取订单详情
 */
const stationDeliveryType = ref(0) // 是否达达配送
const getOrderInfoById = () => {
  http.request({
    url: `/order/delivery/getOrderItemUnDelivery/${Data.orderNumber}`,
    method: 'GET'
  }).then(({ data: res }) => {
    res.orderItems = res.orderItems.filter(i => i.mold !== 2)
    res.orderItems.forEach(prod => {
      prod.changeNum = prod.prodCount
    })
    Data.userAddrOrder = res.userAddrOrder
    if (res.dvyType !== 1) {
      Data.deliveryMethod = 4
      changeShip()
    }
    stationDeliveryType.value = res.stationDeliveryType
    Data.orderInfo = res
    resetShippingMethods()
  })
}

const changeShip = () => {
  Data.shippingMethods = [{
    name: $t('kuaiDiPeiSong-0'),
    value: 1,
    ishidden: 1
  },
  {
    name: $t('wuXuKuaiDi'),
    value: 3,
    ishidden: 1
  },
  {
    name: $t('tongChengPeiSong'),
    value: 4
  }]
}

// 更换地址
const addrEditor = () => {
  uni.setStorageSync('bbcUserAddrOrder', Data.orderInfo.userAddrOrder)
  uni.redirectTo({
    url: `/package-order/pages/modify-address/modify-address?orderNumber=${Data.orderNumber}&orderId=${Data.orderInfo.orderId}&shipping=1&dvyType=${Data.orderInfo.dvyType}`
  })
}

const queryProd = (orderItemId) => {
  const index = Data.prodIds.findIndex((item) => item === orderItemId)
  return index >= 0
}

/**
 * 选择要发货的商品
 * @param {Number} orderItemId 商品订单项id
 * @param {Boolean} canShipping 是否可发货
 */
const selectProd = (orderItemId, canShipping) => {
  if (!canShipping) return
  const index = Data.prodIds.findIndex((item) => item === orderItemId)
  if (index >= 0) {
    Data.prodIds.splice(index, 1)
  } else {
    Data.prodIds.push(orderItemId)
  }
  resetShippingMethods()
}

// 选择物流弹框
const selecMode = () => {
  Data.showSelecMode = true
}

const cancal = () => {
  Data.showSelecMode = false
}

const getDeliveryMethod = (value) => {
  Data.deliveryMethod = value
  Data.showSelecMode = false
  Data.selectedDelivery = {}
}

const toSelecteDelivery = () => {
  uni.navigateTo({
    url: `/package-order/pages/select-logistics/select-logistics?dvyId=${Data.selectedDelivery.dvyId}&isOnlineDelivery=${deliveryType.value}`
  })
}

const deliveryType = ref(0)// {enum} 0,1 配送方式

const outletConfigId = ref(null)
const outletConfigList = ref([])
const deliveryCompanyTypeConfig = ref({
  deliveryCompanyType: null,
  deliveryCompanyName: null,
  isConfig: null,
  isDefault: null,
  shopAddrList: []
})
// 获取网点列表
const onGetOutletConfigList = () => {
  http.request({
    url: '/shop/outletConfig/listOutletConfig',
    method: 'GET'
  }).then(({ data }) => {
    outletConfigList.value = data
    if (deliveryCompanyTypeConfig.value.deliveryCompanyType !== null) {
      data.forEach(el => {
        if (el.deliveryCompanyType === deliveryCompanyTypeConfig.value.deliveryCompanyType) {
          deliveryCompanyTypeConfig.value = el
          el.shopAddrList?.forEach(val => {
            if (val.isDefault === 1) {
              outletConfigId.value = val.outletConfigId
            }
          })
        }
      })
      return
    }
    data.forEach(el => {
      if (el.isDefault === 1) {
        // 设置选中默认配置
        deliveryCompanyTypeConfig.value = el
        el.shopAddrList.forEach(val => {
          if (val.isDefault === 1) {
            outletConfigId.value = val.outletConfigId
          }
        })
      }
    })
  })
}

const computedShopAddrList = computed(() => {
  if (deliveryCompanyTypeConfig.value.shopAddrList) {
    return deliveryCompanyTypeConfig.value.shopAddrList.map((e) => {
      return {
        name: e.printAddr,
        value: e.outletConfigId
      }
    })
  } else {
    return []
  }
})
const selectShopAddr = computed(() => {
  return deliveryCompanyTypeConfig.value?.shopAddrList?.find(el => el.outletConfigId === outletConfigId.value)
})
const showShopAdd = ref(false)
const onSelectShopAddr = () => {
  showShopAdd.value = true
}
const getShopAddr = (value) => {
  showShopAdd.value = false
  outletConfigId.value = value
}

const printerId = ref(null)
const printerList = ref([])
const selerctPrinter = computed(() => {
  return printerList.value?.find(el => el.printerId === printerId.value)
})
const computedPrinterList = computed(() => {
  return printerList.value?.map(e => ({
    name: e.printerName,
    value: e.printerId
  })) || []
})
// 获取打印机列表
const onGetPrinterList = () => {
  http.request({
    url: '/shop/printer/listPrinter',
    method: 'GET'
  }).then(({ data }) => {
    printerList.value = data
    data.forEach(el => {
      if (el.isDefault === 1) {
        // 设置选中默认配置
        printerId.value = el.printerId
      }
    })
  })
}

const showPrinter = ref(false)
//  show选择打印机
const onSelectPrinter = () => {
  if (!computedPrinterList.value.length) {
    uni.showToast({
      title: $t('qingDaoShangJiaPcDuanYingJianSheBeiChuPeiZhiDaYinJi'),
      icon: 'none'
    })
    return
  }
  showPrinter.value = true
}
// 获取选择打印机id
const getPrinter = (value) => {
  showPrinter.value = false
  printerId.value = value
}

// 获取快递100配置
const isPrint = ref(0)
const onGetQuick100 = () => {
  http.request({
    url: '/sys/shopConfig/quick100',
    method: 'GET'
  }).then((res) => {
    isPrint.value = res.data ? 1 : 0
    deliveryType.value = res.data ? 0 : 1
  })
}

</script>

<style lang="scss" scoped>
@use "order-shipping";
</style>
