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

 https://www.mall4j.com/

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

 版权所有，侵权必究！
-->
<template>
  <div class="Mall4j component-brand-add-or-update">
    <el-dialog
      v-model="visible"
      :show-close="false"
      :close-on-click-modal="false"
      class="Mall4j component-brand-add-or-update"
      width="80%"
      top="8vh"
    >
      <div>
        <div class="popup">
          <div class="title">
            <div class="text">
              {{ $t('multishop.shopProcess.editBrand') }}
            </div>
            <div class="tips">
              {{ $t('multishop.shopInformation.signed') }}<span class="txt-bold">{{ signBrandLength + signBrandList.length + dataForm.customSignBrandList.length }}</span>{{ $t('multishop.shopInformation.brandBefore') }}<span class="txt-bold">50</span>{{ $t('multishop.shopInformation.brandAfter') }}
            </div>
            <div
              class="close-btn"
              @click="closePopup"
            >
              <el-icon><Close /></el-icon>
            </div>
          </div>
          <div class="content">
            <div class="left-box">
              <div class="search-box">
                <input
                  v-model="keyword"
                  class="search-input"
                  :placeholder="$t('multishop.shopProcess.searchBrandTips')"
                >
                <div
                  class="search-btn"
                  @click="searchBrand"
                >
                  <el-icon><Search /></el-icon>
                </div>
              </div>
              <div class="brand-box">
                <div class="brand-list">
                  <div
                    v-for="(item, index) in allBrandList"
                    :key="index"
                    class="brand-item"
                    :class="{'active':item.isSelected===true}"
                    @click="addBrand(item, index)"
                  >
                    {{ item.name }}
                  </div>
                </div>
                <div
                  v-if="!allBrandList.length"
                  class="empty-result"
                >
                  {{ $t('table.noData') }}
                </div>
              </div>
            </div>
            <div class="right-box">
              <div
                class="table-box"
                :class="{'big-tb': !showCustomization}"
              >
                <!-- height="482" -->
                <el-table
                  :data="signBrandList"
                  :header-cell-style="{height:'50px',background:'#F5F5F5',color:'#000','font-weight': '400'}"
                >
                  <el-table-column
                    prop="name"
                    :label="$t('multishop.shopInformation.brandName')"
                  />
                  <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="imgUrl"
                    :label="$t('multishop.shopInformation.platformRateLogo')"
                  >
                    <template #default="scope">
                      <ImgShow
                        :src="scope.row.imgUrl"
                        :img-style="{width:'57px',height:'57px'}"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="qualifications"
                    :label="$t('multishop.shopInformation.imgs')"
                    width="230"
                  >
                    <template #default="scope">
                      <div class="business-qual">
                        <imgs-upload
                          v-model="scope.row.qualifications"
                          :limit="2"
                          @input="imgChange(scope.row.qualifications)"
                        />
                      </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
                    prop="address"
                    :label="$t('table.actions')"
                    width="80"
                  >
                    <template #default="scope">
                      <el-button
                        link
                        type="primary"
                        @click="deleteBrand(scope.row.brandId, scope.$index)"
                      >
                        {{ $t('table.delete') }}
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
              <div
                v-if="showCustomization"
                class="custom-box"
              >
                <div class="text">
                  {{ $t('multishop.shopProcess.customBrand') }}
                </div>
                <div
                  class="add-btn"
                  @click="addCustomBrand"
                >
                  {{ $t('multishop.shopProcess.addCustomBrand') }}
                </div>
              </div>
              <!-- 添加自定义品牌 -->
              <div
                v-if="dataForm.customSignBrandList.length && showCustomization"
                class="table-box"
              >
                <el-form
                  ref="brandsInfoFormRef"
                  :model="dataForm"
                  :rules="dataForm.customSignBrandRule"
                  @submit.prevent
                >
                  <!-- height="265" -->
                  <el-table
                    class="add-bank-info-table"
                    :data="dataForm.customSignBrandList"
                    :header-cell-style="{height:'50px',background:'#F5F5F5',color:'#000','font-weight': '400'}"
                  >
                    <el-table-column
                      :label="$t('multishop.shopInformation.brandName')"
                      prop="name"
                    >
                      <template #default="scope">
                        <el-form-item
                          :prop="'customSignBrandList.' + scope.$index + '.name'"
                          :rules="dataForm.customSignBrandRule.name"
                        >
                          <el-input
                            v-model="scope.row.name"
                            :placeholder="$t('multishop.shopInformation.brandName')"
                            maxlength="50"
                            style="width:100%"
                          />
                        </el-form-item>
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="firstLetter"
                      :label="$t('multishop.shopInformation.firstLetter')"
                    >
                      <template #default="scope">
                        <el-form-item
                          :prop="'customSignBrandList.' + scope.$index + '.firstLetter'"
                          :rules="dataForm.customSignBrandRule.firstLetter"
                        >
                          <el-input
                            v-model="scope.row.firstLetter"
                            maxlength="1"
                            placeholder="$t('multishop.shopInformation.firstLetter')"
                            style="width:100%"
                          />
                        </el-form-item>
                      </template>
                    </el-table-column>
                    <el-table-column
                      :label="$t('multishop.shopProcess.brandClassification')"
                      prop="category"
                      required
                    >
                      <template #default="scope">
                        <el-select
                          v-model="scope.row.categoryId"
                          size="small"
                          :placeholder="$t('multishop.shopProcess.brandClassificationTips')"
                        >
                          <el-option
                            v-for="item in props.parentBrandList"
                            :key="item.categoryId"
                            :label="item.parentName"
                            :value="item.categoryId"
                          />
                        </el-select>
                        <div
                          v-if="scope.row.categoryId === null"
                          class="category-error"
                        >
                          {{ $t('multishop.shopProcess.brandClassificationEmpty') }}
                        </div>
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="imgUrl"
                      :label="$t('multishop.shopInformation.platformRateLogo')"
                    >
                      <template #default="scope">
                        <el-form-item
                          :rules="dataForm.customSignBrandRule.imgUrl"
                          :prop="'customSignBrandList.' + scope.$index + '.imgUrl'"
                        >
                          <div class="business-qual">
                            <img-upload
                              v-model="scope.row.imgUrl"
                              @input="imgChange(scope.row.imgUrl)"
                            />
                          </div>
                        </el-form-item>
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="qualifications"
                      :label="$t('multishop.shopInformation.imgs')"
                      width="230"
                    >
                      <template #default="scope">
                        <el-form-item
                          :prop="'customSignBrandList.' + scope.$index + '.qualifications'"
                          :rules="dataForm.customSignBrandRule.qualifications"
                        >
                          <div class="business-qual">
                            <imgs-upload
                              v-model="scope.row.qualifications"
                              :limit="2"
                              @input="imgChange(scope.row.qualifications)"
                            />
                          </div>
                        </el-form-item>
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="address"
                      :label="$t('table.status')"
                      width="70"
                    >
                      <template #default="scope">
                        <el-button
                          link
                          type="primary"
                          @click="deleteCustomBrandItem(scope.$index)"
                        >
                          {{ $t('table.delete') }}
                        </el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-form>
              </div>
            </div>
          </div>
          <div class="btn-box">
            <div
              class="cancel-btn"
              @click="closePopup"
            >
              {{ $t('table.cancel') }}
            </div>
            <div
              class="confirm-btn"
              @click="comfirmSubmit"
            >
              {{ $t('table.confirm') }}
            </div>
          </div>
        </div>
        <div class="shelter-layer" />
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import * as api from '@/api/multishop/shop-process.js'
import { ElMessage } from 'element-plus'
const props = defineProps({
  // 签约分类列表
  parentBrandList: {
    type: Array,
    default () {
      return []
    }
  }
})
const emit = defineEmits(['closePopup'])

