<template>
  <div>
    <el-dialog
      v-model="visible"
      :show-close="false"
      :close-on-click-modal="false"
      class="component-category-add-or-update"
      width="80%"
      top="8vh"
      @close="onClosePopup"
    >
      <div>
        <div class="popup">
          <div class="title">
            <div class="text">
              <span class="stress">*</span>新增签约类目
            </div>
            <div class="tips">
              请选择末级类目签约，已签约<span class="bold">{{ signCategoryList.length }}</span>个类目，最多可签约<span class="bold">200</span>个类目
            </div>
            <div
              class="close-btn"
              @click="onClosePopup"
            >
              <el-icon><Close /></el-icon>
            </div>
          </div>
          <div class="content">
            <div
              v-loading="loading"
              class="left-box"
              element-loading-text="数据处理中..."
            >
              <div class="tree-box">
                <el-tree
                  ref="categoryTreeRef"
                  :data="categorgTreeData"
                  node-key="categoryId"
                  :props="categoryListTreeProps"
                  class="filter-tree"
                  show-checkbox
                  :render-after-expand="false"
                  highlight-current
                  icon-class="el-icon-arrow-right"
                  :default-checked-keys="signCategoryIds"
                  @check="onCheckChange"
                  @node-click="onNodeClick"
                >
                  <template #default="{ data }">
                    <el-tooltip
                      :content="data.level === 2 ? data.name + ' ' + data.deductionRate + '%' : data.name"
                      placement="right"
                      effect="light"
                      :open-delay="500"
                      class="custom-tree-node"
                    >
                      <span>{{ data.level === 2 ? data.name + ' ' + data.deductionRate + '%' : data.name }}</span>
                    </el-tooltip>
                  </template>
                </el-tree>
              </div>
            </div>
            <div
              ref="tableBoxRef"
              class="right-box table-box"
            >
              <el-table
                :data="signCategories"
                :header-cell-style="{height:'50px',background:'#F5F5F5',color:'#000','font-weight': '400'}"
              >
                <el-table-column
                  prop="name"
                  label="类目"
                />
                <el-table-column
                  prop="parentName"
                  label="上级类目"
                />
                <el-table-column
                  prop="platformRate"
                  label="类目扣率"
                >
                  <template #default="{ row }">
                    <span>{{ row.platformRate }} %</span>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="qualifications"
                  label="经营资质"
                  width="230px"
                >
                  <template #default="scope">
                    <div
                      :key="scope.row.qualifications"
                      class="business-qual"
                    >
                      <imgs-upload
                        v-model="scope.row.qualifications"
                        :limit="2"
                      />
                    </div>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="categoryStatus"
                  label="状态"
                  width="80"
                >
                  <template #default="scope">
                    <div
                      v-if="scope.row.categoryStatus === 1"
                      class="tag-txt"
                    >
                      正常
                    </div>
                    <div
                      v-if="scope.row.categoryStatus === 0"
                      class="tag-txt red-tag-txt"
                    >
                      下架
                    </div>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="address"
                  :label="$t('table.actions')"
                  width="80px"
                >
                  <template #default="scope">
                    <el-button
                      type="primary"
                      link
                      @click="onDeleteSelectedCategory(scope)"
                    >
                      {{ $t('table.delete') }}
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
          <div class="btn-box">
            <div
              class="cancel-btn"
              @click="onClosePopup"
            >
              {{ $t('table.cancel') }}
            </div>
            <div
              class="confirm-btn"
              @click="onComfirmSubmit"
            >
              {{ $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 { enableCategories } from '@/api/product/category.js'
import { treeDataTranslate } from '@/utils/index.js'
import { ElMessage } from 'element-plus'
import { Debounce } from '@/utils/debounce'

const props = defineProps({
  // 签约分类列表
  signCategoryList: {
    type: Array,
    default () {
      return []
    }
  },
  push: {
    default: null,
    type: Function
  },
  deleteById: {
    default: null,
    type: Function
  },
  splice: {
    default: null,
    type: Function
  },
  map: {
    default: null,
    type: Function
  }
})
const emit = defineEmits(['closePopup'])

const categorgTreeData = ref([])
const categoryListTreeProps = reactive({
  value: 'categoryId',
  label: 'name'
})
const visible = ref(false)

// table渲染列表
const signCategories = ref([])
// 已选分类id数组
const signCategoryIds = ref([])
// 已选分类父分类id数组
const signCategoryParentIds = ref([])

const loading = ref(false)

const tableBoxRef = ref('')
const init = () => {
  getPlatformCategory()
  getSignCategoryList()
  visible.value = true

  nextTick(() => {
    tableBoxRef.value.addEventListener('scroll', onScroll, true)
  })
}
defineExpose({
  init
})
/**
 * 获取平台分类列表，并转换成树形结构
 */
const getPlatformCategory = () => {
  loading.value = true
  // 包含三级分类的分类列表
  enableCategories({ shopId: 0 }).then(data => {
    loading.value = false
    data = data.filter(item => item.status === 1)
    categorgTreeData.value = treeDataTranslate(data, 'categoryId', 'parentId')
    categorgTreeData.value = removeNotThirdCategoryItem(categorgTreeData.value)
  })
}
/**
 * 去除没有三级分类的类目
 */
const removeNotThirdCategoryItem = (treeData) => {
  const firstCategory = treeData
  const length = firstCategory.length
  for (let i = 0, index = 0; i < length; i++) {
    if (firstCategory[index].level !== 2) {
      if (firstCategory[index].children && firstCategory[index].children.length > 0 && (firstCategory[index].children.some(item => item.children) || firstCategory[index].level !== 0)) {
        const secondCategory = firstCategory[index].children
        firstCategory[index].children = removeNotThirdCategoryItem(secondCategory)
      } else {
        firstCategory.splice(index, 1)
        // 当前位置的元素已经被删除，当前位置索引不用++
        continue
      }
    }
    index++
  }
  return firstCategory
}

// 总已选分类
let newSignCategories = []
/**
 * 签约类目列表
 */
const getSignCategoryList = () => {
  newSignCategories = JSON.parse(JSON.stringify(props.signCategoryList))
  signCategories.value = newSignCategories.splice(0, 15)
  getIds(props.signCategoryList, 0)
}

const categoryTreeRef = ref('')
const getIds = (data, sts) => {
  signCategoryIds.value.splice(0, signCategoryIds.value.length)
  signCategoryParentIds.value.splice(0, signCategoryParentIds.value.length)
  data.forEach(el => {
    // 已选分类id
    signCategoryIds.value.push(el.categoryId)
    // 已选分类的父分类id
    signCategoryParentIds.value.push(el.parentId)
  })
  if (sts === 1) {
    nextTick(() => {
      categoryTreeRef.value.setCheckedKeys(signCategoryIds.value)
    })
  }
}
/**
 * 监听滚动
 */
const onScroll = () => {
  const tableWrapper = document.querySelector(
    '.right-box.table-box .el-table .el-table__body-wrapper'
  )
  const tableBody = document.querySelector(
    '.right-box.table-box .el-table .el-table__body-wrapper .el-table__body'
  )
  // 容器高度
  const boxHeight = tableWrapper.offsetHeight
  // 距离顶部距离
  const boxScrollTop = tableWrapper.scrollTop
  // 表格高度
  const tableHeight = tableBody.offsetHeight

  if (boxScrollTop >= (tableHeight - boxHeight)) {
    signCategories.value = signCategories.value.concat(newSignCategories.splice(0, 15))
  }
}

let message = false
/**
 * 对勾选到的数据逐一处理
 * @param nodeObj 节点数据
 * @param isExist 是否为选中状态
 * @returns {Promise<void>}
 */
const onCheckLevel = async (nodeObj, isExist) => {
  const isExistTwo = props.signCategoryList.some(item => item.categoryId === nodeObj.categoryId)
  if (nodeObj.level !== 2) {
    return
  }
  if (isExist) {
    if (props.signCategoryList.length >= 200) {
      if (!message) {
        message = true
        ElMessage({
          message: '最多可选择200个类目',
          type: 'error',
          duration: 1000,
          onClose: () => {
            message = false
          }
        })
      }
      getIds(props.signCategoryList, 1)
      return
    }
    if (isExistTwo) {
      return
    }
    const signCategoryObj = {
      categoryId: nodeObj.categoryId,
      name: nodeObj.name,
      parentName: nodeObj.parentName,
      platformRate: nodeObj.deductionRate,
      categoryStatus: nodeObj.status,
      qualifications: ''
    }
    props.push(signCategoryObj)
    newSignCategories.push(signCategoryObj)
    if (signCategories.value.length < 10) {
      signCategories.value = signCategories.value.concat(newSignCategories.splice(0, 10))
    } else {
      nextTick(() => {
        onScroll()
      })
    }
  } else {
    props.deleteById(nodeObj.categoryId, props.signCategoryList)
    newSignCategories = props.deleteById(nodeObj.categoryId, newSignCategories)
    signCategories.value = props.deleteById(nodeObj.categoryId, signCategories.value)
    nextTick(() => {
      onScroll()
    })
  }
}

/**
 * 将勾选到的数据进行遍历
 * @param nodeObj 勾选到的当前节点数据
 * @param isExist 判断是否为选中状态
 * @returns {Promise<void>}
 */
const onHandleCheck = async (nodeObj, isExist) => {
  await onCheckLevel(nodeObj, isExist)
  if (nodeObj.children && nodeObj.children.length > 0) {
    for (const item of nodeObj.children) {
      await onCheckLevel(item, isExist)
      if (item.children && item.children.length > 0) {
        for (const childItem of item.children) {
          if (props.signCategoryList.length >= 200 && isExist) {
            await getIds(props.signCategoryList, 1)
            return
          }
          await onCheckLevel(childItem, isExist)
        }
      }
    }
  }
}

/**
 * 节点选中状态发生变化时的回调
 * @param {Object} nodeObj 传递给 data 属性的数组中该节点所对应的对象
 * @param {Boolean} nodeStatus 树目前的选中状态对象
 */
const onCheckChange = async (nodeObj, nodeStatus) => {
  const isExist = nodeStatus.checkedKeys.includes(nodeObj.categoryId)
  if (nodeObj.level !== 2 && props.signCategoryList.length >= 200 && isExist) {
    ElMessage({
      message: '最多可选择200个类目',
      type: 'error',
      duration: 1000
    })
    await getIds(props.signCategoryList, 1)
    return
  }
  if (nodeObj.level === 2) {
    await onHandleCheck(nodeObj, isExist)
    return
  }
  loading.value = true
  setTimeout(() => {
    onHandleCheck(nodeObj, isExist).then(() => {
      loading.value = false
    })
  }, 200)
}

/**
 * 点击节点时触发
 * @param nodeObj 对应于节点点击的节点对象
 * @param nodeStatus TreeNode 的 node 属性
 * @returns {Promise<void>}
 */
const onNodeClick = async (nodeObj, nodeStatus) => {
  if (nodeStatus.level !== 3) return
  await onCheckLevel(nodeObj, !nodeStatus.checked)
  await getIds(props.signCategoryList, 1)
}

/**
 * 签约分类
 */
const signCategory = Debounce(() => {
  const params = []
  props.signCategoryList.forEach(item => {
    const param = {
      categoryId: item.categoryId,
      rate: item.platformRate,
      qualifications: item.qualifications ? item.qualifications : null
    }
    params.push(param)
  })
  api.signCategory(params).then(() => {
    ElMessage({
      message: '类目保存成功！',
      type: 'success',
      duration: 1000
    })
    onClosePopup()
  })
}, 1500)

/**
 * 确认提交
 */
const onComfirmSubmit = () => {
  if (props.signCategoryList.length > 0) {
    props.signCategoryList.forEach((el) => {
      signCategories.value.forEach((item) => {
        if (el.categoryId === item.categoryId) {
          el.qualifications = item.qualifications
        }
      })
    })
    signCategory()
  } else {
    ElMessage({
      message: '请选择至少一种分类',
      type: 'error',
      duration: 1000
    })
  }
}

/**
 * 删除已选分类
 */
const onDeleteSelectedCategory = (scope) => {
  const index = scope.$index
  props.splice(index, 1)
  signCategories.value.splice(index, 1)
  getIds(props.signCategoryList, 1)
  onScroll()
}

/**
 * 关闭弹窗
 */
const onClosePopup = () => {
  visible.value = false
  emit('closePopup', 'category')
}

</script>

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