<template>
  <div class="app-container">
    <!-- 检索区 -->
    <el-card shadow="never" class="search-card">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
        <el-form-item label="分类名称" prop="keyword">
          <el-input v-model="queryParams.keyword" placeholder="请输入分类名称" clearable style="width: 200px" @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 列表区 -->
    <el-card shadow="never" class="table-card">
      <el-alert type="info" :closable="false" class="mb12" title="平台全部分类（shop_id 为空），与店铺分类数据隔离" />
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAddLevel1" v-hasPermi="['agri:category:add']">添加一级分类</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['agri:category:remove']">批量删除</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table border v-loading="loading" :data="categoryList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="分类名称" align="left" min-width="160">
          <template slot-scope="scope">
            <span :class="{ 'level2-name': scope.row.categoryLevel === '2' }">
              {{ scope.row.categoryLevel === '2' ? '└ ' : '' }}{{ scope.row.categoryName }}
            </span>
            <el-tag v-if="scope.row.categoryLevel === '1'" size="mini" type="info" class="level-tag">一级</el-tag>
            <el-tag v-else size="mini" class="level-tag">二级</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="上级分类" align="center" prop="parentName" width="120">
          <template slot-scope="scope">
            <span>{{ scope.row.parentName || '—' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="分类图片" align="center" width="90">
          <template slot-scope="scope">
            <image-preview :src="scope.row.categoryPic" :width="50" :height="50" />
          </template>
        </el-table-column>
        <el-table-column label="是否显示" align="center" width="90">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.showFlag === '1'" type="success" size="small">是</el-tag>
            <el-tag v-else type="info" size="small">否</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="是否热门" align="center" width="90">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.hotFlag === '1'" type="warning" size="small">是</el-tag>
            <el-tag v-else type="info" size="small">否</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="排序" align="center" prop="sortNo" width="70" />
        <el-table-column label="操作" align="center" width="220" fixed="right">
          <template slot-scope="scope">
            <el-button v-if="scope.row.canAddChild" size="mini" type="text" icon="el-icon-plus" @click="handleAddChild(scope.row)" v-hasPermi="['agri:category:add']">添加子分类</el-button>
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['agri:category:edit']">编辑</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['agri:category:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!-- 添加/编辑弹窗 -->
    <el-dialog :title="title" :visible.sync="open" width="560px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-form-item label="分类层级">
          <span>{{ form.categoryLevel === '2' ? '二级分类' : '一级分类' }}</span>
        </el-form-item>
        <el-form-item v-if="form.categoryLevel === '2'" label="上级分类" prop="parentId">
          <el-select v-model="form.parentId" placeholder="请选择一级分类" style="width: 100%" :disabled="!!form.categoryId">
            <el-option v-for="item in level1List" :key="item.categoryId" :label="item.categoryName" :value="item.categoryId" />
          </el-select>
        </el-form-item>
        <el-form-item label="分类名称" prop="categoryName">
          <el-input v-model="form.categoryName" placeholder="请输入分类名称" maxlength="64" />
        </el-form-item>
        <el-form-item label="分类图片" prop="categoryPic">
          <image-upload v-model="form.categoryPic" :limit="1" :file-size="5" :file-type="['png', 'jpg', 'jpeg']" />
        </el-form-item>
        <el-form-item label="排序" prop="sortNo">
          <el-input-number v-model="form.sortNo" :min="0" :precision="0" controls-position="right" />
        </el-form-item>
        <el-form-item label="是否显示" prop="showFlag">
          <el-radio-group v-model="form.showFlag">
            <el-radio label="1">是</el-radio>
            <el-radio label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否热门" prop="hotFlag">
          <el-radio-group v-model="form.hotFlag">
            <el-radio label="1">是</el-radio>
            <el-radio label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCategory, level1Options, addCategory, updateCategory, delCategory } from "@/api/agri/category"

export default {
  name: "AgriCategory",
  data() {
    return {
      loading: true,
      ids: [],
      multiple: true,
      showSearch: true,
      total: 0,
      categoryList: [],
      level1List: [],
      title: "",
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyword: undefined
      },
      form: {},
      rules: {
        categoryName: [{ required: true, message: "请输入分类名称", trigger: "blur" }],
        categoryPic: [{ required: true, message: "请上传分类图片", trigger: "change" }],
        parentId: [{ required: true, message: "请选择上级分类", trigger: "change" }],
        showFlag: [{ required: true, message: "请选择是否显示", trigger: "change" }],
        hotFlag: [{ required: true, message: "请选择是否热门", trigger: "change" }],
        sortNo: [{ required: true, message: "请输入排序", trigger: "blur" }]
      }
    }
  },
  created() {
    this.getList()
    this.loadLevel1Options()
  },
  methods: {
    /** 查询分类列表 */
    getList() {
      this.loading = true
      listCategory(this.queryParams).then(response => {
        this.categoryList = response.rows || []
        this.total = response.total || 0
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    /** 加载一级分类下拉 */
    loadLevel1Options() {
      level1Options().then(response => {
        this.level1List = response.data || []
      }).catch(() => {})
    },
    reset() {
      this.form = {
        categoryId: undefined,
        categoryLevel: "1",
        parentId: 0,
        categoryName: undefined,
        categoryPic: undefined,
        sortNo: 0,
        showFlag: "1",
        hotFlag: "0"
      }
      this.resetForm("form")
    },
    cancel() {
      this.open = false
      this.reset()
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.categoryId)
      this.multiple = !selection.length
    },
    /** 添加一级分类 */
    handleAddLevel1() {
      this.reset()
      this.form.categoryLevel = "1"
      this.form.parentId = 0
      this.open = true
      this.title = "添加一级分类"
    },
    /** 添加二级分类 */
    handleAddChild(row) {
      this.reset()
      this.form.categoryLevel = "2"
      this.form.parentId = row.categoryId
      this.open = true
      this.title = "添加子分类"
    },
    /** 编辑分类 */
    handleUpdate(row) {
      this.reset()
      this.form = { ...row }
      if (this.form.categoryLevel === "1") {
        this.form.parentId = 0
      }
      this.open = true
      this.title = "编辑分类"
    },
    /** 提交 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return
        }
        const payload = { ...this.form }
        if (payload.categoryLevel === "1") {
          payload.parentId = 0
        }
        const submitFn = payload.categoryId != undefined ? updateCategory : addCategory
        submitFn(payload).then(() => {
          this.$modal.msgSuccess(payload.categoryId != undefined ? "修改成功" : "新增成功")
          this.open = false
          this.getList()
          this.loadLevel1Options()
        })
      })
    },
    /** 删除分类 */
    handleDelete(row) {
      const categoryIds = row.categoryId || this.ids
      const isLevel1 = row.categoryId && row.categoryLevel === "1"
      const msg = isLevel1
        ? "删除一级分类将同时删除其下全部二级分类，是否继续？"
        : "确认删除所选分类？分类下存在商品时无法删除"
      this.$modal.confirm(msg).then(() => {
        return delCategory(categoryIds)
      }).then(() => {
        this.$modal.msgSuccess("删除成功")
        this.getList()
        this.loadLevel1Options()
      }).catch(() => {})
    }
  }
}
</script>

<style scoped>
.search-card {
  margin-bottom: 10px;
}
.mb12 {
  margin-bottom: 12px;
}
.level2-name {
  padding-left: 8px;
}
.level-tag {
  margin-left: 6px;
}
</style>
