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

https://www.mall4j.com/

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

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

<template>
  <view class="Mall4j page-prod-management">
    <view
      class="prod-header"
      :class="[showShadow ? 'shadow' : '']"
    >
      <view
        class="search"
        @click="closeMask"
      >
        <search-bar
          :key-wrod="dataForm.prodName"
          :placeholder="$t('qingShuRuShangPinMingCheng-0')"
          @handle-search="handleSearch"
        />
      </view>
      <view
        class="prod-status-bar"
        @click="closeMask"
      >
        <status-bar
          :status-list="statusList"
          @handle-change-sts="handleChangeSts"
        />
      </view>
    </view>
    <view class="prod-list-con">
      <prod-lists
        v-if="prodList.length > 0"
        ref="prodListRef"
        :is-batch-oper="isBatchOper"
        :data-form="dataForm"
        :prod-list="prodList"
        :close-mask="closeMask"
        :batch-oper-btn-config="batchOperBtnConfig"
        @handle-switch-batch-oper-sts="handleSwitchBatchOperSts"
        @delete-prod="deleteProd"
        @set-status="setStatus"
        @batch-set-status="batchSetStatus"
        @batch-delete-prod="batchDeleteProd"
      />
      <empty-tips
        v-if="isLoaded && prodList.length === 0"
        :tips-list="prodEmptyTips"
      />
      <view class="prod-bottom" />
    </view>
    <view class="footer-btn">
      <common-btn
        :btn-config="prodManaBtnConfig"
        @handle-click-more-btn="handleClickMoreBtn"
      />
    </view>
  </view>
</template>

<script setup>
import { onMounted } from 'vue'
import prodLists from '../../components/prod-list/prod-list.vue'

const Data = reactive({
  isLoaded: false, // 列表是否加载完毕
  // 是否正在进行批量操作
  isBatchOper: false,
  // 按钮配置
  prodManaBtnConfig: {
    btnList: [
      {
        btnText: $t('piLiangCaoZuo'),
        isPlain: true,
        isShow: false
      },
      {
        btnText: $t('faBuShangPin'),
        isPlain: false,
        isShow: util.isAuthorities('prod:prod:save')
      }
    ]
  },
  prodEmptyTips: [$t('zanWuXiangGuanShangPin')],
  statusList: [
    {
      label: $t('quanBu'),
      sts: ''
    },
    {
      label: $t('shangJia'),
      sts: 1
    },
    {
      label: $t('xiaJia'),
      sts: 0
    },
    {
      label: $t('daiShenHe'),
      sts: 6
    },
    {
      label: $t('weiGuiXiaJia'),
      sts: 2
    },
    {
      label: $t('weiGuiXiaJiaDaiShenHe'),
      sts: 3
    }
  ],
  batchOperBtnConfig: {},
  showShadow: false,
  prodList: [], // 商品数据
  dataForm: {
    prodName: '',
    status: '',
    pages: 1,
    current: 1,
    prodId: ''
  }
})

const { isLoaded, isBatchOper, prodManaBtnConfig, prodEmptyTips, statusList, batchOperBtnConfig, showShadow, prodList, dataForm } = toRefs(Data)

onLoad((options) => {
  if (options.prodId) {
    Data.dataForm.prodId = options.prodId
    getProdList()
  } else {
    getProdList()
  }
})

onMounted(() => {
  changeBtnTip()
})

onReachBottom(() => {
// 批量操作时不响应不加载更多商品
  if (Data.isBatchOper) return
  if (Data.dataForm.pages > Data.dataForm.current) {
    ++Data.dataForm.current
    getProdList()
  }
})

onShow(() => {
// 加载导航标题
  uni.setNavigationBarTitle({
    title: $t('shangPinGuanLi')
  })
})

onPageScroll((e) => {
  Data.showShadow = e.scrollTop > 40
})

/**
 * 切换批量操作状态
 */
const handleSwitchBatchOperSts = () => {
  Data.isBatchOper = !Data.isBatchOper
}

/**
 * 切换顶部状态
 */
const handleChangeSts = (sts) => {
  Data.dataForm.status = sts
  Data.dataForm.current = 1
  getProdList()
  changeBtnTip()
}

