<template>
  <view class="typeManagement-container">
    <view class="typeManagement-content">
      <view class="no-commodity-type" v-if="typeManageList.length <= 0">
        <view class="no-commodity-type-bg"></view>
        <view class="no-commodity-type-tips">暂无商品类型</view>
      </view>
      <scroll-view
        v-if="typeManageList.length > 0"
        scroll-y
        class="typeManagement-scroll"
        :show-scrollbar="false"
        @scrolltolower="handerScrolltolower"
        refresher-enabled
        :refresher-triggered="isRefreshing"
        @refresherrefresh="handleRefresh"
      >
        <view
          class="typeManagement-item"
          v-for="(item, index) of typeManageList"
          :key="index"
        >
          <view class="typeManagement-info">
            <view class="type-name">{{ item.type_name }}</view>
            <view class="type-catergory-name">
              {{ item.type_category_name }}
            </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="handerAddAndEditPopup(false, item)"
              custom-prefix="custom-icon-icon_519 custom-icon"
              size="24"
            ></u-icon>
          </view>
        </view>
        <view
          class="m-loading-box"
          v-if="typeManageList.length > 0 && !isNotypeManageData"
        >
          <block v-if="loadingDownTypeManageData">
            <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="typeManagement-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="type_name"
            class="form-item"
            required
          >
            <u--textarea
              class="u-textarea"
              v-model="form.type_name"
              count
              autoHeight
              maxlength="20"
              placeholder="请输入类型名称"
            ></u--textarea>
          </u-form-item>
          <u-form-item
            label="商品分类"
            prop="type_category_name"
            class="form-item"
            @click="hadnerShowClassifyListPopup()"
          >
            <u--input
              v-model="form.type_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="type_spec_names"
            class="form-item"
            @click="hadnerShowSpecificationPopup()"
          >
            <u--textarea
              class="u-textarea"
              v-model="form.type_spec_names"
              autoHeight
              disabled
              disabledColor="#ffffff"
              placeholder="请选择类型名称"
            ></u--textarea>
            <u-icon slot="right" name="arrow-right"></u-icon>
          </u-form-item>
        </u--form>
        <view class="popup-btn-list">
          <u-button
            class="btn-item"
            :hairline="true"
            :plain="true"
            shape="circle"
            @click="handerCloseAddAndEditPopup"
          >
            取消
          </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>
    <u-popup
      class="specification-popup"
      zIndex="10080"
      :show="showSpecificationPopup"
      mode="bottom"
      closeable
      @close="handerCloseSpecificationPopup"
    >
      <view class="specification-popup-content">
        <view class="specification-popup-title">选择规格</view>
        <view class="no-data" v-if="allSpecificationList.length <= 0">
          <view class="no-data-bg"></view>
          <view class="no-data-tips" @click="skipuSpecification">
            暂无商品规格，点击马上添加
            <u-icon
              style="display: inline-block"
              name="arrow-right"
              color="red"
            ></u-icon>
          </view>
        </view>
        <scroll-view
          v-if="allSpecificationList.length > 0"
          scroll-y
          class="specification-type-search-scroll"
          :show-scrollbar="false"
          :style="{
            maxHeight: allSpecificationList.length >= 5 ? '500px' : 'none',
            overflowY: allSpecificationList.length >= 5 ? 'auto' : 'visible',
          }"
        >
          <view
            class="specification-item"
            v-for="(item, index) in allSpecificationList"
            :key="index"
          >
            <view class="specification-name">分类名称：{{ item.name }}</view>
            <u-checkbox-group
              class="specification-checkbox-gourp"
              v-model="item.checkboxList"
              @change="checkboxChange"
            >
              <u-checkbox
                class="specification-checkbox-item"
                v-for="(group, index2) of item.list"
                :key="index2"
                :customStyle="{ marginBottom: '8px' }"
                :label="group.spec_name"
                :name="group.spec_id"
              ></u-checkbox>
            </u-checkbox-group>
          </view>
        </scroll-view>
        <view class="popup-btn-list">
          <u-button
            class="btn-item"
            :hairline="true"
            :plain="true"
            shape="circle"
            @click="handerCloseSpecificationPopup"
          >
            取消
          </u-button>
          <u-button
            class="btn-item btn-item-2"
            :hairline="true"
            :plain="true"
            shape="circle"
            @click="handerAffirmSpecification"
          >
            确认
          </u-button>
        </view>
      </view>
    </u-popup>
    <u-popup
      class="affirm-popup"
      zIndex="10077"
      :show="showDelectPopup"
      mode="center"
    >
      <view class="affirm-popup-content">
        <view class="affirm-popup-title">
          确认删除"{{ currDelectItem.type_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="handerDelectType"
          >
            确认
          </u-button>
        </view>
      </view>
    </u-popup>
    <tki-tree
      ref="tkitree"
      :range="classifyList"
      :foldAll="true"
      rangeKey="label"
      idKey="id"
      title="选择商品分类"
      @confirm="treeConfirm"
      @cancel="treeCancel"
    ></tki-tree>
    <u-toast ref="uToast"></u-toast>
  </view>
