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

  https://www.mall4j.com/

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

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

<template>
  <view class="Mall4j component-prod-list">
    <view class="prod-list">
      <label
        v-for="(prodItem, index) in productList"
        :key="index"
        class="prod-item"
      >
        <view
          v-if="isBatchOper"
          class="check-box"
        >
          <checkbox
            :checked="prodItem.isChecked"
            @tap.stop="handleSingleProdCheck(index)"
          />
        </view>
        <view class="prod-con">
          <view class="prod-img">
            <img-show :src="prodItem.pic" />
          </view>
          <view class="prod-info">
            <view class="name">{{ prodItem.prodName }}</view>
            <view class="price">￥<text class="price-big">{{ parsePrice(prodItem.price)[0] }}</text>{{ '.' +
              parsePrice(prodItem.price)[1] }}</view>
            <view>
              <view class="prod-stutus-item">{{ [$t('puTongShangPin'), $t('tuanGouShangPin'), $t('miaoShaShangPin'), $t('jiFenShangPin'), '', $t('zuHeXuanPin')][prodItem.prodType] }}</view>
              <view class="prod-stutus-item">{{ [$t('shiWuShangPin'),$t('xuNiShangPin'),$t('zuHeShangPin'),$t('dianZiKaQuan')][prodItem.mold] }}</view>
            </view>
            <view class="stock-status">
              <text class="stock">{{ $t('kuCun-0') }}{{ prodItem.totalStocks }}</text>
              <text class="status">{{ $t('zhuangTai-0') }}
                <text v-if="prodItem.status === 1">{{ $t('shangJia-0') }}</text>
                <text v-if="prodItem.status === 0">{{ $t('xiaJia-0') }}</text>
                <text v-if="prodItem.status === 6">{{ $t('daiShenHe') }}</text>
                <text v-if="prodItem.status === 2">{{ $t('weiGuiXiaJia') }}</text>
                <text v-if="prodItem.status === 3">{{ $t('weiGuiXiaJiaDaiShenHe') }}</text>
                <text v-if="prodItem.status === 4">{{ $t('brandRemoval') }}</text>
                <text v-if="prodItem.status === 5">{{ $t('brandRemovalAudit') }}</text>
              </text>
              <view
                v-if="isAuthorities('prod:prod:update') || isAuthorities('prod:prod:status') || isAuthorities('prod:prod:audit') || isAuthorities('prod:prod:delete')"
                class="edit-icon-box"
                @tap.stop="showEdit = true; showIndex = index"
              >
                <view
                  v-for="dot in 3"
                  :key="dot"
                  class="edit-icon"
                />
              </view>
            </view>
            <view
              v-if="showEdit && showIndex === index"
              class="popup"
            >
              <view
                class="mask-edit"
                @tap.stop="mask"
              />
              <view class="edit-popup">
                <view
                  v-if="isAuthorities('prod:prod:update')"
                  class="item"
                  @tap.stop="editProd(prodItem)"
                >
                  {{ prodItem.stationId?$t('chaKan'):$t('bianJi') }}</view>
                <view
                  v-if="isAuthorities('prod:prod:status') && prodItem.status === 0 && !prodItem.prodBelongs"
                  class="item"
                  @tap.stop="setStatus(prodItem.prodId, 1)"
                >{{ $t('shangJia-0') }}</view>
                <view
                  v-if="isAuthorities('prod:prod:status') && prodItem.status === 1&& !prodItem.prodBelongs"
                  class="item"
                  @tap.stop="setStatus(prodItem.prodId, 0)"
                >{{ $t('xiaJia-0') }}</view>
                <view
                  v-if="isAuthorities('prod:prod:audit') && prodItem.status === 2 && !prodItem.prodBelongs"
                  class="item"
                  @tap.stop="application(prodItem.prodId)"
                >{{ $t('shenQingShangJia') }}</view>
                <view
                  v-if="isAuthorities('prod:prod:audit') && prodItem.status === 3 && !prodItem.prodBelongs"
                  class="item"
                  @tap.stop="application(prodItem.prodId)"
                >{{ $t('shenHeLiShi') }}</view>
                <view
                  v-if="isAuthorities('prod:prod:delete')"
                  class="item"
                  @tap.stop="deleteProd(prodItem.prodId)"
                >{{ $t('shanChu') }}
                </view>
              </view>
            </view>
          </view>
        </view>
      </label>
    </view>
    <!-- 批量操作的按钮 -->
    <view
      v-if="isBatchOper"
      class="footer-btn-con"
    >
      <view class="btn-con batch-oper">
        <label
          class="all-check"
          @tap="handleSwitchAllChecked"
        >
          <checkbox
            :checked="isAllChecked"
            @tap="handleSwitchAllChecked"
          />
          <text>{{ $t('quanXuan') }}</text>
        </label>
        <view @tap="handleExitBatchOper">
          {{ $t('tuiChuPiLiang') }}
        </view>
      </view>
      <view class="btn-con del-btn">
        <button
          v-if="batchOperBtnConfig.btnText"
          class="btn"
          style="flex: 1;"
          type="default"
          hover-class="none"
          @tap="handleClickBtn"
        >
          {{ batchOperBtnConfig.btnText }}
        </button>

        <template v-else>
          <button
            v-for="(value, index) in batchOperBtnConfig.btnList"
            :key="index"
            class="btn"
            :class="{ 'btn-plain': index == 0, isHide: !value.isShow }"
            style="width:180rpx"
            type="default"
            hover-class="none"
            @tap="handleClickMoreBtn(index + 1)"
          >
            {{ batchOperBtnConfig.btnList[index].btnText }}
          </button>
        </template>
      </view>
    </view>
  </view>
