<template>
  <div class="brandClassification">
    <div class="head-title">
      品牌分类管理
      <div>
        <el-button style="float: right; margin-top: -25px" size="small" type="primary" @click="goAdd">
          新增分类
        </el-button>
      </div>
    </div>
    <div style="margin-top: 10px; background: #fff; padding: 20px">
      <div v-loading="loading" class="cat-container">
        <el-card class="card-item-box" shadow="never">
          <div slot="header" class="card-header">
            <span class="header-title">一级分类</span>
            <span class="header-count">{{ tableData.length }} 条</span>
          </div>
          <div class="card-body">
            <div class="list-item" :class="{ active: activeIndex == item.ID }" @click="getChild(item, index)"
              v-for="(item, index) in tableData" :key="index">
              <div class="item-left">
                <div v-if="!item.Logo" class="item-logo noIcon"></div>
                <div v-else class="item-logo" :style="{ backgroundImage: 'url(' + item.Logo + ')' }"></div>
                <div class="item-info">
                  <el-tooltip class="item" effect="dark" :content="item.ClassName" placement="top">
                    <span class="item-name">{{ item.ClassName }}</span>
                  </el-tooltip>
                  <span class="item-id">ID: {{ item.ID }}</span>
                </div>
              </div>
              <div class="item-actions">
                <el-button @click.stop="editNews(item)" type="text" size="small" class="action-btn edit">编辑</el-button>
                <el-button @click.stop="delNews(item)" type="text" size="small" class="action-btn delete">删除</el-button>
              </div>
            </div>
            <div v-if="tableData.length == 0" class="empty-state">
              <i class="el-icon-folder-opened" style="font-size: 48px; color: #c0c4cc"></i>
              <p>暂无数据</p>
            </div>
          </div>
        </el-card>

        <el-card class="card-item-box" shadow="never">
          <div slot="header" class="card-header">
            <span class="header-title">二级分类</span>
            <span class="header-count">{{ childTableData.length }} 条</span>
          </div>
          <div class="card-body">
            <div class="list-item" v-for="(item, index) in childTableData" :key="index">
              <div class="item-left">
                <div v-if="!item.Logo" class="item-logo noIcon"></div>
                <div v-else class="item-logo" :style="{ backgroundImage: 'url(' + item.Logo + ')' }"></div>
                <div class="item-info">
                  <el-tooltip class="item" effect="dark" :content="item.ClassName" placement="top">
                    <span class="item-name">{{ item.ClassName }}</span>
                  </el-tooltip>
                  <span class="item-id">ID: {{ item.ID }}</span>
                </div>
              </div>
              <div class="item-actions">
                <el-button @click.stop="editChildNews(item)" type="text" size="small" class="action-btn edit">编辑
                </el-button>
                <el-button @click.stop="delChildNews(item)" type="text" size="small" class="action-btn delete">删除
                </el-button>
              </div>
            </div>
            <div v-if="childTableData.length == 0" class="empty-state">
              <i class="el-icon-folder-opened" style="font-size: 48px; color: #c0c4cc"></i>
              <p>请先选择一级分类</p>
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 选择文件 -->
    <el-dialog title="选择文件" :visible.sync="isShowImage" width="1240px">
      <ChooseImg @SelectId="SelectId"></ChooseImg>
    </el-dialog>

    <!-- 新增/编辑弹窗 -->
    <el-dialog :title="addMsg.ID > 0 ? '编辑品牌分类' : '新增品牌分类'" :visible.sync="dialogVisible" width="500px">
      <el-form label-width="100px" :model="addMsg" :rules="rules" ref="addMsgForm">
        <el-form-item label="分类级别" label-width="100px" class="is-required">
          <el-radio-group v-model="addLevel" @change="onLevelChange">
            <el-radio :label="1">一级分类</el-radio>
            <el-radio :label="2">二级分类</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="上级分类" v-if="addLevel === 2" class="is-required" prop="ParentId">
          <el-select v-model="addMsg.ParentId" placeholder="请选择上级分类" size="small" style="width: 100%" filterable>
            <el-option v-for="item in tableData" :key="item.ID" :label="item.ClassName" :value="item.ID"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分类名称" class="is-required" prop="ClassName">
          <el-input type="text" v-model="addMsg.ClassName" size="small" placeholder="品牌分类名称" maxlength="100">
          </el-input>
        </el-form-item>
        <!--class="is-required" prop="Logo"-->
        <el-form-item label="Logo" >
          <el-button @click="isShowImage = true" size="small">选择文件</el-button>
          <div style="position: relative; width: 100px; margin-top: 10px; border: none">
            <img v-if="!addMsg.Logo || addMsg.Logo == ''" src="../../assets/img/default.png"
              style="width: 80px; height: 80px" alt="" />
            <img v-else style="width: 80px; height: 80px" :src="addMsg.Logo" alt="" />
          </div>
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="addMsg.SortNum" :min="0" :max="9999" size="small"></el-input-number>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" size="small">取消</el-button>
        <el-button type="primary" @click="submitform('addMsgForm')" size="small">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import ChooseImg from "@/components/global/ChooseImg.vue";
  export default {
    name: "brandClassification",
    components: {
      ChooseImg,
    },
    data() {
      return {
        val: "",
        loading: false,
        msg: {
          ClassName: "",
          BrandCategory: 3,
          ParentId: 0,
        },
        total: 0,
        tableData: [],
        childTableData: [],
        activeIndex: 0,
        currentParentId: null,
        currentParentName: "",
        addLevel: 1,
        isShowImage: false,
        dialogVisible: false,
        addMsg: {
          ID: 0,
          Logo: "",
          ClassName: "",
          ParentId: 0,
          BrandCategory: 3,
          SortNum: 0,
        },
        rules: {
          ClassName: [{
            required: true,
            message: "请输入品牌分类名称",
            trigger: "blur",
          }, ],
          Logo: [{
            required: true,
            message: "请选择Logo",
            trigger: "blur",
          }, ],
          ParentId: [{
            required: true,
            message: "请选择上级分类",
            trigger: "change",
          }, ],
        },
      };
    },
    created() {
      this.getList();
    },
    methods: {
      goAdd() {
        this.addMsg.ID = 0;
        this.addMsg.Logo = "";
        this.addMsg.ClassName = "";
        this.addMsg.ParentId = 0;
        this.addMsg.SortNum = 0;
        this.addLevel = 1;
        this.dialogVisible = true;
      },
      onLevelChange(val) {
        if (val === 1) {
          this.addMsg.ParentId = 0;
        } else {
          if (this.tableData.length > 0) {
            this.addMsg.ParentId = this.tableData[0].ID;
          }
        }
      },
      SelectId(msg) {
        let url = this.getIconLink(msg.url);
        this.addMsg.Logo = url;
        this.isShowImage = false;
      },
      getChild(item, index) {
        this.activeIndex = item.ID;
        this.currentParentId = item.ID;
        this.currentParentName = item.ClassName;
        // 从树形数据的 subList 获取二级分类
        this.childTableData = item.subList || [];
      },
      getList() {
        this.loading = true;
        this.apipost("/api/Trade/GetBrandClassTreeEdit", this.msg, (res) => {
          this.loading = false;
          if (res.data.resultCode == 1) {
            let pageData = res.data.data || [];
            pageData.forEach((item) => {
              item.checked = false;
              if (item.subList && item.subList.length > 0) {
                item.subList.forEach((child) => {
                  child.checked = false;
                });
              }
            });
            this.tableData = pageData;
            // 刷新后保持之前选中的分类
            if (this.currentParentId) {
              // 找到之前选中的一级分类
              const selectedItem = pageData.find((item) => item.ID === this.currentParentId);
              if (selectedItem) {
                this.getChild(selectedItem, 0);
              } else if (pageData.length > 0) {
                // 之前选中的被删了，选中第一个
                this.getChild(pageData[0], 0);
              } else {
                this.childTableData = [];
                this.activeIndex = 0;
              }
            } else if (pageData.length > 0) {
              // 首次加载默认选中第一大类
              this.getChild(pageData[0], 0);
            }
          }
        });
      },
      delNews(item) {
        let that = this;
        that.Confirm("删除一级分类会对应删除相应的二级分类,是否继续?", function () {
          that.apipost(
            "/api/Trade/RemoveBrandClass", {
              Id: item.ID,
              Status: 1
            },
            (res) => {
              if (res.data.resultCode == 1) {
                that.Success(res.data.message);
                that.getList();
              } else {
                that.Error(res.data.message);
              }
            }
          );
        });
      },
      editNews(item) {
        this.apipost(
          "/api/Trade/GetBrandClassDetails", {
            ID: item.ID
          },
          (res) => {
            if (res.data.resultCode == 1) {
              this.dialogVisible = true;
              this.addLevel = 1;
              var tempData = res.data.data;
              this.addMsg.ID = tempData.ID;
              this.addMsg.Logo = tempData.Logo;
              this.addMsg.ClassName = tempData.ClassName;
              this.addMsg.ParentId = tempData.ParentId || 0;
              this.addMsg.SortNum = tempData.SortNum || 0;
            } else {
              this.Error(res.data.message);
            }
          }
        );
      },
      delChildNews(item) {
        let that = this;
        that.Confirm("是否删除?", function () {
          that.apipost(
            "/api/Trade/RemoveBrandClass", {
              Id: item.ID,
              Status: 1
            },
            (res) => {
              if (res.data.resultCode == 1) {
                that.Success(res.data.message);
                that.getList();
              } else {
                that.Error(res.data.message);
              }
            }
          );
        });
      },
      editChildNews(item) {
        this.apipost(
          "/api/Trade/GetBrandClassDetails", {
            ID: item.ID
          },
          (res) => {
            if (res.data.resultCode == 1) {
              this.dialogVisible = true;
              this.addLevel = 2;
              var tempData = res.data.data;
              this.addMsg.ID = tempData.ID;
              this.addMsg.Logo = tempData.Logo;
              this.addMsg.ClassName = tempData.ClassName;
              this.addMsg.ParentId = tempData.ParentId || 0;
              this.addMsg.SortNum = tempData.SortNum || 0;
            } else {
              this.Error(res.data.message);
            }
          }
        );
      },
      submitform(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.apipost("/api/Trade/GetSetBrandClass", this.addMsg, (res) => {
              if (res.data.resultCode == 1) {
                this.dialogVisible = false;
                this.getList();
                this.Success(res.data.message);
              } else {
                this.Error(res.data.message);
              }
            });
          } else {
            return false;
          }
        });
      },
    },
  };

