<template>
  <div>
    <el-row>
      <el-col :span="6" style="padding: 10px 0 0 10px">
        <div class="toolbar">
          <div class="inner-toolbar">
            <div class="toolbar-btns">
              <span class="categary">商品类别</span>
              <el-button size="mini" v-if="checkPermission(['category:add'])" type="primary"
                @click="handleAddCategary">新增类别</el-button>
            </div>
          </div>
        </div>
        <el-tree :data="categorys" node-key="category_id" :expand-on-click-node="false"
          :style="{ height: categoryHeight }" :default-expanded-keys="expandedKeys" ref="categoryTree">
          <span class="custom-tree-node" slot-scope="{ node, data }" @click="handleSeachShop(data)">
            <span>{{ data.name }}</span>
            <span>
              <el-button type="text" size="mini" :disabled="node.level === 3" icon="el-icon-plus"
                :title="node.level === 3 ? '类别最多添加三级' : '增加'" v-if="checkPermission(['category:add'])"
                @click.stop="handleAddCategary(data)"></el-button>
              <el-button type="text" style="color: #f56c6c" size="mini" icon="el-icon-minus"
                v-if="checkPermission(['category:del'])" @click.stop="handleDeleteCategory(data)"></el-button>
              <el-button type="text" size="mini" icon="el-icon-edit" v-if="checkPermission(['category:edit'])"
                @click.stop="handleEditCategary(data)"></el-button>
              <!--  <el-button type="text" size="mini" icon="el-icon-setting" v-if="checkPermission(['category:spec'])"
                @click.stop="handleEditSpecs(data)">规格</el-button>
               <el-button
                type="text"
                size="mini"
                icon="el-icon-setting"
                v-if="checkPermission(['category:params'])"
                @click.stop="handleEditParams(data)"
                >参数</el-button
              > -->
            </span>
          </span>
        </el-tree>
      </el-col>
      <el-col :span="18">
        <en-table-layout :tableData="tableData.data" class="draggable-table" :row-key="getRowKeys" :loading="loading"
          style="margin: 10px 10px 0 10px">
          <div slot="toolbar" class="inner-toolbar">
            <div class="toolbar-btns">
              <el-button size="mini" v-if="checkPermission(['goodsAddForm'])" type="primary"
                @click="handleAddGoods('sail')">新增售卖商品</el-button>
              <el-button size="mini" v-if="checkPermission(['goodsAddForm'])" type="primary"
                @click="handleAddGoods('hire')">新增租赁商品</el-button>
            </div>
            <div class="toolbar-search" style="display: flex; align-items: center;">
              <span style=" white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">商品编号/序列号:</span>
              <en-table-search @search="searchEvent" placeholder="请输入关键字搜索" />
              <el-button style="margin-left: 5px;" @click="refresh" icon="el-icon-refresh" type="info" plain></el-button>
            </div>
          </div>

          <template slot="table-columns">
            <el-table-column prop="sn" label="商品编号" />
            <el-table-column prop="name" label="商品名称" />
            <el-table-column prop="category_id" label="商品类别">
              <template slot-scope="scope">
                {{ categorysName(scope.row.category_id) }}
              </template>
            </el-table-column>
            <el-table-column prop="brand_id" label="品牌">
              <template slot-scope="scope">
                {{ brand(scope.row.brand_id) }}
              </template>
            </el-table-column>
            <el-table-column prop="" label="商品形式"><template slot-scope="scope">
                {{ sailOrHire(scope.row.hire_or_sail) }}
              </template></el-table-column>

            <!-- <el-table-column prop="price" label="价格" :formatter="MixinFormatPrice"/>
            <el-table-column prop="label_names" label="商品标签"/> -->
            <el-table-column label="上架" key="market_enable" v-if="checkPermission(['goods:update'])">
              <template slot-scope="scope">
                <el-switch v-model="scope.row.market_enable" active-color="#13ce66" inactive-color="#ff4949"
                  @change="switchVal($event, scope.row)">
                </el-switch>
                <!-- <span>{{ scope.row.market_enable ? '上架' : '下架' }}</span> -->
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200px">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" v-if="checkPermission(['goodsEditForm'])"
                  @click="handleEditGoods(scope.row)">编辑</el-button>
                <el-button size="mini" v-if="checkPermission(['goods:delete'])" type="danger"
                  @click="handleDeleteGoods(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </template>

          <el-pagination v-if="tableData" slot="pagination" @size-change="handlePageSizeChange"
            @current-change="handlePageCurrentChange" :current-page="tableData.page_no" :page-sizes="[50, 70, 90, 100]"
            :page-size="tableData.page_size" layout="total, sizes, prev, pager, next, jumper"
            :total="tableData.data_total">
          </el-pagination>
        </en-table-layout>
      </el-col>
    </el-row>
    <!--编辑分类dialog-->
    <el-dialog :title="categoryForm.name ? '编辑类别' : '添加类别'" :visible.sync="dialogCategoryVisible" width="500px"
      :close-on-click-modal="false" :close-on-press-escape="false">
      <el-form :model="categoryForm" ref="categoryForm" label-width="100px">
        <el-form-item label="上级类别名称" prop="parent_id">
          <el-cascader v-model="categoryForm.parent_id" ref="cascaderHandle" :options="categorys" :props="{
            label: 'name',
            value: 'category_id',
            emitPath: false,
            checkStrictly: true,
          }" @change="handleChange" clearable></el-cascader>
        </el-form-item>
        <el-form-item label="商品类别名称" prop="category_name">
          <el-input v-model="categoryForm.category_name" :maxlength="12"></el-input>
        </el-form-item>
        <el-form-item label="商品类别编号" prop="custom_sn">
          <el-input v-model="categoryForm.custom_sn"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogCategoryVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitCategoryForm('categoryForm')">确 定</el-button>
      </span>
    </el-dialog>
    <!--编辑关联规格dialog-->
    <el-dialog title="关联规格" width="500px" :visible.sync="dialogSpecsVisible" :close-on-click-modal="false"
      :close-on-press-escape="false">
      <el-form :model="specsForm" ref="specsForm">
        <el-form-item label="选择规格">
          <el-select v-model="specsForm.selectedSpecsList" placeholder="请选择关联规格" multiple filterable
            style="width: 350px">
            <el-option v-for="item in specsForm.specsList" :key="item.id" :label="item.text" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogSpecsVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitSpecsForm()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import * as API_Goods from "@/api/goods";
