<template>
  <view class="specification-container">
    <view class="specification-content">
      <favorite-loading
        class="specification-loading"
        v-show="loading"
        :color="'#fe4119'"
        text=""
        animation="spinner15"
      ></favorite-loading>
      <view class="no-data" v-if="specificationList.length <= 0 && !loading">
        <view class="no-data-bg"></view>
        <view class="no-data-tips">暂无规格</view>
      </view>
      <scroll-view
        v-if="specificationList.length > 0 && !loading"
        scroll-y
        scroll-with-animation
        :show-scrollbar="false"
        @scrolltolower="handerScrolltolower"
        refresher-enabled
        :refresher-triggered="isRefreshing"
        @refresherrefresh="handleRefresh"
        class="specification-scroll"
      >
        <view
          class="specification-item"
          v-for="(item, index) of specificationList"
        >
          <view class="specification-info">
            <view class="specification-name">{{ item.spec_name }}</view>
            <view class="specification-classify">
              分类：
              <text style="color: red" v-if="item.spec_category_id == 0">
                未绑定分类
              </text>
              <text v-else>{{ handerCategoryName(item) }}</text>
            </view>
            <view class="specification-sort">排序：{{ item.spec_order }}</view>
          </view>
          <view class="specification-btn-content">
            <u-icon
              class="u-icon-jianhao"
              custom-prefix="custom-icon-jianhao_fangxing custom-icon"
              size="24"
              @click="handerShowDelectPopup(item)"
            ></u-icon>
            <u-icon
              class="u-icon-bianji"
              @click="handerShowEeditPopup(item)"
              custom-prefix="custom-icon-icon_519 custom-icon"
              size="24"
            ></u-icon>
          </view>
        </view>
        <view
          class="m-loading-box"
          v-if="specificationList.length > 0 && !isNoSpecificationData"
        >
          <block v-if="loadingDownSpecificationData">
            <view class="u-loadmore">
              <view class="u-loading"></view>
              <text class="u-loadmore-tips">正在加载...</text>
            </view>
          </block>
          <block v-else>
            <view class="u-loadmore u-loadmore-line">
              <text class="u-loadmore-tips">没有更多商品类型了 ~</text>
            </view>
          </block>
        </view>
      </scroll-view>
    </view>
    <view class="specification-bottom">
      <view class="bottom-list">
        <u-button
          class="bottom-btn-item"
          :hairline="true"
          :plain="true"
          shape="circle"
          @click="handerAddAndEditPopup(true)"
        >
          <u-icon class="bottom-icon" name="plus-circle"></u-icon>
          新建规格
        </u-button>
      </view>
    </view>
    <u-popup
      class="add-popup"
      zIndex="10077"
      :show="showAddAndEditPopup"
      mode="center"
      @close="handerCloseAddAndEditPopup"
    >
      <view class="add-popup-content">
        <view class="add-popup-title">
          {{ isAdd ? "添加规格" : "编辑规格" }}
        </view>
        <u--form
          labelPosition="left"
          :model="form"
          ref="uForm"
          label-width="100"
          :rules="rules"
        >
          <u-form-item
            label="规格名称"
            prop="spec_name"
            class="form-item"
            required
          >
            <u--textarea
              class="u-textarea"
              v-model="form.spec_name"
              count
              autoHeight
              maxlength="20"
              placeholder="请输入规格名称"
            ></u--textarea>
          </u-form-item>
          <u-form-item
            label="商品分类"
            prop="type_name"
            class="form-item"
            @click="hadnerShowClassifyListPopup()"
          >
            <u--input
              v-model="form.spec_category_name"
              disabled
              disabledColor="#ffffff"
              placeholder="请选择商品分类"
              border="none"
              @click="hideKeyboard()"
            ></u--input>
            <u-icon slot="right" name="arrow-right"></u-icon>
          </u-form-item>
          <u-form-item label="分类排序" prop="spec_order" class="form-item">
            <u--input
              v-model="form.spec_order"
              type="number"
              placeholder="请输入商品排序"
              border="none"
            ></u--input>
          </u-form-item>
        </u--form>
        <view class="popup-btn-list">
          <u-button
            class="btn-item"
            :hairline="true"
            :plain="true"
            shape="circle"
            @click="showAddAndEditPopup = false"
          >
            取消
          </u-button>
          <u-button
            class="btn-item btn-item-2"
            :hairline="true"
            :plain="true"
            shape="circle"
            @click="handerAffirmAddAndEdit"
          >
            {{ isAdd ? "添加" : "修改" }}
          </u-button>
        </view>
      </view>
    </u-popup>
    <tki-tree
      ref="tkitree"
      :range="baTreePickerList"
      :foldAll="true"
      rangeKey="category_name"
      idKey="category_id"
      title="选择商品分类"
      @confirm="treeConfirm"
      @cancel="treeCancel"
    ></tki-tree>

    <u-popup
      class="affirm-popup"
      zIndex="10077"
      :show="showDelectPopup"
      mode="center"
    >
      <view class="affirm-popup-content">
        <view class="affirm-popup-title">
          确认删除"{{ currDelectItem.spec_name }}"规格?
        </view>
        <view class="popup-btn-list">
          <u-button
            class="btn-item"
            :hairline="true"
            :plain="true"
            shape="circle"
            @click="showDelectPopup = false"
          >
            取消
          </u-button>
          <u-button
            class="btn-item btn-item-2"
            :hairline="true"
            :plain="true"
            shape="circle"
            @click="handerDelectClassify"
          >
            确认
          </u-button>
        </view>
      </view>
    </u-popup>
    <u-toast ref="uToast"></u-toast>
  </view>