const visible = ref(false)
const keyword = ref('')
const allBrandList = ref([])
const signBrandList = ref([])

// 是否显示自定义品牌
const showCustomization = ref(true)
const signBrandLength = ref(0)

// eslint-disable-next-line no-unused-vars
const validateFirstLetter = (rule, value, callback) => {
  const regexp = /^[A-Z]{1}$/
  if (!regexp.test(value)) {
    callback(new Error($t('multishop.shopProcess.oneCapitalLetter')))
  } else {
    callback()
  }
}

const dataForm = computed(() => {
  return {
    customSignBrandList: [],
    customSignBrandRule: {
      name: [
        { required: true, message: $t('multishop.shopProcess.brandEmpty'), trigger: 'blur' },
        { min: 1, max: 50, message: $t('multishop.shopProcess.brandBetween'), trigger: 'blur' }
      ],
      category: [
        { required: true, message: $t('multishop.shopProcess.brandClassificationEmpty'), trigger: ['blur', 'change'] }
      ],
      firstLetter: [
        { required: true, message: $t('multishop.shopProcess.firstLetterEmpty'), trigger: 'blur' },
        { validator: validateFirstLetter, trigger: 'blur' }
      ]
    }
  }
})

// 初始化
const init = (pageType) => {
  visible.value = true
  if (pageType === 'editor') {
    showCustomization.value = false
  }
  getPlatformBrand()
  getSignBrandList()
}

defineExpose({
  init
})
/**
 * 图片的值发生改变，重新校验对应表单字段
 * @param {String} value 改变的值
 */
const imgChange = (value) => {
  if (value) {
    // brandsInfoFormRef.value?.validate()
  }
}

/**
 * 获取平台全部品牌
 */
const getPlatformBrand = () => {
  api.getApplySigningBrand(keyword.value).then(data => {
    const _signBrandList = signBrandList.value
    brandEcho(data, _signBrandList)
  })
}

/**
 * 左侧回显选中品牌或已签约品牌
 * @param {Array} _allBrandList 全部品牌
 * @param {Array} signBrandListPar 选中品牌和已签约品牌
 */