import * as API_Category from "@/api/category";
import Sortable from "sortablejs";
import * as API_brand from "@/api/basicSetting";
export default {
  name: "productFile",
  data() {
    return {
      categorys: [],
      categoryForm: {},
      dialogCategoryVisible: false,
      // 列表loading状态
      loading: false,
      // 列表参数
      params: {
        page_no: 1,
        page_size: 50,
        category_id: "",
      },
      // 列表数据
      tableData: "",
      dialogSpecsVisible: false,
      // 编辑关联规格 表单
      specsForm: {
        category_id: null,
        selectedSpecsList: [],
        specsList: [],
      },
      // 左侧商品分类高度，和table保持一致
      categoryHeight: `${document.body.clientHeight - 219}px`,
      brandList: [],
      expandedKeys: [],

    };
  },
  mounted() {
    this.GET_ProductList();
    this.GET_Category();
    this.timer = setInterval(function () {
      document.querySelectorAll(".el-cascader-node__label").forEach((el) => {
        el.onclick = function () {
          if (this.previousElementSibling) this.previousElementSibling.click();
        };
      });
    }, 1000);
  },
  methods: {
    sailOrHire(val) {
      let name = "";
      if (val == "sail") {
        name = "售卖";
        return name;
      } else {
        name = "租赁";
        return name;
      }
    },
    brand(val) {
      let name = "";
      this.brandList.map((el) => {
        if (el.brand_id == val) {
          return (name = el.name);
        }
      });
      return name;
    },
    //获取类别名称
    categorysName(val) {
      /* let name = "";
      this.categorys.map((el) => {
        if (el.category_id == val) {
          return (name = el.name);
        }
      });
      return name; */
      let name = "";
      const findCategoryName = (categories, categoryId) => {
        for (const category of categories) {
          if (category.category_id === categoryId) {
            name = category.name;
            break;
          }
          if (category.children && category.children.length > 0) {
            findCategoryName(category.children, categoryId);
          }
        }
      };
      findCategoryName(this.categorys, val);
      return name;
    },
    getRowKeys(row) {
      return row.id;
    },
    // 行拖拽
    rowDrop() {
      const tbody = document.querySelector(".draggable-table .el-table__body-wrapper tbody");
      const _this = this;
      Sortable.create(tbody, {
        animation: 300,
        onEnd({ newIndex, oldIndex }) {
          const currRow = _this.tableData.data.splice(oldIndex, 1)[0];
          _this.tableData.data.splice(newIndex, 0, currRow);
          /*  console.log("拖拽后的行详情：", currRow); */
          _this.updateList(currRow.id, newIndex);
        },
      });
    },
    // 更新列表顺序
    updateList(id, newIndex) {
      // 假设API需要商品ID和新的索引位置
      console.log(this.tableData.data);
      /* API_Goods.updateSort({data:[{goods_id: id, sort: newIndex}]}).then((res) => {
          this.$message.success("更新成功！");
          this.GET_ProductList();
      }).catch(()=>{ this.$message.error("更新失败！");}) */
    },
    /*  updateList(id, sort) {
       API_Goods.updateSort({ goods_id: id, sort: sort }).then((res) => {
         if (res.errno != 0) {
           this.getList();
         }
       });
     }, 
     //行拖拽
     rowDrop() {
       const tbody = document.querySelector(
         ".draggable-table .el-table__body-wrapper tbody"
       );
       const _this = this;
       Sortable.create(tbody, {
         animation: 300,
         onEnd({ newIndex, oldIndex }) {
           const currRow = _this.tableData.data.splice(oldIndex, 1)[0];
           _this.tableData.data.splice(newIndex, 0, currRow);
           console.log(currRow);
           _this.updateList(currRow.id, currRow.sort);
         },
       });
     },*/
    switchVal(val, row) {
      API_Goods.updateGoods({ id: row.id, market_enable: val }).then((res) => {
        this.GET_ProductList();
      });
      // console.log(val,row);
    },
    handleChange(val) {
      this.categoryForm.parent_id = val;
      this.$refs.cascaderHandle.dropDownVisible = false; // 监听值发生变化就关闭它
    },
    handleEditGoods(row) {
      this.$router.push({
        name: "goodsEditForm",
        params: { id: row.id, hire_or_sail: row.hire_or_sail },
      });
    },
    /** 编辑关联规格 */
    handleEditSpecs(cat) {
      API_Category.getSpecsByCategoryId(cat.category_id).then((response) => {
        this.specsForm = {
          ...this.specsForm,
          category_id: cat.category_id,
          specsList: response,
          selectedSpecsList: response
            .filter((item) => item.selected)
            .map((item) => item.id),
        };
        this.dialogSpecsVisible = true;
      });
    },
    /** 编辑分类参数 */
    handleEditParams(cat) {
      this.$router.push({
        name: "categoryParams",
        params: { id: cat.category_id },
      });
    },
    /** 编辑关联规格 表单提交 */
    submitSpecsForm() {
      API_Category.updateCategorySpecs(
        this.specsForm.category_id,
        this.specsForm.selectedSpecsList
      ).then((response) => {
        this.dialogSpecsVisible = false;
        this.$message.success("保存成功！");
      });
    },
    refresh() {
      this.params.page_no = 1;
      this.params.category_id = "";
      this.GET_ProductList();
    },
    handleSeachShop(data) {
      this.params.page_no = 1;
      this.params.category_id = data.category_id;
      this.GET_ProductList();
    },
    submitCategoryForm(formName) {
      const { category_id } = this.categoryForm;
      if (!category_id) {
        API_Category.addCategory(this.categoryForm).then(() => {
          this.dialogCategoryVisible = false;
          this.$message.success("保存成功！");
          this.$refs[formName].resetFields();
          this.GET_Category();
        });
      } else {
        API_Category.editCategory(category_id, this.categoryForm).then(
          (response) => {
            this.$message.success("保存成功！");
            this.dialogCategoryVisible = false;
            this.$refs[formName].resetFields();
            this.GET_Category();
          }
        );
      }
    },
   /*  handleDeleteCategory(category) {
      this.$confirm("确定要删除这个分类吗？", "提示", { type: "warning" })
        .then(() => {
          API_Category.deleteCategory(category.category_id).then(() => {
            this.$message.success("删除成功！");
            this.GET_Category();
          });
        })
        .catch(() => {});
    } */handleDeleteCategory(data) {
      this.$nextTick(() => {
        const node = this.$refs.categoryTree.getNode(data.category_id);
        if (!node) {
          console.error('Node not found for category_id:', data.category_id);
          return;
        }

        // 保持父节点展开
        const parentNode = node.parent;
        if (parentNode && !this.expandedKeys.includes(parentNode.data.category_id)) {
          this.expandedKeys.push(parentNode.data.category_id);
        }

        // 执行删除操作
        this.$confirm("确定要删除这个分类吗？", "提示", { type: "warning" })
          .then(() => {
            API_Category.deleteCategory(data.category_id).then(() => {
              this.$message.success("删除成功！");
              this.GET_Category(); // 重新获取分类数据
              // 重新设置展开的节点，以防止收缩
              this.$nextTick(() => {
                this.$refs.categoryTree.store.expandedKeys = this.expandedKeys;
              });
            });
          })
          .catch(() => { });
      });
    },
    /** 添加类别 */
    handleAddCategary(category) {
      this.categoryForm = {
        parent_id: category ? category.category_id : 0,
      };
      this.dialogCategoryVisible = true;
    },
    /** 编辑类别  */
    handleEditCategary(category) {
      this.categoryForm = {
        parent_id: category.parent_id,
        category_id: category.category_id,
        category_name: category.name,
        custom_sn: category.custom_sn,
      };
      this.dialogCategoryVisible = true;
    },
    /** 获取类别 */
    GET_Category() {
      API_Category.getCategoryAllChildren("0").then((response) => {
        this.categorys = response;
      });
    },
    /** 分页大小发生改变 */
    handlePageSizeChange(size) {
      this.params.page_size = size;
      this.GET_ProductList();
    },

    /** 分页页数发生改变 */
    handlePageCurrentChange(page) {
      this.params.page_no = page;
      this.GET_ProductList();
    },

    /** 添加商品档案 */
    handleAddGoods(val) {
      console.log(val);
      this.$router.push({
        name: "goodsAddForm",
        params: { hire_or_sail: val },
      });
    },

    /** 删除商品档案 */
    handleDeleteGoods(row) {
      this.$confirm("确定要删除这个商品档案吗？", "提示", { type: "warning" })
        .then(() => {
          API_Goods.deleteGoods(row.id).then(() => {
            this.$message.success("删除成功！");
            this.GET_ProductList();
          });
        })
        .catch((error) => {
          console.log(error);
        });
    },

    /** 搜索事件触发 */
    searchEvent(data) {
      this.params = {
        ...this.params,
        keyword: data,
      };
      this.params.page_no = 1;
      this.GET_ProductList();
    },

    /** 获取商品档案列表 */
    GET_ProductList() {
      this.loading = true;
      API_Goods.getGoodsList(this.params)
        .then((response) => {
          this.loading = false;
          this.tableData = response;
        })
        .catch(() => {
          this.loading = false;
        });
      API_brand.getBrandList(this.params).then((response) => {
        this.loading = false;
        this.brandList = response.data;
      });
    },
  },
  watch: {
    $route: {
      immediate: true,
      handler(newVal) {
        if (newVal.name === "productFile") {
          this.GET_ProductList();
        }
      },
    },
  },
};
</script>

<style type="text/scss" lang="scss" scoped>
.toolbar {
  display: flex;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  height: 45px;
  border-bottom: 1px solid #e6ebf5;
  background-color: #fff;
}

.inner-toolbar {
  padding: 0 20px;

  .categary {
    padding-right: 10px;
    font-size: 14px;
  }
}

.face-image {
  display: block;
  width: 50px;
  height: 50px;
  margin: 0 auto;
}

/deep/ .el-dialog__body {
  padding: 10px 20px;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
  width: 500px;
}
</style>