</template>

<script setup>
import { onMounted, reactive, watch } from 'vue'
import util from '@/utils/util'
const { isAuthorities } = util

const emit = defineEmits(['handleSwitchBatchOperSts', 'batchSetStatus', 'batchDeleteProd', 'setStatus', 'deleteProd'])

const props = defineProps({
  // 是否在批量操作的状态
  isBatchOper: {
    type: Boolean,
    default: false
  },
  prodList: {
    type: Array,
    default: () => {
      return []
    }
  },
  closeMask: {
    type: Function,
    default: null
  },
  batchOperBtnConfig: {
    type: Object,
    default: () => {
      return { btnText: $t('shanChu') }
    }
  },
  dataForm: {
    type: Object,
    default: () => {
      return {}
    }
  }
})

const Data = reactive({
  // 是否全选
  isAllChecked: false,
  productList: [],
  showEdit: false,
  showIndex: -1
})

const { isAllChecked, productList, showEdit, showIndex } = toRefs(Data)

watch(() => props.prodList, () => {
  init()
}, { deep: true })

onMounted(() => {
  init()
})

const init = () => {
  if (props.prodList.length) {
    Data.productList = props.prodList
  }
}

/**
     * 商品的单独勾选
     */
const handleSingleProdCheck = (index) => {
  if (!props.isBatchOper) {
    return
  }
  const obj = Data.productList[index]
  obj.isChecked = !obj.isChecked
  Data.productList[index] = obj
  // 校验是否已经全选
  checkIsAllChecked()
}

/**
     * 退出批量操作
     */
const handleExitBatchOper = () => {
  mask()
  emit('handleSwitchBatchOperSts')
}

/**
     * 全选按钮点击
     */
const handleSwitchAllChecked = () => {
  mask()
  Data.isAllChecked = !Data.isAllChecked
  for (let i = 0; i < Data.productList.length; i++) {
    const element = Data.productList[i]
    element.isChecked = Data.isAllChecked
  }
}

/**
     * 校验是否已经全选
     */
const checkIsAllChecked = () => {
  let isAllCheckedPar = true
  for (let i = 0; i < Data.productList.length; i++) {
    const element = Data.productList[i]
    if (!element.isChecked) {
      isAllCheckedPar = false
      break
    }
  }
  Data.isAllChecked = isAllCheckedPar
}

const mask = () => {
  Data.showEdit = false
}

/**
     * 编辑商品
     */
const editProd = (item) => {
  mask()
  uni.navigateTo({
    url: `/package-prod/pages/post-prod/post-prod?prodId=${item.prodId}&prodBelongs=${item.prodBelongs || ''}`
  })
}

