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

  https://www.mall4j.com/

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

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

<template>
  <view class="Mall4j page-modify-logistics">
    <view class="logistics">
      <view
        v-for="(item,i) in dateForm"
        :key="i"
        class="good-logistics"
      >
        <view class="good-info">
          <view class="package">
            {{ $t('baoGuo') }}{{ i + 1 }}
          </view>
          <view class="good-num">
            {{ $t('gongTotalcountJianShangPin').replace('[totalCount]', item.totalCount) }}
          </view>
        </view>
        <view class="logistics-info">
          <view class="list">
            <view class="left">
              <text class="info">
                {{ $t('faHuoFangShi') }}
              </text>
              <text class="content">
                {{ shippingMethods[shippingIndex[i]] ? shippingMethods[shippingIndex[i]].name : '' }}
              </text>
            </view>
            <!-- <text class="iconfont">&#xe775;</text> -->
          </view>
          <view
            v-if="[0,1].includes(item.deliveryType)"
            class="list"
          >
            <view class="left">
              <text class="info">
                {{ $t('peiSongFangShi') }}
              </text>
              <text class="content">
                {{ [$t('xianShangFaHuo'), $t('xianXiaFaHuo')][item.deliveryType] }}
              </text>
            </view>
            <!-- <text class="iconfont">&#xe775;</text> -->
          </view>
          <view
            v-if="[0,1].includes(item.deliveryType)"
            class="list"
            @tap="item.deliveryType===1?toSelecteDelivery(i):void(0)"
          >
            <view class="left">
              <text class="info">
                {{ $t('kuaiDiGongSi') }}
              </text>
              <text
                v-if="item.deliveryType===1"
                class="content"
                :style="{color:selectedDeliveryArr[i].dvyName ? '' : '#999999'}"
              >
                {{ selectedDeliveryArr[i].dvyName || $t('qingXuanZeWuLiuGongSi') }}
              </text>
              <text
                v-else
                class="content"
              >
                {{ deliveryCompanyType[item.dvyId-1].label }}
              </text>
            </view>
            <!-- <text class="iconfont">&#xe775;</text> -->
            <view
              v-if="item.deliveryType===1"
              class="icon"
            />
          </view>
          <view
            v-if="[0,1].includes(item.deliveryType)"
            class="list"
          >
            <view class="left">
              <text class="info">
                {{ $t('kuaiDiDanHao-0') }}
              </text>
              <input
                v-model="item.dvyFlowId"
                class="input"
                type="text"
                :disabled="item.deliveryType === 0"
                :placeholder="$t('qingShuRuKuaiDiDanHao')"
                placeholder-class="placeholder-class"
              >
            </view>
            <!-- <text class="iconfont" @tap="deliveryModeOpen">&#xe775;</text> -->
          </view>
        </view>
      </view>
    </view>
    <button
      type="primary"
      class="btn"
      @tap="submit"
    >
      {{ $t('queRenXiuGai') }}
    </button>
    <!-- 选择配送方式 -->
    <select-popup
      v-if="showSelecMode"
      :value="dateForm[index].deliveryType"
      :data="shippingMethods"
      @submit-data="getDeliveryMethod"
      @cancal="cancal"
    />
  </view>
</template>

<script setup>
import { reactive } from 'vue'

const Data = reactive({
  orderNumber: '',
  selectedDelivery: {},
  selectedDeliveryArr: [],
  showSelecMode: false,
  shippingMethods: [
    {
      name: $t('kuaiDiPeiSong'),
      value: 0
    },
    {
      name: $t('kuaiDiPeiSong-0'),
      value: 1
    },
    {
      name: $t('wuXuKuaiDi'),
      value: 3
    }
  ],
  dateForm: [],
  index: 0,
  shippingIndex: [],
  isFirst: true
})
const deliveryCompanyType = [{
  value: 1,
  label: $t('shunFengSuYun')
}, {
  value: 2,
  label: $t('jingDongKuaiDi')
}, {
  value: 3,
  label: $t('yuanTongSuDi')
}, {
  value: 4,
  label: $t('yunDaKuaiDi')
}, {
  value: 5,
  label: $t('zhongTongKuaiDi')
}, {
  value: 6,
  label: $t('shenTongKuaiDi')
}, {
  value: 7,
  label: $t('baiShiKuaiDi')
}, {
  value: 8,
  label: 'EMS'
}]

