<!--
 Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
 https://www.mall4j.com/
 未经允许，不可做商业用途！
 版权所有，侵权必究！
-->
<template>
  <div class="Mall4j component-contract-info">
    <!-- 签约信息 -->
    <div class="contract-info table-box">
      <!-- 签约类目 -->
      <div class="s-category-item s-item">
        <div class="apply-sign">
          <div class="table-data-title">
            <div class="text">
              <span class="stress">*</span>{{ $t('multishop.shopInformation.category') }}
            </div>
            <div class="tips">
              {{ $t('multishop.shopInformation.signed') }}
              <span class="txt-bold">{{ signCategoryList.length }}</span>
              {{ $t('multishop.shopInformation.signableBefore') }}
              <span class="txt-bold">200</span>
              {{ $t('multishop.shopInformation.signableAfter') }}
            </div>
          </div>
          <el-button
            v-permission="['shop:shopCategory:save']"
            type="primary"
            @click="cateAddOrUpdateHandle(0)"
          >
            {{ $t('multishop.shopInformation.applySigningCategory') }}
          </el-button>
        </div>
        <div class="si-content">
          <el-table
            :data="signCategoryList"
            header-cell-class-name="table-header"
            row-class-name="table-row-low"
          >
            <el-table-column
              prop="name"
              :label="$t('multishop.shopInformation.categoryName')"
              align="left"
            />
            <el-table-column
              prop="parentName"
              :label="$t('multishop.shopInformation.parentName')"
              align="left"
            />
            <el-table-column
              prop="platformRate"
              :label="$t('multishop.shopInformation.platformRate')"
              align="left"
            >
              <template #default="{ row }">
                <span v-if="row.customizeRate === null">{{ row.platformRate }} %</span>
                <span v-else>{{ row.customizeRate }} %</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="qualifications"
              :label="$t('multishop.shopInformation.qualifications')"
              align="left"
            >
              <template #default="{row}">
                <div
                  v-if="row.imgs && row.imgs.length"
                  class="img-box"
                >
                  <el-image
                    v-for="(img,index) in row.imgs"
                    :key="index"
                    class="rotating-img"
                    :src="addDomain(img)"
                    :preview-src-list="addDomain(row.imgs)"
                    preview-teleported
                  >
                    <template #error>
                      <img
                        class="img-slot"
                        src="@/assets/images/def.png"
                        alt
                      >
                    </template>
                  </el-image>
                </div>
                <span v-else>--</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="categoryStatus"
              :label="$t('table.status')"
              width="80"
            >
              <template #default="scope">
                <div
                  v-if="scope.row.categoryStatus === 1"
                  class="tag-txt"
                >
                  {{ $t('multishop.shopInformation.tag') }}
                </div>
                <div
                  v-if="scope.row.categoryStatus === 0"
                  class="tag-txt red-tag-txt"
                >
                  {{ $t('multishop.shopInformation.redTag') }}
                </div>
              </template>
            </el-table-column>
            <el-table-column
              :label="$t('table.actions')"
              width="100"
              align="center"
            >
              <template #default="scope">
                <el-button
                  link
                  type="primary"
                  @click="categoryDelete(scope.row)"
                >
                  {{ $t('table.delete') }}
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <!-- 签约品牌 -->
      <div class="s-brand-item s-item">
        <div class="apply-sign">
          <div class="table-data-title">
            <div class="text">
              {{ $t('multishop.shopInformation.brand') }}
            </div>
            <div class="tips">
              {{ $t('multishop.shopInformation.signed') }}
              <span class="txt-bold">{{ signedBrands.length }}</span>
              {{ $t('multishop.shopInformation.brandBefore') }}
              <span class="txt-bold">50</span>
              {{ $t('multishop.shopInformation.brandAfter') }}
            </div>
          </div>
          <el-button
            v-permission="['shop:shopBrand:save']"
            type="primary"
            @click="cateAddOrUpdateHandle(1)"
          >
            {{ $t('multishop.shopInformation.applySigningBrand') }}
          </el-button>
        </div>
        <div class="si-content">
          <el-table
            :data="signedBrands"
            header-cell-class-name="table-header"
            row-class-name="table-row-low"
          >
            <el-table-column
              prop="name"
              :label="$t('multishop.shopInformation.brandName')"
              align="left"
            />
            <el-table-column
              prop="firstLetter"
              :label="$t('multishop.shopInformation.firstLetter')"
              align="left"
            />
            <el-table-column
              prop="parentName"
              :label="$t('multishop.shopInformation.parentName')"
              align="left"
            />
            <el-table-column
              prop="platformRate"
              :label="$t('multishop.shopInformation.platformRateLogo')"
              align="left"
            >
              <template #default="scope">
                <div class="img-box">
                  <el-image
                    v-if="scope.row.imgUrl"
                    class="rotating-img"
                    :src="addDomain(scope.row.imgUrl)"
                    :preview-src-list="[addDomain(scope.row.imgUrl)]"
                    preview-teleported
                  >
                    <template #error>
                      <img
                        class="img-slot"
                        src="@/assets/images/def.png"
                        alt
                      >
                    </template>
                  </el-image>
                  <span v-else>--</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="imgs"
              :label="$t('multishop.shopInformation.imgs')"
              align="left"
            >
              <template #default="{row}">
                <div
                  v-if="row.imgs && row.imgs.length"
                  class="img-box"
                >
                  <el-image
                    v-for="(img,index) in row.imgs"
                    :key="index"
                    class="rotating-img"
                    :src="addDomain(img)"
                    :preview-src-list="addDomain(row.imgs)"
                    preview-teleported
                  >
                    <template #error>
                      <img
                        class="img-slot"
                        src="@/assets/images/def.png"
                        alt
                      >
                    </template>
                  </el-image>
                </div>
                <div v-if="!(row.imgs && row.imgs.length)">
                  --
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="brandStatus"
              :label="$t('table.status')"
              width="80"
            >
              <template #default="scope">
                <div
                  v-if="scope.row.brandStatus === 1"
                  class="tag-txt"
                >
                  {{ $t('multishop.shopInformation.tag') }}
                </div>
                <div
                  v-if="scope.row.brandStatus === 0"
                  class="tag-txt red-tag-txt"
                >
                  {{ $t('multishop.shopInformation.redTag') }}
                </div>
              </template>
            </el-table-column>
            <el-table-column
              :label="$t('table.actions')"
              width="100"
              align="center"
            >
              <template #default="scope">
                <el-button
                  link
                  type="primary"
                  @click="brandDelete(scope.row)"
                >
                  {{ $t('table.delete') }}
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <!-- 签约有效期 -->
      <div
        v-if="paySettlementType!==1"
        class="s-brand-item s-item"
      >
        <div class="apply-sign">
          <div class="table-data-title">
            <div class="text">
              <span class="stress">*</span>{{ $t('multishop.shopInformation.contractValidity') }}
            </div>
            <div class="tips">
              {{ $t('multishop.shopInformation.supplierStoreValidity') }}
            </div>
          </div>
        </div>
        <div class="si-content">
          <div class="contract-time-box">
            <el-date-picker
              v-model="shopBasicInfo.contractStartTime"
              style="width:170px;"
              type="date"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="开始日期"
              disabled
            />
            <span style="margin: 0 10px">-</span>
            <div class="end-time">
              <el-date-picker
                v-model="shopBasicInfo.contractEndTime"
                style="width:170px;"
                type="date"
                value-format="YYYY-MM-DD HH:mm:ss"
                :placeholder="shopBasicInfo.contractStartTime&& !shopBasicInfo.contractEndTime ? '' : '结束日期'"
                disabled
              />
              <span
                v-if="shopBasicInfo.contractStartTime&& !shopBasicInfo.contractEndTime"
                class="text disable"
              >
                无固定期限
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- /签约信息 -->
    <category-add-or-update
      v-if="cateAddOrUpdateVisible"
      ref="cateAddOrUpdateRef"
      :sign-category-list="signCategoryList"
      :push="push"
      :delete-by-id="deleteById"
      :splice="splice"
      :map="map"
      @close-popup="closePopup"
    />
    <brand-add-or-update
      v-if="brandAddOrUpdateVisible"
      ref="brandAddOrUpdateRef"
      :parent-brand-list="parentBrandList"
      @close-popup="closePopup"
    />
  </div>