</template>

<script>
import {
  GetTypeManageList,
  UpdateType,
  DelectType,
  GetAllSpecification,
} from "@/api/warehouse/typeManage";
import { GetProductCategoryTree } from "@/api/warehouse/productList";
import tkiTree from "./components/tree/tree";
export default {
  name: "typeManagement",
  components: {
    tkiTree,
  },
  data() {
    return {
      isRefreshing: false,
      pageNum: 1,
      pageSize: 20,
      isNotypeManageData: false,
      isNoDownTypeManageData: false,
      isNotypeManageData: false,
      loadingDownTypeManageData: false,
      loding: false,
      isAdd: false,
      showSpecificationPopup: false,
      showAddAndEditPopup: false,
      showDelectPopup: false,
      classifyList: [],
      typeManageList: [],
      allSpecificationInfo: {},
      allSpecificationList: [],
      checkboxList: [],
      specsCheckboxList: [],
      currDelectItem: {},
      form: {
        type_name: "",
        type_category_id: "",
        type_category_name: "",
        type_spec_ids: "",
        type_spec_names: "",
        type_is_draft: 0,
        type_id: "",
        store_id: "",
        type_is_param: 0,
        type_brand_ids: "",
        type_buildin: 0,
        type_is_assist: 0,
        type_is_draft: 0,
        type_is_entity: 0,
        type_is_brand: 0,
        store_name: "",
        type_remark: "",
        type_assist_ids: "",
      },
      rules: {
        type_name: [
          {
            required: true,
            message: "请输入商品类型名称",
            // 可以单个或者同时写两个触发验证方式
            trigger: ["change", "blur"],
          },
        ],
      },
    };
  },
  computed: {},
  onLoad: function (options) {},
  onReady() {},
  onShow() {
    this.getProductCategoryTree();
    this.getAllSpecification();
    this.getTypeManageList();
  },
  methods: {
    async getProductCategoryTree() {
      let res = await GetProductCategoryTree();
      if (res && res.status == 200) {
        this.classifyList = res.data;
      }
    },
    async getAllSpecification() {
      let res = await GetAllSpecification();
      if (res && res.status == 200) {
        this.allSpecificationInfo = res.data;

        if (
          this.allSpecificationInfo &&
          Object.keys(this.allSpecificationInfo).length > 0
        ) {
          this.allSpecificationList = Object.entries(
            this.allSpecificationInfo
          ).map(([key, value]) => ({
            key, // include the original key if needed
            list: value,
            name: key,
            checkboxList: [],
          }));
        }

        console.log(this.allSpecificationList);
      }
    },
    findLabelInClassifyList(classifyList, targetId) {
      for (const category of classifyList) {
        if (category.id === targetId) {
          return category.label;
        }
        if (category.children && category.children.length > 0) {
          const foundLabel = this.findLabelInClassifyList(
            category.children,
            targetId
          );
          if (foundLabel) return foundLabel;
        }
      }
      return "未分类"; // 没找到返回空字符串
    },

    // 扁平化数组
    flatten(arr) {
      return arr.reduce((result, item) => {
        return result.concat(Array.isArray(item) ? this.flatten(item) : item);
      }, []);
    },
    // 编辑规格参数默认选中
    formaSpecification(specIds) {
      const list = this.flatten(Object.values(this.allSpecificationInfo));
      const selects = list.filter((item) => specIds.includes(item.spec_id));
      this.form.type_spec_names = selects
        .map((item) => {
          return item.spec_name;
        })
        .join(", ");
      this.form.type_spec_ids = selects
        .map((item) => {
          return item.spec_id;
        })
        .join(",");
    },
    handerAddAndEditPopup(isAdd, item) {
      this.isAdd = isAdd;
      if (isAdd) {
        this.form = {
          type_name: "",
          type_category_name: "",
          type_category_id: "",
          type_spec_ids: "",
          type_spec_names: "",
          type_is_draft: 0,
        };
      } else {
        this.form = JSON.parse(JSON.stringify(item));

        if (this.form.type_spec_ids.length > 0) {
          this.formaSpecification(
            this.form.type_spec_ids.split(",").map(Number)
          );
          if (this.allSpecificationList.length > 0) {
            const updatedData = this.updateCheckboxList(
              this.allSpecificationList,
              this.form.type_spec_ids.split(",").map(Number)
            );
          }
        }
      }
      this.showAddAndEditPopup = true;
    },
    updateCheckboxList(data, ids) {
      // 遍历每个主对象
      return data.map((item) => {
        // 检查该对象的list数组中是否有spec_id匹配传入的ids
        const matchedIds = item.list
          .filter((spec) => ids.includes(spec.spec_id))
          .map((spec) => spec.spec_id);

        // 如果有匹配的，就添加到checkboxList中（去重）
        if (matchedIds.length > 0) {
          return {
            ...item,
            checkboxList: [...new Set([...item.checkboxList, ...matchedIds])],
          };
        }
        return item;
      });
    },
    async getTypeManageList() {
      if (!this.loadingDownTypeManageData) {
        this.loding = true;
      }

      if (this.isRefreshing) {
        this.pageNum = 1;
        this.isNotypeManageData = false;
        this.isNoDownTypeManageData = false;
      }

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

      let res = await GetTypeManageList(params);
      if (res && res.status == 200) {
        if (this.loadingDownTypeManageData) {
          if (res.data.items.length <= 0) {
            this.loadingDownTypeManageData = false;
            this.isNoDownTypeManageData = true;
            return;
          } else {
            this.typeManageList = [...this.typeManageList, ...res.data.items];
          }
        } else {
          this.typeManageList = res.data.items;
        }

        if (this.typeManageList.length <= 0) {
          this.isNotypeManageData = true;
        }

        if (this.typeManageList.length > 0) {
          // 给 typeManageList 增加 type_category_name
          this.typeManageList.forEach((item) => {
            item.type_category_name = this.findLabelInClassifyList(
              this.classifyList,
              item.type_category_id
            );
          });
        }
      }
      this.loadingDownTypeManageData = false;
      this.isRefreshing = false;
    },
    checkboxChange(e) {
      console.log(e);
    },
    hadnerShowClassifyListPopup() {
      this.$refs.tkitree._show();
    },
    handerCloseAddAndEditPopup() {
      this.clearallSpecificationCheckBoxList();
      this.showAddAndEditPopup = false;
    },
    hadnerShowSpecificationPopup() {
      if (this.form.type_spec_ids.length > 0) {
        this.formaSpecification(this.form.type_spec_ids.split(",").map(Number));
        if (this.allSpecificationList.length > 0) {
          const updatedData = this.updateCheckboxList(
            this.allSpecificationList,
            this.form.type_spec_ids.split(",").map(Number)
          );

          this.allSpecificationList = updatedData;
        }
      }

      this.showSpecificationPopup = true;
    },
    clearallSpecificationCheckBoxList() {
      if (this.allSpecificationList.length > 0) {
        this.allSpecificationList.forEach((item) => {
          item.checkboxList = [];
        });
      }

      console.log(this.allSpecificationList);
    },
    handerCloseSpecificationPopup() {
      this.clearallSpecificationCheckBoxList();
      this.showSpecificationPopup = false;
    },
    handerShowDelectPopup(item) {
      this.currDelectItem = item;
      this.showDelectPopup = true;
    },
    async handerDelectType() {
      let params = {
        type_ids: this.currDelectItem.type_id,
      };

      let res = await DelectType(params);
      this.showDelectPopup = false;
      if (res && res.status == 200) {
        this.$refs.uToast.show({
          message: "删除成功",
          type: "succeed",
          duration: 1000,
        });

        this.typeManageList = this.typeManageList.filter(
          (item) => item.type_id !== this.currDelectItem.type_id
        );
      }
    },
    handerAffirmAddAndEdit() {
      var params = {};

      if (this.isAdd) {
        params = {
          type_name: this.form.type_name,
          type_category_id: this.form.type_category_id,
          type_is_draft: 0,
          type_spec_ids: this.form.type_spec_ids,
        };
      } else {
        params = this.form;
      }

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

          this.clearallSpecificationCheckBoxList();

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

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

        this.showAddAndEditPopup = false;
      });
    },
    handerAffirmSpecification() {
      const allCheckboxLists = [];

      // 使用 for 循环遍历每个对象
      for (let i = 0; i < this.allSpecificationList.length; i++) {
        const item = this.allSpecificationList[i];
        // 将当前对象的 checkboxList 添加到新数组中
        allCheckboxLists.push(...item.checkboxList);
      }

      this.formaSpecification(allCheckboxLists);

      this.showSpecificationPopup = false;
    },
    treeCancel() {
      this.$refs.tkitree._hide();
    },
    treeConfirm(list) {
      if (list.length > 1) {
        this.form.type_category_name = list[1].label;
        this.form.type_category_id = list[1].id;
      } else {
        this.form.type_category_name = list[0].label;
        this.form.type_category_id = list[0].id;
      }
    },
    skipuSpecification() {
      uni.navigateTo({
        url: "/pages/warehouse/manage/specification",
      });
    },
  },
};
</script>