// 切换批量按钮
const changeBtnTip = () => {
  let obj = {
    isShow: util.isAuthorities('prod:prod:batchDelete'),
    btnText: $t('shanChu')
  }
  if (Data.dataForm.status === 1) {
    obj = {
      btnList: [
        {
          btnText: $t('xiaJia-0'),
          isShow: util.isAuthorities('prod:prod:batchStatus')
        },
        {
          btnText: $t('shanChu'),
          isShow: util.isAuthorities('prod:prod:batchDelete')
        }
      ]
    }
  } else if (Data.dataForm.status === 0) {
    obj = {
      btnList: [
        {
          btnText: $t('shangJia-0'),
          isShow: util.isAuthorities('prod:prod:batchStatus')
        },
        {
          btnText: $t('shanChu'),
          isShow: util.isAuthorities('prod:prod:batchDelete')
        }
      ]
    }
  }
  Data.batchOperBtnConfig = obj
  Data.prodManaBtnConfig.btnList[0].isShow = isButBatch()
}

const isButBatch = () => {
  if (Data.batchOperBtnConfig.isShow) return true
  if (Data.batchOperBtnConfig.btnList) return Data.batchOperBtnConfig.btnList.some(e => e.isShow)
  return false
}

const prodListRef = ref()
/**
 * 获取商品列表
 */
const getProdList = () => {
  uni.showLoading()
  Data.isLoaded = false
  http.request({
    url: '/admin/search/prod/page',
    method: 'GET',
    data: {
      current: Data.dataForm.current,
      size: 20,
      keyword: Data.dataForm.prodName,
      prodId: Data.dataForm.prodId,
      status: Data.dataForm.status
    }
  }).then(({ data: res }) => {
    Data.isLoaded = true
    res.records.forEach(order => {
      order.price = util.priceAdd0(order.price)
      order.pic = util.checkFileUrl(order.pic) || '/static/images/def.png'
    })

    let list = []
    if (Data.dataForm.current === 1) {
      list = res.records
    } else {
      list = Data.prodList.concat(res.records)
    }
    Data.prodList = list
    Data.dataForm.pages = res.pages
    nextTick(() => {
      if (prodListRef.value) prodListRef.value.isAllChecked = false
    })
    uni.hideLoading()
  })
}

// 点击底部按钮（批量，发布）
const handleClickMoreBtn = (index) => {
  // console.log('btn', index)
  if (Data.prodList.length > 0) prodListRef.value.mask()
  switch (index) {
    case 1:
      handleSwitchBatchOperSts()
      break
    case 2:
      handlePostProd()
      break
  }
}

/**
 * 发布商品按钮
 */
const handlePostProd = () => {
  uni.navigateTo({
    url: '/package-prod/pages/post-prod/post-prod?add=true'
  })
}

/**
 * 搜索输入框的值
 */
const handleSearch = (keyWord) => {
  Data.dataForm.prodName = keyWord
  Data.dataForm.prodId = ''
  Data.dataForm.current = 1
  getProdList()
}

/**
 * 删除
 */
const deleteProd = (id) => {
  http.request({
    url: `/prod/prod/${id}`,
    method: 'delete',
    data: {}
  }).then(() => {
    uni.showToast({
      title: $t('shanChuChengGong'),
      mask: true,
      icon: 'success',
      duration: 1000
    })
    setTimeout(function () {
      Data.dataForm.current = 1
      getProdList()
    }, 1000)
  })
}

/**
 * 下架/上架
 */
const setStatus = (id, status) => {
  http.request({
    url: '/prod/prod/prodStatus',
    method: 'put',
    data: {
      status,
      prodId: id
    }
  }).then(() => {
    uni.showToast({
      title: $t('xiuGaiChengGong-0'),
      mask: true,
      icon: 'success',
      duration: 1000
    })
    setTimeout(function () {
      Data.dataForm.current = 1
      getProdList()
    }, 1000)
  })
}

// 批量设置状态
const batchSetStatus = (status, prodIdList) => {
  http.request({
    url: `/prod/prod/batchProdStatus/${status}`,
    method: 'put',
    data: prodIdList
  }).then(() => {
    uni.showToast({
      title: $t('xiuGaiChengGong-0'),
      mask: true,
      icon: 'success',
      duration: 1000
    })
    setTimeout(function () {
      Data.dataForm.current = 1
      getProdList()
    }, 1000)
  })
}

// 批量删除
const batchDeleteProd = (prodIdList) => {
  http.request({
    url: '/prod/prod',
    method: 'delete',
    data: prodIdList
  }).then(() => {
    uni.showToast({
      title: '',
      mask: true,
      icon: 'success',
      duration: 1000
    })
    setTimeout(function () {
      Data.dataForm.current = 1
      getProdList()
    }, 1000)
  })
}

// 隐藏浮层
const closeMask = () => {
  if (Data.prodList.length > 0) prodListRef.value.mask()
}
</script>

<style lang="scss" scoped>
@use "prod-management";
</style>