</template>
<script setup>

import * as api from '@/api/multishop/shop-process.js'
import categoryAddOrUpdate from '../category-add-or-update/index.vue'
import BrandAddOrUpdate from '../brand-add-or-update/index.vue'
import { ElMessageBox, ElMessage } from 'element-plus'

const allinPayStore = useAllinpayStore()
const paySettlementType = ref(allinPayStore.paySettlementType)

const shopBasicInfo = ref({})

// 店铺分类签约信息
const signCategoryList = ref([])
// 平台品牌签约信息
const signedBrands = ref([]) // 平台品牌+自定义品牌
const cateAddOrUpdateVisible = ref(false)
const brandAddOrUpdateVisible = ref(false)
const parentBrandList = ref([])
onMounted(() => {
  // 查询基本信息
  queryShopBasicInfo()
  // 查询分类签约信息
  getSignCategoryList()
  // 查询品牌签约信息
  getSignBrandList()
})

/**
 * 查询基本信息
 */
const queryShopBasicInfo = () => {
  api.getBasicInfo().then(data => {
    if (data.type) {
      data.type = data.type.toString()
    }
    shopBasicInfo.value = data
  })
}
/**
 * 签约类目列表
 */
const getSignCategoryList = () => {
  api.getSignCategoryList().then((data) => {
    if (data) {
      signCategoryList.value = data
      signCategoryList.value.forEach(item => {
        item.imgs = item.qualifications ? item.qualifications.split(',') : []
      })
      parentBrandList.value = JSON.parse(JSON.stringify(signCategoryList.value))
      const obj = {}
      parentBrandList.value = parentBrandList.value.reduce((cur, next) => {
        if (!obj[next.parentName]) {
          obj[next.parentName] = cur.push(next)
        }
        return cur
      }, []) // 设置cur默认类型为数组，并且初始值为空的数组 数组对象去重
    }
  })
}