// 点击底部单个按钮
const handleClickBtn = () => {
  mask()
  const list = Data.productList.filter((item) => {
    return item.isChecked
  })
  if (list.length === 0) {
    uni.showToast({
      title: $t('qingXuanZeShangPin'),
      mask: true,
      icon: 'none',
      duration: 1000
    })
    return
  }
  batchDeleteProd(list)
}

// 点击底部多个按钮（下架、上架、删除）
const handleClickMoreBtn = (index) => {
  mask()
  const list = Data.productList.filter((item) => {
    return item.isChecked
  })
  if (list.length === 0) {
    uni.showToast({
      title: $t('qingXuanZeShangPin'),
      mask: true,
      icon: 'none',
      duration: 1000
    })
    return
  }
  switch (index) {
    case 1:
      if (props.dataForm.status === 1) {
        batchSetData(0, list)
      } else if (props.dataForm.status === 0) {
        batchSetData(1, list)
      }
      break
    case 2:
      batchDeleteProd(list)
      break
  }
}

// 批量设置
const batchSetData = (status, list) => {
  const prodList = list.filter(item => {
    if (status === 0 && item.status === 1) {
      // 进行下架商品操作，则只改变状态为上架的
      return true
    } else if (status === 1 && item.status === 0) {
      // 进行上架商品操作，则只改变状态为下架的
      return true
    } else {
      // 其他状态不做修改
      return false
    }
  })
  const prodIdList = prodList.map(item => {
    return item.prodId
  })
  uni.showModal({
    title: '',
    content: (status === 0 ? $t('queDingPiLiangXiaJiaShangJiaShangPin') : $t('queDingPiLiangShangJiaShangPin')),
    cancelText: $t('quXiao-0'),
    confirmText: $t('queDing'),
    confirmColor: '#082BA6',
    success (res) {
      if (res.confirm) {
        emit('batchSetStatus', status, prodIdList)
      }
    }
  })
}

// 批量删除
const batchDeleteProd = (list) => {
  const prodIdList = list.map(item => {
    return item.prodId
  })
  uni.showModal({
    title: '',
    content: $t('queDingPiLiangShanChuShangPin'),
    cancelText: $t('quXiao-0'),
    confirmText: $t('queDing'),
    confirmColor: '#082BA6',
    success (res) {
      if (res.confirm) {
        emit('batchDeleteProd', prodIdList)
      }
    }
  })
}

const parsePrice = (price) => {
  if (price.toString().indexOf('.') > -1) {
    return price.toString().split('.')
  }
  return [price]
}

/**
     * 下架
     */
const setStatus = (prodId, status) => {
  uni.showModal({
    title: '',
    content: (status === 0 ? $t('queDingXiaJiaShangPin') : $t('queDingShangJiaShangPin')),
    cancelText: $t('quXiao-0'),
    confirmText: (status === 0 ? $t('xiaJia-0') : $t('shangJia-0')),
    confirmColor: '#082BA6',
    success (res) {
      if (res.confirm) {
        emit('setStatus', prodId, status)
      }
      Data.showEdit = false
    }
  })
}

/**
     * 申请上架
     */
const application = (prodId) => {
  uni.navigateTo({
    url: `/package-prod/pages/prod-application/prod-application?prodId=${prodId}`
  })
}

/**
     * 删除
     */
const deleteProd = (prodId) => {
  uni.showModal({
    title: '',
    content: $t('queDingShanChuShangPin'),
    cancelText: $t('quXiao-0'),
    cancelColor: '#333',
    confirmText: $t('shanChu'),
    confirmColor: '#2B4499',
    success (res) {
      if (res.confirm) {
        emit('deleteProd', prodId)
      }
      Data.showEdit = false
    }
  })
}

defineExpose({
  mask
})
</script>