const { selectedDeliveryArr, showSelecMode, shippingMethods, dateForm, index, shippingIndex } = toRefs(Data)

const { proxy } = getCurrentInstance()

watch(() => Data.selectedDelivery, (val) => {
  Data.selectedDeliveryArr[Data.index] = val
  Data.dateForm[Data.index].dvyId = val.dvyId
  proxy.$forceUpdate()
}, { deep: true })

onLoad((options) => {
  Data.orderNumber = options.orderNumber
  getOrderDeliveriesById()
})

onShow(() => {
  if (uni.getStorageSync('bbcSelectedDelivery') && Data.isFirst === false) {
    Data.selectedDelivery = uni.getStorageSync('bbcSelectedDelivery')
    uni.removeStorageSync('bbcSelectedDelivery')
  }
  Data.isFirst = false
  uni.setNavigationBarTitle({
    title: $t('xiuGaiWuLiu')
  })
})

// 订单包裹物流详情
const getOrderDeliveriesById = () => {
  http.request({
    url: `/order/delivery/getOrderDeliveries/${Data.orderNumber}`,
    method: 'PUT'
  }).then(({ data: res }) => {
    if (res) {
      Data.dateForm = res
      res.forEach(item => {
        const index = Data.shippingMethods.findIndex(el => {
          return el.value === item.deliveryType
        })
        Data.shippingIndex.push(index)
        Data.selectedDeliveryArr.push({ dvyId: item.dvyId })
        let count = 0
        item.orderItems.forEach(el => {
          count += el.prodCount
        })
        item.totalCount = count
      })
      getDeliveryList()
    }
  })
}

/**
     * 获取物流公司列表
     */
const getDeliveryList = () => {
  http.request({
    url: '/admin/delivery/list',
    method: 'GET'
  }).then(({ data }) => {
    data.forEach((item) => {
      Data.selectedDeliveryArr.forEach(el => {
        if (item.dvyId === el.dvyId) {
          el.dvyName = item.dvyName
        }
      })
    })
  })
}

const getDeliveryMethod = (value) => {
  Data.dateForm[Data.index].deliveryType = value
  Data.shippingIndex[Data.index] = Data.shippingMethods.findIndex(item => {
    return item.value === value
  })
  Data.showSelecMode = false
}

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

// 选择物流公司
const toSelecteDelivery = (index) => {
  Data.index = index
  uni.navigateTo({
    url: `/package-order/pages/select-logistics/select-logistics?dvyId=${Data.selectedDeliveryArr[Data.index].dvyId}`
  })
}

// 修改订单包裹物流
const submit = () => {
  const reg = /^[a-zA-Z0-9]{4,30}$/
  const flag = Data.dateForm.some(item => {
    if (item.deliveryType === 1) {
      item.dvyFlowId = item.dvyFlowId.trim()
      if (item.dvyFlowId.length === 0) {
        uni.showToast({
          title: $t('kuaiDiDanHaoBuNengWeiKong'),
          icon: 'none'
        })
        return true
      } else if (!reg.test(item.dvyFlowId)) {
        uni.showToast({
          title: $t('qingShuRuZhengQueDeKuaiDiDanHao'),
          icon: 'none'
        })
        return true
      }
    }
    return false
  })

  if (flag) return
  uni.showLoading({
    mask: true
  })
  http.request({
    url: '/order/delivery/updateOrderDeliveries',
    method: 'PUT',
    data: {
      deliveryOrders: Data.dateForm
    }
  }).then(() => {
    uni.hideLoading()
    uni.showToast({
      title: $t('caoZuoChengGong-1'),
      icon: 'none',
      success: () => {
        setTimeout(() => {
          uni.navigateBack({
            delta: 1
          })
        }, 1500)
      }
    })
  })
}
</script>

<style lang="scss" scoped>
@use "modify-logistics";
</style>
