<template>
  <view class="new-sku-cell">
    <view class="flex-wrapper">
      <view class="new-sku-cell-left">
        <!-- 促 -->
        <view
          class="promotion-earning-icon"
          v-if="!isNewPriceDisplay && sku.actPrice"
        ></view>
        <view class="spec">{{ sku.specQuality }}{{ sku.specUnit }}</view>
        <view
          class="price"
          :class="{ 'promotion-price': !isNewPriceDisplay && sku.actPrice }"
        >
          ¥{{ comparePrice }}
        </view>
      </view>
      <view class="new-sku-cell-right">
        <view
          @click="updateSaleStatus(1)"
          class="btn-status"
          :class="{ active: sku.storeSkuStatus }"
        >
          可售
        </view>
        <view
          @click="updateSaleStatus(2)"
          class="btn-status"
          :class="{ active: !sku.storeSkuStatus && !autoSaleAt }"
        >
          不可售
        </view>
        <view
          @click="updateSaleStatus(3)"
          class="btn-status"
          :class="{ active: !sku.storeSkuStatus && autoSaleAt }"
        >
          临时不可售
        </view>
      </view>
    </view>

    <view class="flex-wrapper-3">
      <view   @tap="openDialog(skuName,sku,'stock')"> 
        库存：{{(sku as AnyObject).stock}}
        <jx-icon icon="shuxie" color="#999" :size="24" />
      </view>
      <view class="locationCode" @tap="openDialog(skuName,sku,'locationCode')">
        货架码：{{(sku as AnyObject).locationCode && (sku as AnyObject).locationCode !== 'EMPTY_VALUE' ? (sku as AnyObject).locationCode : ''}}
        <jx-icon icon="shuxie" color="#999" :size="24" />
      </view>          
    </view>

    <view class="flex-wrapper-2">
      <view class="cell-bottom">{{ sku.comment ? sku.comment : '' }}</view>
      <view class="auto-at" v-if="autoSaleAt">
        该规格将在 {{ autoSaleAt }} 可售
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import shopping from '@/api/https/shopping'
import { store } from '@/store'
import { getStorage } from '@/utils/storage'
import toast from '@/utils/toast'
import { isNullDate, timeFormatD, timeFormatHMS } from '@/utils/tools'
import { computed, ref } from 'vue'

/**
 * props
 */
interface PropType {
  id: number
  actPrice: number
  specQuality: string
  specUnit: string
  storeSkuStatus: string
  comment: string
  earningPrice: number
  price: number
  autoSaleAt: string
}
interface SkuNameType {
  id: number
}
interface SkuType {
  sku: PropType
  skuName: SkuNameType
}
const props = defineProps<SkuType>()

/**
 * emit
 */
const emit = defineEmits<{
  (e: 'refresh', id: number): void
  (e: 'openDialog', obj: AnyObject): void
}>()

function openDialog(skuName: AnyObject,sku:AnyObject,type:String) {
  let payload = {
    nameID:skuName.id,
    Skus:[{
        skuID:sku.id,
        stock:sku.stock,
        locationCode:sku.locationCode && sku.locationCode !== 'EMPTY_VALUE' ? sku.locationCode : ''
      }]
  }
  emit('openDialog', {payload,type,name:skuName.name})
}

/**
 * 格式化价格
 */
const comparePrice = computed(() => {
  let sku = props.sku
  if (isNewPriceDisplay && sku.actPrice) {
    return (sku.earningPrice / 100).toFixed(2)
  } else {
    return (sku.price / 100).toFixed(2)
  }
})

/**
 * 是否显示原价格(读取vuex)
 */
const isNewPriceDisplay = computed(() => {
  return store.getters['storeInfo/isNewPriceDisplay']
})

/**
 * 自动销售时间
 */
const autoSaleAt = computed(() => {
  if (isNullDate(props.sku.autoSaleAt)) {
    return false
  } else {
    return timeFormatHMS(props.sku.autoSaleAt)
  }
})

let identifying = 0
/**
 * 设置商品可售状态
 */
function updateSaleStatus(type: number) {
  // 临时不可售时不能操作不可售
  if (identifying == 3 && type == 2) {
    return uni.jxAlert({
      title: '提示',
      content:
        '【临时不可售】状态下不能设置为【不可售】，只能从【可售】切换到【不可售】',
    })
  }
  // 相同状态不操作
  if (type == identifying) return false
  identifying = type
  updateStatus(type, props.sku.id)
}

/**
 * 通过接口修改商品可售状态
 */
async function updateStatus(type: number, id: number) {
  try {
    if (type == 3) {
      // 临时不可售
      let data = {
        storeIDs: JSON.stringify([+getStorage('storeID')]),
        payload: JSON.stringify([
          {
            skuID: id,
            isSale: -1,
          },
        ]),
        isAsync: false,
        autoSaleAt: computedAutoSaleAt(),
      }
      let res = await shopping.update_stores_skus_sale(data)
      if (res.code == 0) {
        toast('操作成功')
      } else {
        toast('操作失败', 2)
      }
    } else {
      let data = {
        storeIDs: JSON.stringify([+getStorage('storeID')]),
        payload: JSON.stringify([
          {
            nameID: props.skuName.id,
            skus: [
              {
                skuID: id,
                isSale: +type == 1 ? 1 : -1,
              },
            ],
          },
        ]),
      }
      let res = await shopping.update_stores_skus(data)
      if (res.code == 0) {
        toast('操作成功')
      } else {
        toast('操作失败', 2)
      }
    }
  } catch (error) {
    toast('系统异常')
  } finally {
    emit('refresh', props.skuName.id)
  }
}

/**
 * 计算自动可售时间
 */
function computedAutoSaleAt() {
  let now = +new Date()
  let autoTime = +new Date(
    `${timeFormatD(+new Date())} ${autoSaleAtTimer.value}`
  )
  if (now < autoTime) {
    return `${timeFormatD(+new Date())} ${autoSaleAtTimer.value}`
  } else {
    return `${timeFormatD(+new Date() + 24 * 3600 * 1000)} ${
      autoSaleAtTimer.value
    }`
  }
}

/**
 * 获取系统可售时间
 */
const autoSaleAtTimer = computed(() => {
  // 如遇错误到以往git版本中查看
  return '20:25:00'
})
</script>

<style lang="scss" scoped>
@import './skuNameID.scss';
</style>