<style lang="scss" scoped>
@import "@/styles/variables.scss";

.typeManagement-container {
  .tab-hander {
    display: flex;
    justify-content: space-around;
    margin: 40rpx 0;
    font-weight: 500;
  }

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

  .typeManagement-item {
    display: flex;
    justify-content: space-around;
    align-items: center;
    margin: 72rpx 0;

    .typeManagement-info {
      flex: 1;
      display: flex;
      justify-content: space-around;

      .type-name {
        max-width: 160rpx;
        word-break: break-all; /* 允许在任意字符间断行 */
        overflow-wrap: break-word; /* 优先在单词间断行 */
        display: -webkit-box;
        -webkit-line-clamp: 2; /* 限制最多2行 */
        -webkit-box-orient: vertical;
        overflow: hidden;
        text-overflow: ellipsis; /* 超出部分显示省略号 */
      }
    }

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

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

  ::v-deep .u-textarea {
    &.u-textarea {
      padding-left: 0 !important;
    }

    &.u-textarea--disabled {
      background: #fff;
    }
  }

  .specification-popup {
    ::v-deep.u-popup__content {
      border-top-left-radius: 16rpx;
      border-top-right-radius: 16rpx;
    }

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

    .specification-popup-content {
      .specification-popup-title {
        padding: 40rpx;
        text-align: center;
        font-weight: 500;
      }
    }

    .specification-name {
      padding: 24rpx 36rpx;
      background: #f8f8f8;
      color: #888888;
    }

    .specification-checkbox-gourp {
      display: flex;
      flex-wrap: wrap;
      padding: 24rpx;

      .specification-checkbox-item {
        margin-right: 40rpx;
      }
    }

    .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;
      }
    }
  }

  .no-data {
    .no-data-bg {
      margin: 15% 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: red;
      text-align: center;
    }
  }

  .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;
        }
      }
    }
  }

  .typeManagement-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;
        }
      }
    }
  }

  .no-commodity-type {
    .no-commodity-type-bg {
      margin: 50% auto;
      margin-bottom: 0;
      width: 300rpx;
      height: 200rpx;
      background-image: url("../../../static/warehouse/no-commodity-type.png");
      background-size: 100%;
    }

    .no-commodity-type-tips {
      margin: 80rpx auto;
      color: #cccccc;
      text-align: center;
    }
  }
}
</style>