/**
 * 获取签约品牌列表
 */
const getSignBrandList = () => {
  api.getSignBrandList().then(data => {
    data.platformBrandList.forEach((item) => {
      let parentName = ''
      if (item.categories) {
        parentName = `${item.categories[0].categories[0].name}>${item.categories[0].categories[1].name}>${item.categories[0].name}`
      }
      item.parentName = parentName
    })
    signedBrands.value = data.platformBrandList.concat(data.customizeBrandList)
    signedBrands.value.forEach(el => {
      let parentName = ''
      if (el.categories) {
        parentName = `${el.categories[0].categories[0].name}>${el.categories[0].categories[1].name}>${el.categories[0].name}`
      }
      el.parentName = parentName
      el.imgs = el.qualifications ? el.qualifications.split(',') : []
    })
  })
}
/**
 * 编辑签约信息弹窗
 * @param {Number} type 签约类型 0:类别 1:品牌
 */
const cateAddOrUpdateRef = ref(null)
const brandAddOrUpdateRef = ref(null)
const cateAddOrUpdateHandle = (type) => {
  if (type === 0) {
    cateAddOrUpdateVisible.value = true
    nextTick(() => {
      cateAddOrUpdateRef.value?.init()
    })
  } else if (type === 1) {
    brandAddOrUpdateVisible.value = true
    nextTick(() => {
      brandAddOrUpdateRef.value?.init('editor')
    })
  }
}

/**
 * 关闭弹窗
 */
const closePopup = (val) => {
  if (val === 'category') {
    cateAddOrUpdateVisible.value = false
    getSignCategoryList()
  } else if (val === 'brand') {
    brandAddOrUpdateVisible.value = false
    getSignBrandList()
  }
}

const categoryDelete = (row) => {
  const obj = {
    categoryShopId: row.categoryShopId
  }
  ElMessageBox.confirm($t('table.sureToDelete'), $t('table.tips'), {
    confirmButtonText: $t('table.confirm'),
    cancelButtonText: $t('table.cancel'),
    type: 'warning'
  }).then(() => {
    api.deleteSigningCategory(obj).then(() => {
      ElMessage({
        message: $t('table.delSuccess'),
        type: 'success',
        duration: 1500,
        onClose: () => getSignCategoryList()
      })
    }).catch(() => {
    })
  }).catch(() => {})
}

const brandDelete = (row) => {
  const obj = {
    brandShopId: row.brandShopId
  }
  ElMessageBox.confirm($t('table.sureToDelete'), $t('table.tips'), {
    confirmButtonText: $t('table.confirm'),
    cancelButtonText: $t('table.cancel'),
    type: 'warning'
  }).then(() => {
    api.deleteSigningBrand(obj).then(() => {
      ElMessage({
        message: $t('table.delSuccess'),
        type: 'success',
        duration: 1500,
        onClose: () => getSignBrandList()
      })
    }).catch(() => {
    })
  }).catch(() => {})
}

const map = () => {
  return signCategoryList.value.map(item => item.categoryId)
}
const splice = (categoryId) => {
  signCategoryList.value = signCategoryList.value.filter(i => i.categoryId !== categoryId)
}
const push = (vla) => {
  signCategoryList.value.push(vla)
}
const deleteById = (id, list) => {
  for (let index = list.length - 1; index >= 0; index--) {
    if (list[index] && list[index].categoryId === id) {
      list.splice(index, 1)
    }
  }
  return list
}

</script>
<style lang="scss" scoped>
@use "index";
</style>