</script>

<style>
 
  .brandClassification .cat-container {
    display: flex;
    gap: 16px;
    min-height: 400px;
  }

  .brandClassification .card-item-box {
    flex: 1;
    min-width: 0;
  }

  .brandClassification .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .brandClassification .header-title {
    font-size: 15px;
    font-weight: 600;
    color: #303133;
  }

  .brandClassification .header-count {
    font-size: 12px;
    color: #909399;
    background: #f4f4f5;
    padding: 2px 8px;
    border-radius: 10px;
  }

  .brandClassification .card-body {
    max-height: 500px;
    overflow-y: auto;
  }

  .brandClassification .list-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12px 8px;
    border-bottom: 1px solid #f0f2f5;
    transition: background-color 0.2s;
    cursor: pointer;
  }

  .brandClassification .list-item:hover {
    background-color: #f5f7fa;
  }

  .brandClassification .list-item.active {
    background-color: #ecf5ff;
  }

  .brandClassification .list-item:last-child {
    border-bottom: none;
  }

  .brandClassification .item-left {
    display: flex;
    align-items: center;
    flex: 1;
    min-width: 0;
  }

  .brandClassification .item-logo {
    width: 36px;
    height: 36px;
    border-radius: 6px;
    background-size: cover;
    background-position: center;
    margin-right: 12px;
    flex-shrink: 0;
    border: 1px solid #ebeef5;
  }

  .brandClassification .item-logo.noIcon {
    background-image: url("../../assets/img/default.png");
    background-size: 100% 100%;
  }

  .brandClassification .item-info {
    display: flex;
    flex-direction: column;
    min-width: 0;
  }

  .brandClassification .item-name {
    font-size: 14px;
    color: #303133;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 150px;
  }

  .brandClassification .item-id {
    font-size: 12px;
    color: #909399;
    margin-top: 2px;
  }

  .brandClassification .item-actions {
    display: flex;
    gap: 8px;
    flex-shrink: 0;
  }

  .brandClassification .action-btn {
    padding: 4px 8px;
    font-size: 13px;
    border-radius: 4px;
    transition: all 0.2s;
  }

  .brandClassification .action-btn.edit {
    color: #409eff;
  }

  .brandClassification .action-btn.edit:hover {
    background-color: #ecf5ff;
  }

  .brandClassification .action-btn.delete {
    color: #f56c6c;
  }

  .brandClassification .action-btn.delete:hover {
    background-color: #fef0f0;
  }

  .brandClassification .empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 60px 0;
    color: #909399;
  }

  .brandClassification .empty-state p {
    margin-top: 12px;
    font-size: 14px;
  }

</style>
