<template>
  <el-dialog
    custom-class="center-dialog"
    :loading="loading"
    :title="title"
    top="0vh"
    :visible.sync="dialogFormVisible"
    width="60%"
    @close="close"
  >
    <el-row v-for="(categorys, index) in categoryOptions" :key="index">
      <el-row>
        <el-col :span="4">
          <span>{{ categorys.category_name }}</span>
        </el-col>
        <el-checkbox-group v-model="checkCategorys">
          <el-col :span="20">
            <el-checkbox
              v-for="cagegory in categorys.sub"
              :key="cagegory.category_id"
              :label="cagegory.category_id"
              @change="change(categorys.category_id, cagegory)"
            >
              {{ cagegory.category_name }}
            </el-checkbox>
          </el-col>
        </el-checkbox-group>
      </el-row>
      <el-row>
        <el-divider />
      </el-row>
    </el-row>
    <div slot="footer" class="dialog-footer">
      <el-button @click="close">{{ __('取消') }}</el-button>
      <el-button type="primary" @click="save">{{ __('确定') }}</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { translateTitle as __ } from '@/utils/i18n'
  import { categoryTree } from '@/api/base/product/category'
  import { doEdit } from '@/api/base/product/category/nav'

  export default {
    name: 'BaseProductCategorySpecEdit',
    data() {
      return {
        category_id: undefined,
        categoryOptions: [], // 所有数据
        checkCategorys: [], // 控件展示的选中数据
        saveCategorys: [], // 最终保存的数据
        loading: false,
        title: this.__('修改分类'),
        dialogFormVisible: false,
      }
    },
    created() {},
    methods: {
      change(pid, category) {
        let categories = this.getPCategory(pid).sub
        let index = this.hasCategory(categories, category.category_id)
        if (index !== -1) {
          categories.splice(index, 1)
          return
        }
        categories.push(category)
      },
      // 判断 categorys 是否包含 category_id 的元素
      hasCategory(categories, category_id) {
        for (let i = 0; i < categories.length; i++) {
          if (String(categories[i].category_id) === String(category_id)) {
            return i
          }
        }
        return -1
      },
      // 获取父级category
      getPCategory(pid) {
        return this.saveCategorys.find(
          (category) => String(category.category_id) === String(pid)
        )
      },
      async categoryTree(category_parent_id) {
        this.loading = true
        const { data } = await categoryTree({
          category_parent_id: category_parent_id,
        })
        this.dealCategoryOptions(data)
        this.loading = false
      },
      // 构建
      // checkCategorys saveCategorys 数据
      dealCategoryOptions(data) {
        if (!data || data.length === 0) this.categoryOptions = []
        data.forEach((category) => {
          const objCate = {
            category_id: category.category_id,
            category_image: category.category_image,
            category_is_enable: category.category_is_enable,
            category_name: category.category_name,
            id: category.category_id,
            sub: [],
          }
          // 复制对象
          this.saveCategorys.push(JSON.parse(JSON.stringify(objCate)))
          category.sub.forEach((cate) => {
            const obj = {
              category_id: cate.category_id,
              category_image: cate.category_image,
              category_is_enable: cate.category_is_enable,
              category_name: cate.category_name,
              id: cate.category_id,
              sub: [],
            }
            objCate.sub.push(obj)
          })
          this.categoryOptions.push(objCate)
        })
      },
      __,
      async showEdit(row) {
        this.category_id = row.category_id
        await this.categoryTree(this.category_id)
        let category_ids_recommend = row.category_ids_recommend

        if (category_ids_recommend.trim()) {
          const recommendArr = Array.from(JSON.parse(category_ids_recommend))
          this.dealSelectedCategory(recommendArr)
        }
        this.isEdit = true
        this.dialogFormVisible = true
      },
      dealSelectedCategory(recommendArr) {
        this.saveCategorys.forEach((p) => {
          recommendArr.forEach((r) => {
            if (String(p.category_id) === String(r.category_id)) p.sub = r.sub
          })
        })
        recommendArr.forEach((pCategory) => {
          Array.from(pCategory.sub).forEach((category) => {
            this.checkCategorys.push(Number(category.category_id))
          })
        })
      },
      close() {
        this.dialogFormVisible = false
        this.category_id = undefined
        this.categoryOptions = []
        this.checkCategorys = []
        this.saveCategorys = []
      },
      async save() {
        const obj = {
          category_id: this.category_id,
          category_ids_recommend: JSON.stringify(this.saveCategorys),
          isEdit: true,
        }
        const { msg, status } = await doEdit(obj)
        if (200 == status) {
          this.$baseMessage(msg, 'success')
        } else {
          this.$baseMessage(msg, 'error')
        }
        this.$emit('fetch-data')
        this.close()
      },
    },
  }
</script>