</template>

<script>
import {
  GetSpecificationList,
  UpdateSpecification,
  DelectSpecification,
} from "@/api/warehouse/specification";
import { GetCommodityClassify } from "@/api/warehouse/classifyList";
import tkiTree from "./components/tree/tree";
export default {
  name: "specification",
  components: {
    tkiTree,
  },
  data() {
    return {
      loading: false,
      loadingClassIfy: false,
      pageNum: 1,
      pageSize: 20,
      specificationList: [],
      currDelectItem: {},
      showDelectPopup: false,
      showAddAndEditPopup: false,
      form: {
        spec_name: "",
        spec_order: "",
        spec_category_id: 0,
        spec_format: "text",
        spec_category_name: "",
      },
      isAdd: false,
      rules: {
        spec_name: [
          {
            required: true,
            message: "请输入规格名称",
            // 可以单个或者同时写两个触发验证方式
            trigger: ["change", "blur"],
          },
        ],
      },
      baTreePickerList: [],
      isRefreshing: false,
      isNoSpecificationData: false,
      loadingDownSpecificationData: false,
      isNoDownSpecificationData: false,
      time: null,
    };
  },
  computed: {},
  onLoad: function (options) {},
  onReady() {},
  onShow() {
    this.getCommodityClassify();
    this.getSpecificationList();
  },

  mounted() {},
  methods: {
    async getCommodityClassify() {
      this.loadingClassIfy = true;
      let res = await GetCommodityClassify();
      if (res && res.status == 200) {
        const classifyList = res.data;
        if (classifyList.length > 0) {
          this.baTreePickerList = classifyList.map((item) => {
            // 创建父节点，并保留所有原始字段
            const parentNode = {
              ...item, // 保留所有原始数据
              children: null, // 先初始化为 null
            };

            // 如果有子分类，递归处理
            if (item.sub && item.sub.length > 0) {
              parentNode.children = item.sub.map((subItem) => ({
                ...subItem, // 保留所有子分类的原始数据
              }));
            }

            return parentNode;
          });
        }
      }
      this.loadingClassIfy = false;
    },
    async getSpecificationList(isNoLoading = true) {
      if (isNoLoading) {
        this.loading = true;
      }

      let params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
      };

      let res = await GetSpecificationList(params);
      if (res && res.status == 200) {
        if (this.loadingDownSpecificationData) {
          if (res.data.items.length <= 0) {
            this.loadingDownSpecificationData = false;
            this.isNoDownSpecificationData = true;
          } else {
            this.specificationList = [
              ...this.specificationList,
              ...res.data.items,
            ];
          }
        } else {
          this.specificationList = res.data.items;
        }

        if (this.specificationList.length <= 0) {
          this.isNoSpecificationData = true;
        }
      }
      this.loading = false;
      this.isRefreshing = false;
      this.loadingDownSpecificationData = false;
    },
    handerScrolltolower() {
      clearTimeout(this.time);
      if (this.isNoDownTypeManageData) return;
      this.loadingDownSpecificationData = true;
      this.pageNum = this.pageNum + 1;
      this.time = setTimeout(() => {
        this.getSpecificationList(false);
      }, 500);
    },
    handleRefresh() {
      this.isRefreshing = true;
      this.pageNum = 1;
      this.getSpecificationList();
    },
    handerShowDelectPopup(item) {
      this.currDelectItem = item;
      this.showDelectPopup = true;
    },
    handerCategoryName(item) {
      if (item) {
        const findCategory = (categories, targetId) => {
          for (const category of categories) {
            if (category.category_id === targetId) {
              return category;
            }

            if (category.children && category.children.length > 0) {
              const foundInSub = findCategory(category.children, targetId);
              if (foundInSub) return foundInSub;
            }
          }
          return null;
        };

        if (this.baTreePickerList.length > 0) {
          const matchedCategory = findCategory(
            this.baTreePickerList,
            item.spec_category_id
          );

          return (matchedCategory && matchedCategory.category_name) || "";
        }
      }
    },
    handerShowEeditPopup(item) {
      this.isAdd = false;
      item = {
        spec_category_name: "",
        ...item,
      };
      this.form = item;

      const findCategory = (categories, targetId) => {
        for (const category of categories) {
          if (category.category_id === targetId) {
            return category;
          }

          if (category.children && category.children.length > 0) {
            const foundInSub = findCategory(category.children, targetId);
            if (foundInSub) return foundInSub;
          }
        }
        return null;
      };

      if (this.baTreePickerList.length > 0) {
        const matchedCategory = findCategory(
          this.baTreePickerList,
          item.spec_category_id
        );
        if (matchedCategory) {
          this.form.spec_category_name = matchedCategory.category_name;
        }
      }
      this.showAddAndEditPopup = true;
    },
    hadnerShowClassifyListPopup() {
      this.$refs.tkitree._show();
    },
    handerAddAndEditPopup(isAdd) {
      this.isAdd = isAdd;
      this.form = {
        spec_name: "",
        spec_order: "",
        spec_category_id: 0,
        spec_format: "text",
        spec_category_name: "",
      };
      this.showAddAndEditPopup = true;
    },
    handerAffirmAddAndEdit() {
      let params = this.form;

      this.$refs.uForm.validate().then(async () => {
        let res = await UpdateSpecification(params);
        if (res && res.status == 200) {
          this.$refs.uToast.show({
            message: this.isAdd ? "添加成功" : "修改成功",
            type: "succeed",
            duration: 1000,
          });
          this.showAddAndEditPopup = false;

          // 静默更新，不影响当前数组
          let params = {
            pageSize: 9999,
            pageNum: 1,
          };

          let res = await GetSpecificationList(params);
          if (res && res.status == 200) {
            this.specificationList = res.data.items;
          }

          this.form = {
            spec_name: "",
            spec_order: "",
            spec_category_id: 0,
            spec_format: "text",
            spec_category_name: "",
          };
        }
      });
    },
    async handerDelectClassify() {
      let params = {
        spec_ids: this.currDelectItem.spec_id,
      };

      let res = await DelectSpecification(params);
      if (res && res.status == 200) {
        this.$refs.uToast.show({
          message: "删除成功",
          type: "succeed",
          duration: 1000,
        });
        this.showDelectPopup = false;
        this.specificationList = this.specificationList.filter(
          (item) => item.spec_id !== this.currDelectItem.spec_id
        );
      }
    },
    treeCancel() {
      this.$refs.tkitree._hide();
    },
    treeConfirm(list) {
      console.log(this.form);
      if (list.length > 1) {
        this.form.spec_category_name = list[1].category_name;
        this.form.spec_category_id = list[1].category_id;
      } else {
        this.form.spec_category_name = list[0].category_name;
        this.form.spec_category_id = list[0].category_id;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
@import "@/styles/variables.scss";
.specification-container {
  .specification-scroll {
    -ms-overflow-style: none; /* IE和Edge */
    scrollbar-width: none; /* Firefox */
    height: calc(100vh - 300rpx);
  }

  .specification-loading {
    margin: 70% auto;
    display: flex;
  }

  .no-data {
    .no-data-bg {
      margin: 50% auto;
      margin-bottom: 0;
      width: 300rpx;
      height: 200rpx;
      background-image: url("../../../static/warehouse/no-classify.png");
      background-size: 100%;
    }
    .no-data-tips {
      margin: 80rpx auto;
      color: #aaaaaa;
      text-align: center;
    }
  }

  .m-loading-box {
    text-align: center;
    padding: 40rpx;
    color: #aaaa;
    font-size: 28rpx;
  }

  .specification-content {
    padding: 24rpx;

    .specification-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin: 20rpx 0;
      margin-left: 40rpx;
      margin-bottom: 20px;

      .specification-info {
        .specification-name {
          font-size: 17px;
          font-weight: bold;
        }

        .specification-classify {
          font-size: 28rpx;
          margin: 16rpx 0;
          color: #606060;
        }

        .specification-sort {
          font-size: 15px;
          color: #606060;
        }
      }

      .specification-btn-content {
        display: flex;
        justify-content: space-around;
        width: 220rpx;

        .u-icon-jianhao {
          ::v-deep.custom-icon-jianhao_fangxing {
            color: $base-color !important;
          }
        }
      }
    }
  }

  .affirm-popup {
    ::v-deep.u-popup__content {
      border-radius: 16rpx;
    }

    ::v-deep.u-fade-enter-to {
      z-index: 10076 !important;
    }

    .affirm-popup-content {
      width: 600rpx;

      .affirm-popup-title {
        padding: 40rpx;
        text-align: center;
        font-weight: bold;
      }

      .affirm-popup-tips {
        padding: 0 60rpx;
        font-size: 28rpx;
        text-align: center;
      }

      .popup-btn-list {
        display: flex;
        margin: 50rpx;

        .btn-item {
          width: 46%;
          height: 80rpx;
          border-color: #909193;

          &::after {
            border: none;
          }
        }

        .btn-item-2 {
          background: $base-color;
          color: #fff;
          border: none;
        }
      }
    }
  }

  .add-popup {
    ::v-deep.u-popup__content {
      border-radius: 16rpx;
    }

    ::v-deep.u-fade-enter-to {
      z-index: 10076 !important;
    }

    .add-popup-content {
      width: 700rpx;

      .add-popup-title {
        padding: 40rpx;
        text-align: center;
        font-weight: bold;
        font-size: 36rpx;
      }

      .u-form {
        margin: 0 40rpx;

        .form-item {
          margin: 28rpx 0;
        }
      }

      .popup-btn-list {
        display: flex;
        margin: 50rpx;

        .btn-item {
          width: 46%;
          height: 80rpx;
          border-color: #909193;

          &::after {
            border: none;
          }
        }

        .btn-item-2 {
          background: $base-color;
          color: #fff;
          border: none;
        }
      }
    }
  }

  .specification-bottom {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 172rpx;
    background: #fff;
    border-top: 2px solid #eeeeee;
    z-index: 2;

    .bottom-list {
      display: flex;
      align-items: center;
      justify-content: flex-end;
      margin-top: 40rpx;

      .bottom-btn-item {
        margin: 0;
        margin-right: 20rpx;
        width: 400rpx;
        height: 88rpx;
        font-size: 32rpx;
        border-color: #d2d2d2;
        color: #000;

        .bottom-icon {
          margin-right: 8rpx;
        }

        &::after {
          border: none;
        }
      }
    }
  }
}
</style>