const brandEcho = (_allBrandList, signBrandListPar) => {
  _allBrandList.forEach(item => {
    item.isSelected = false
  })
  if (signBrandListPar.length > 0 && _allBrandList.length > 0) {
    for (let i = 0; i < signBrandListPar.length; i++) {
      for (let j = 0; j < _allBrandList.length; j++) {
        if (signBrandListPar[i].brandId === _allBrandList[j].brandId) {
          _allBrandList[j].isSelected = true
          break
        }
      }
    }
  }
  allBrandList.value = _allBrandList
}

/**
 * 获取签约品牌列表
 */
const getSignBrandList = () => {
  api.getSignBrandList().then(data => {
    signBrandLength.value = data.platformBrandList.length
  })
}

/**
 * 搜索品牌
 */
const searchBrand = () => {
  getPlatformBrand()
}

/**
 * 选中添加品牌
 */
const addBrand = (brandObj, index) => {
  brandObj.brandStatus = brandObj.status
  const length = signBrandLength.value + signBrandList.value.length + dataForm.value.customSignBrandList.length
  if (length >= 50) {
    ElMessage.warning($t('multishop.shopProcess.maxBrand'))
  } else {
    if (brandObj.isSelected === false) {
      if (brandObj.categories) {
        brandObj.parentName = `${brandObj.categories[0].categories[0].name}>${brandObj.categories[0].categories[1].name}>${brandObj.categories[0].name}`
      }
      signBrandList.value.push(brandObj)
    }
    allBrandList.value[index].isSelected = true
  }
}

/**
 * 添加自定义品牌
 */
const addCustomBrand = () => {
  const length = signBrandLength.value + signBrandList.value.length + dataForm.customSignBrandList.length
  if (length >= 50) {
    ElMessage.warning($t('multishop.shopProcess.maxBrand'))
    return
  }
  dataForm.customSignBrandList.push(
    {
      name: '',
      firstLetter: '',
      categoryId: '',
      imgUrl: '',
      qualifications: ''
    }
  )
}

/**
 * 删除自定义品牌项
 */
const deleteCustomBrandItem = (index) => {
  dataForm.customSignBrandList.splice(index, 1)
}

/**
 * 删除选中品牌
 * @param {Number} id 品牌id
 * @param {Number} index 选中品牌列表索引
 */
const deleteBrand = (id, index) => {
  // 去除选中样式
  allBrandList.value.forEach(brandItem => {
    if (brandItem.brandId === id) {
      brandItem.isSelected = false
    }
  })
  signBrandList.value.splice(index, 1)
}

/**
 * 签约品牌
 */
const signBrand = () => {
  const params = {
    platformBrandList: [],
    customizeBrandList: []
  }
  signBrandList.value.forEach(item => {
    const param = {
      brandId: item.brandId,
      name: item.name,
      imgUrl: item.imgUrl,
      qualifications: item.qualifications
    }
    params.platformBrandList.push(param)
  })
  if (dataForm.customSignBrandList) {
    params.customizeBrandList = dataForm.customSignBrandList
  }
  api.addSigningBrand(params).then(() => {
    ElMessage({
      message: $t('multishop.shopProcess.brandSaveTips'),
      type: 'success',
      duration: 1000
    })
    closePopup()
  })
}

/**
 * 确认提交
 */
const brandsInfoFormRef = ref('')
const comfirmSubmit = () => {
  let pass = true
  if (dataForm.value.customSignBrandList.length) {
    brandsInfoFormRef.value?.validate((valid) => {
      if (dataForm.customSignBrandList && dataForm.customSignBrandList.find(el => !el.categoryId)) {
        dataForm.customSignBrandList.forEach(item => {
          if (item.categoryId === '') {
            item.categoryId = null
          }
        })
        pass = false
        return
      }
      if (!valid) {
        pass = false
        return
      }
      if (dataForm.customSignBrandList && dataForm.customSignBrandList.find(el => !el.name || !el.name.trim())) {
        ElMessage.error($t('multishop.shopProcess.brandEmpty'))
        pass = false
        return
      }
      if (dataForm.customSignBrandList && dataForm.customSignBrandList.find(el => !el.imgUrl)) {
        ElMessage.error($t('multishop.shopProcess.brandLogoEmpty'))
        pass = false
        return
      }
      if (dataForm.customSignBrandList && dataForm.customSignBrandList.find(el => !el.firstLetter)) {
        ElMessage.error($t('multishop.shopProcess.firstLetterEmpty'))
        pass = false
        return
      }
      if (dataForm.customSignBrandList && dataForm.customSignBrandList.find(el => !el.imgUrl)) {
        ElMessage.error($t('multishop.shopProcess.qualificationsEmpty'))
        pass = false
        return
      }
      if (dataForm.customSignBrandList && dataForm.customSignBrandList.find(el => !el.qualifications)) {
        ElMessage.error($t('multishop.shopProcess.qualificationsEmpty'))
        pass = false
      }
    })
  }
  if (signBrandList.value.find(el => !el.qualifications)) {
    ElMessage.error($t('multishop.shopProcess.qualificationsEmpty'))
    return
  }
  if (pass) {
    signBrand()
  }
}

/**
 * 关闭弹窗
 */
const closePopup = () => {
  emit('closePopup', 'brand')
}
</script>

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