<style lang="scss" scoped>
.component-prod-list {
  .prod-list {
    background-color: #fff;
    border-radius: 10rpx;
    padding: 30rpx;

    .prod-item {
      display: flex;
      // height: 130rpx;
      margin-bottom: 30rpx;

      &:last-child {
        margin-bottom: 0;
      }

      .check-box {
        width: 36rpx;
        margin-right: 20rpx;
        display: flex;
        align-items: center;
      }

      .prod-con {
        flex: 1;
        display: flex;

        .prod-img {
          margin-right: 20rpx;
          width: 140rpx;
          height: 140rpx !important;
          border-radius: 10rpx;
          overflow: hidden;
        }

        .prod-info {
          flex: 1;
          margin-left: auto;
          display: flex;
          flex-direction: column;
          line-height: 17px;

          .name {
            font-size: 14px;
            font-weight: bold;
            flex: 1;
            line-height: 20px;
            color: #333333;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 1;
            display: -webkit-box;
            white-space: normal;
            word-break: break-word;
            overflow: hidden;
            text-overflow: ellipsis;
          }

          .price {
            font-size: 24rpx;
            flex: 1;
            color: #082BA6;
            line-height: 34rpx;
            font-weight: bold;
            margin-top: 18rpx;

            .price-big {
              font-size: 32rpx;
            }
          }

          .prod-stutus-item {
            display: inline-block;
            // margin-top: 18rpx;
            margin-right: 10rpx;
            padding: 2rpx 6rpx;
            font-size: 20rpx;
            // width: 92rpx;
            word-break: break-all;
            line-height: 28rpx;
            color: #082ba6;
            border: 2rpx solid #082ba6;
            border-radius: 4rpx;
          }

          .stock-status {
            font-size: 24rpx;
            line-height: 34rpx;
            flex: 1;
            color: #999;

            .edit-icon-box {
              float: right;
            }

            .edit-icon {
              display: inline-block;
              width: 6rpx;
              margin-left: 6rpx;
              height: 6rpx;
              background: #c8c9cc;
              border-radius: 50%;
            }

            .stock {
              margin-right: 20rpx;
            }
          }

          .popup {
            position: relative;

            .edit-popup {
              animation: window-open 0.4s 1;
              position: absolute;
              right: -10px;
              top: 5px;
              width: auto;
              background: #262728;
              z-index: 99;
              opacity: 0.9;
              border-radius: 4px;
              display: flex;
              flex-direction: row;
              box-sizing: border-box;
              padding: 7px 0;

              .item {
                color: #ddd;
                font-size: 12px;
                height: 30px;
                border-right: 1px solid #ddd;
                display: flex;
                align-items: center;
                padding: 0 25px;
                justify-content: center;
              }

              .item:last-child {
                border: none;
              }
            }

            .edit-popup::after {
              content: '';
              position: absolute;
              right: 0;
              top: -15rpx;
              width: 0;
              height: 0;
              border-left: 34rpx solid transparent;
              border-right: 34rpx solid transparent;
              border-bottom: 40rpx solid #262728;
            }
          }
        }
      }
    }
  }

  .footer-btn-con {
    z-index: 9;
    width: 100%;
    position: fixed;
    left: 0;
    bottom: 0;
    padding-bottom: var(--mall4j-safe-area-inset-bottom);
    box-sizing: border-box;
    box-shadow: 0px -2px 4px rgba(0, 0, 0, 0.03);
    background: #fff;
    display: flex;

    .btn-con {
      color: #333;
      font-size: 28rpx;
      display: flex;
      align-items: center;

      .btn.btn-plain {
        height: 70rpx;
        line-height: 70rpx;
        border-radius: 35rpx;
        font-size: 26rpx;
        background: rgba(255, 255, 255, 0.39);
        border: 2rpx solid #082BA6;
        color: #082BA6
      }
      :deep(uni-button[type='default']) {
        height: 70rpx;
        line-height: 70rpx;
        border-radius: 35rpx;
        font-size: 26rpx;
        color: #fff;
        background-color: #082ba6;
        border: 1px solid #082ba6;
      }

      .btn.isHide {
        display: none;
      }

      &:last-child {
        flex: 5;
      }

      .all-check {
        margin-right: 30rpx;
        display: flex;
        align-items: center;
      }
    }

    .btn-con.batch-oper {
      padding-left: 30rpx;
    }

    .btn-con.del-btn {
      padding: 20rpx;
      padding-right: 30rpx;
      box-sizing: border-box;
    }
  }
/* #ifdef H5 */
  /*checkbox选中后样式  */
 :deep(uni-checkbox .uni-checkbox-input){
    &:empty{
      background-color: #fff;
    }
    background: #082BA6;
    svg path{
      fill:#fff
    }
  }
  /* #endif */
}

.mask-edit {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 94%;
  bottom: 0;
  background: rgba(0, 0, 0, 0);
  z-index: 10;
}
</style>
