<template>
  <view class="editClassify-container">
    <navBar
      class="nav-bar"
      :statusBar="true"
      :border="false"
      :fixed="true"
      :height="'44px'"
      rightWidth="0"
      :leftWidth="30"
      title="编辑分类"
      backgroundColor="#fff"
    >
      <block slot="left">
        <u-icon
          name="arrow-left"
          color="#000"
          size="20"
          @click="pageBack()"
        ></u-icon>
      </block>
    </navBar>
    <u-alert
      title="注意，确认商品类型后不可修改名称，商品类型，虚拟商品!"
      :center="true"
      type="error"
    ></u-alert>
    <view class="edit-item">
      <view class="item-name">一级分类</view>
      <u--form labelPosition="left" :model="form" ref="uForm" label-width="100">
        <u-form-item
          label="分类名称"
          prop="category_name"
          class="form-item"
          required
        >
          <u--textarea
            class="u-textarea"
            v-model="form.category_name"
            count
            autoHeight
            maxlength="8"
            placeholder="请输入分类名称"
            :disabled="form.type_id != 0"
          ></u--textarea>
        </u-form-item>
        <u-form-item
          label="商品类型"
          prop="type_name"
          class="form-item"
          @click="hadnerShowCommodityTypePopup(false)"
        >
          <u--input
            v-model="form.type_name"
            disabled
            disabledColor="#ffffff"
            placeholder="请选择商品类型"
            border="none"
            @click="hideKeyboard()"
          ></u--input>
          <u-icon
            slot="right"
            name="arrow-right"
            v-if="form.type_id == 0"
          ></u-icon>
        </u-form-item>
        <u-form-item label="分类排序" prop="category_order" class="form-item">
          <u--input
            v-model="form.category_order"
            type="number"
            placeholder="请输入商品排序"
            border="none"
          ></u--input>
        </u-form-item>
        <u-form-item
          label="允许虚拟商品"
          prop="category_order"
          class="form-item form-item-switch"
        >
          <u-switch
            v-model="form.category_virtual_enable"
            :disabled="form.type_id != 0"
            :activeValue="1"
            :inactiveValue="0"
            activeColor="#5ac725"
            inactiveColor="#fe411b"
          ></u-switch>
        </u-form-item>
      </u--form>
    </view>
    <view class="edit-item edit-item-2">
      <view class="second-level-item">
        <view class="item-name">二级分类</view>
        <u-icon
          class="u-icon-jiahao"
          @click="handerShowEeditPopup(true)"
          custom-prefix="custom-icon-jiahao custom-icon"
          size="20"
        ></u-icon>
      </view>
      <view class="second-level-item-input" v-for="(item, index) of form.sub">
        <u--input
          placeholder="请输入"
          border="surround"
          v-model="item.category_name"
          @change="handerLeveInputChange"
          maxlength="8"
          readonly
          @focus="handerInputFocus(index)"
          @blur="handerInputBlur(index)"
        >
          <template slot="suffix">
            <view class="statistics" v-if="isIntpufocus && index == focusIndex">
              {{ item.category_name.length }} / 8
            </view>

            <view v-else class="icon-list">
              <u-icon
                class="u-icon-jianhao"
                custom-prefix="custom-icon-jianhao_fangxing custom-icon"
                size="20"
                @click="handerShowDelectPopup(item)"
              ></u-icon>
              <u-icon
                class="u-icon-bianji"
                @click="handerShowEeditPopup(false, item)"
                custom-prefix="custom-icon-icon_519 custom-icon"
                size="24"
              ></u-icon>
            </view>
          </template>
        </u--input>
      </view>
    </view>
    <view class="bottom">
      <u-button
        class="save-btn-item"
        :hairline="true"
        :plain="true"
        shape="circle"
        @click="handerSave"
      >
        保存
      </u-button>
    </view>
    <u-popup
      class="affirm-popup"
      zIndex="10077"
      :show="showDelectPopup"
      mode="center"
    >
      <view class="affirm-popup-content">
        <view class="affirm-popup-title">
          确认删除"{{ delectClassifyItem.category_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-popup
      class="add-popup"
      zIndex="10077"
      :show="showEditPopup"
      mode="center"
    >
      <view class="add-popup-content">
        <view class="add-popup-title">
          {{
            isAddClassify
              ? "添加二级分类"
              : `编辑二级"${this.form2.category_name}"分类`
          }}
        </view>
        <view class="tips">
          注意，确认商品类型后不可修改名称，商品类型，虚拟商品!
        </view>
        <u--form
          labelPosition="left"
          :model="form2"
          ref="uForm2"
          label-width="100"
          :rules="rules2"
        >
          <u-form-item
            label="分类名称"
            prop="category_name"
            class="form-item"
            required
          >
            <u--textarea
              class="u-textarea"
              v-model="form2.category_name"
              :disabled="form2.type_id != 0"
              count
              autoHeight
              maxlength="8"
              placeholder="请输入二级分类名称"
            ></u--textarea>
          </u-form-item>
          <u-form-item
            label="商品类型"
            prop="type_name"
            class="form-item"
            @click="hadnerShowCommodityTypePopup(true)"
          >
            <u--input
              v-model="form2.type_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="category_order" class="form-item">
            <u--input
              v-model="form2.category_order"
              type="number"
              placeholder="请输入商品排序"
              border="none"
            ></u--input>
          </u-form-item>
          <u-form-item
            label="允许虚拟商品"
            prop="category_order"
            class="form-item form-item-switch"
          >
            <u-switch
              v-model="form2.category_virtual_enable"
              :activeValue="1"
              :inactiveValue="0"
              activeColor="#5ac725"
              inactiveColor="#fe411b"
              :disabled="form2.type_id != 0"
            ></u-switch>
          </u-form-item>
        </u--form>
        <view class="popup-btn-list">
          <u-button
            class="btn-item"
            :hairline="true"
            :plain="true"
            shape="circle"
            @click="showEditPopup = false"
          >
            取消
          </u-button>
          <u-button
            class="btn-item btn-item-2"
            :hairline="true"
            :plain="true"
            shape="circle"
            @click="handerAffirmEditClassify"
          >
            确认
          </u-button>
        </view>
      </view>
    </u-popup>
    <u-popup
      class="commodity-type-popup"
      :show="showCommodityTypePopup"
      mode="bottom"
      zIndex="10080"
      closeable
      @close="handerCloseTypePopup"
    >
      <view class="commodity-type-popup-content">
        <view class="commodity-type-popup-title">选择商品类型</view>
        <view class="no-commodity-type" v-if="typeManageList.length <= 0">
          <view class="no-commodity-type-bg"></view>
          <view class="no-commodity-type-tips" @click="skipuBrandList">
            暂无商品类型，点击马上添加
            <u-icon
              style="display: inline-block"
              name="arrow-right"
              color="red"
            ></u-icon>
          </view>
        </view>
        <scroll-view
          v-if="typeManageList.length > 0"
          scroll-y
          class="commodity-type-search-scroll"
          :show-scrollbar="false"
          @scrolltolower="handerScrolltolower"
          refresher-enabled
          :refresher-triggered="isRefreshing"
          @refresherrefresh="handleRefresh"
          :style="{
            maxHeight: typeManageList.length >= 2 ? '500px' : 'none',
            overflowY: typeManageList.length >= 2 ? 'auto' : 'visible',
          }"
        >
          <u-radio-group
            class="commodity-type-radio-group"
            v-model="radioValue"
            placement="column"
            @change="handerRadioChange"
          >
            <u-radio
              class="commodity-type-radio"
              v-for="(item, index) in typeManageList"
              :key="index"
              :label="item.type_name"
              :name="item.type_id"
              @change="radioChange"
            ></u-radio>
          </u-radio-group>
          <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 class="popup-btn-list">
          <u-button
            class="btn-item"
            :hairline="true"
            :plain="true"
            shape="circle"
            @click="handerCancelCommodityTpye"
          >
            取消
          </u-button>
          <u-button
            class="btn-item btn-item-2"
            :hairline="true"
            :plain="true"
            shape="circle"
            @click="handerAffirmCommodityType"
          >
            确认
          </u-button>
        </view>
      </view>
    </u-popup>
    <u-toast ref="uToast"></u-toast>
  </view>
</template>

<script>
import { GetTypeManageList } from "@/api/warehouse/typeManage";
import {
  GetCommodityClassify,
  UpdateCommodityClassify,
  DelectCommodityClassify,
} from "@/api/warehouse/classifyList";
import navBar from "@/components/uni-nav-bar/uni-nav-bar";
export default {
  name: "editClassify",
  props: {
    classifyItem: {
      type: Object,
      default: {
        category_name: "",
      },
    },
    currSecondLevelItem: {
      type: Object,
      default: {
        category_name: "",
      },
    },
    isEdit: {
      type: Boolean,
      default: false,
    },
    isEditStairType: {
      type: Boolean,
      default: false,
    },
    isEditSecondLevelType: {
      type: Boolean,
      default: false,
    },
    isEditSecondLevelName: {
      type: Boolean,
      default: false,
    },
    isAddSecondLevelClassify: {
      type: Boolean,
      default: false,
    },
  },
  components: {
    navBar,
  },
  data() {
    return {
      pageNum: 1,
      pageSize: 20,
      typeManageList: [],
      form: {
        type_category_id: 0,
        category_name: "",
        category_virtual_enable: 0,
        type_name: "",
      },
      rules: {
        contact_name: [
          {
            required: true,
            message: "请输入联系人",
            // 可以单个或者同时写两个触发验证方式
            trigger: ["change", "blur"],
          },
        ],
      },
      secondLevel: [],
      isIntpufocus: false,
      focusIndex: 0,
      delectClassifyItem: {
        category_name: "",
      },
      showDelectPopup: false,
      showEditPopup: false,
      form2: {
        category_name: "",
        category_virtual_enable: 0,
        type_name: "",
        type_id: 0,
      },
      rules2: {
        category_name: [
          {
            required: true,
            message: "请输入二级分类名称",
            // 可以单个或者同时写两个触发验证方式
            trigger: ["change", "blur"],
          },
        ],
      },
      radioValue: "",
      isRefreshing: false,
      isNotypeManageData: false,
      isNoDownTypeManageData: false,
      loadingDownTypeManageData: false,
      showCommodityTypePopup: false,
      isSubsetSelect: false,
      classifyList: [],
      isAddClassify: false,
      time: null,
    };
  },
  computed: {},
  onLoad: function (options) {},
  onReady() {},
  onShow() {
    // this.classifyItem = form;
  },

  mounted() {
    this.getTypeManageList();

    if (this.isEditStairType) {
      this.hadnerShowCommodityTypePopup(false);
    }

    if (this.isEditSecondLevelName) {
      this.showEditPopup = true;
      this.form2 = this.currSecondLevelItem;
    }

    if (this.isAddSecondLevelClassify) {
      this.isAddClassify = true;
      this.showEditPopup = true;
    }

    if (this.isEdit) {
      this.form = JSON.parse(JSON.stringify(this.classifyItem));
    }
    console.log(this.form);
    console.log(this.classifyItem);
    this.$refs["uForm"].setRules(this.rules);
  },
  methods: {
    pageBack() {
      this.$emit("pageBack");
    },
    handerPageBack() {
      this.$emit("pageBack");
    },
    handerRadioChange() {},
    radioChange() {},
    handerInputFocus(index) {
      this.isIntpufocus = true;
      this.focusIndex = index;
    },
    handerInputBlur(e) {
      this.isIntpufocus = false;
    },
    handerLeveInputChange() {},
    async getTypeManageList() {
      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) {
          const matchedItem = this.typeManageList.find(
            (item) => item.type_category_id === this.classifyItem.category_id
          );
          if (matchedItem) {
            this.form.type_name = matchedItem.type_name;
          }
        }

        if (this.typeManageList.length <= 0) {
          this.isNotypeManageData = true;
        }
      }
      this.loadingDownTypeManageData = false;
      this.isRefreshing = false;
    },

    handerScrolltolower() {
      clearTimeout(this.time);
      if (this.isNoDownTypeManageData) return;
      this.loadingDownTypeManageData = true;
      this.pageNum = this.pageNum + 1;
      this.time = setTimeout(() => {
        this.getTypeManageList();
      }, 500);
    },
    handleRefresh() {
      this.isRefreshing = true;
      this.pageNum = 1;
      this.getTypeManageList();
    },
    handerSave() {
      console.log(this.form);

      this.$refs.uForm.validate().then(async (valid) => {
        let params = {
          category_parent_id: this.form.category_parent_id,
          type_id: this.form.type_id,
          type_id_disable: false,
          category_name: this.form.category_name,
          category_image: this.form.category_image,
          category_virtual_enable: this.form.category_virtual_enable,
          category_commission_rate: this.form.category_commission_rate,
          category_order: this.form2.category_order,
          page_id: this.form.page_id,
          category_id: this.form.category_id,
        };

        let res = await UpdateCommodityClassify(params);
        if (res && res.status == 200) {
          this.$refs.uToast.show({
            message: "修改成功",
            type: "succeed",
            duration: 1000,
          });
        }
      });
    },
    handerAffirmEditClassify() {
      console.log(this.radioValue);

      this.$refs.uForm2.validate().then(async (valid) => {
        let params = {
          category_image: "",
          category_virtual_enable: this.form2.category_virtual_enable,
          category_id: this.form2.category_id,
          type_id: this.radioValue,
          category_parent_id: this.form.category_id,
          category_name: this.form2.category_name,
          category_order: this.form.category_order,
        };

        console.log(this.form2);

        let res = await UpdateCommodityClassify(params);
        if (res && res.status == 200) {
          this.$refs.uToast.show({
            message: this.isAddClassify ? "添加成功" : "修改成功",
            type: "succeed",
            duration: 1000,
          });
          await this.getCommodityClassify();
        }
        this.showEditPopup = false;
        this.radioValue = "";
      });
    },
    async getCommodityClassify() {
      let res = await GetCommodityClassify();
      if (res && res.status == 200) {
        let list = res.data;

        if (list.length > 0) {
          const newList = list.find(
            (item) => item.category_id === this.classifyItem.category_id
          );

          this.form = newList;

          console.log("更新后:", this.form);

          if (this.typeManageList.length > 0) {
            const matchedItem = this.typeManageList.find(
              (item) => item.type_category_id === this.classifyItem.category_id
            );
            if (matchedItem) {
              this.form.type_name = matchedItem.type_name;
            }
          }
        }

        this.$emit("addClassify", res.data);
      }
    },
    handerCloseTypePopup() {
      this.showCommodityTypePopup = false;
      this.radioValue = "";
    },
    handerShowDelectPopup(item) {
      this.delectClassifyItem = item;
      this.showDelectPopup = true;
    },
    handerShowEeditPopup(isAddClassify, item) {
      this.isAddClassify = isAddClassify;

      if (!isAddClassify) {
        this.form2 = item;
      } else {
        this.form2 = {
          type_category_id: 0,
          category_name: "",
          category_virtual_enable: 0,
          type_name: "",
          type_id: 0,
        };
      }

      this.showEditPopup = true;

      setTimeout(() => {
        this.$refs["uForm2"].setRules(this.rules2);
      }, 0);
    },
    async handerDelectClassify() {
      const categoryId = this.delectClassifyItem.category_id;

      let params = {
        category_id: categoryId,
      };

      let res = await DelectCommodityClassify(params);
      if (res && res.status == 200) {
        this.form.sub = this.form.sub.filter(
          (item) => item.category_id !== categoryId
        );

        this.$refs.uToast.show({
          message: "删除成功",
          type: "succeed",
          duration: 1000,
        });

        this.$emit("updateClassify", this.form);
      }
      this.showDelectPopup = false;
    },
    hadnerShowCommodityTypePopup(isSubsetSelect) {
      this.isSubsetSelect = isSubsetSelect;

      if ((!isSubsetSelect && this.form.type_id == 0) || !this.form.type_id) {
        this.showCommodityTypePopup = true;
      }

      if ((isSubsetSelect && this.form2.type_id == 0) || !this.form2.type_id) {
        this.showCommodityTypePopup = true;
      }
    },
    handerCancelCommodityTpye() {
      this.showCommodityTypePopup = false;
      this.radioValue = "";
    },
    handerAffirmCommodityType() {
      console.log(this.radioValue);

      const matchedItem = this.typeManageList.find(
        (item) => item.type_id === this.radioValue
      );

      if (this.isSubsetSelect) {
        this.form2.type_name = matchedItem.type_name;
      } else {
        this.form.type_name = matchedItem.type_name;
      }

      this.showCommodityTypePopup = false;
    },
    skipuBrandList() {
      uni.navigateTo({
        url: "/pages/warehouse/manage/typeManagement",
      });
    },
  },
};
</script>

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

.editClassify-container {
  width: 100vw;
  height: calc(100vh - 166rpx);
  background: #f5f6fa;
  overflow-y: auto;

  .nav-bar {
    ::v-deep.uni-navbar__header-container-inner {
      font-size: 16px;
      font-weight: bold;

      .uni-nav-bar-text {
        font-size: 16px;
      }
    }
  }

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

  .edit-item {
    margin: 24rpx;
    padding: 24rpx 32rpx;
    border-radius: 16rpx;
    background: #fff;
    box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.1);

    .item-name {
      margin: 20rpx 0;
      font-size: 17px;
      font-weight: 500;
    }

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

    .form-item-switch {
      ::v-deep.u-form-item__body__right__content__slot {
        align-items: end;
        flex-direction: column;
      }
    }

    .second-level-item {
      position: sticky;
      top: 0;
      left: 0;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .u-icon {
        margin-right: 40rpx;

        ::v-deep.custom-icon-jiahao {
          color: $base-color !important;
        }
      }
    }
  }

  .second-level-item-input {
    margin: 40rpx 0;
    font-weight: 500;

    .statistics {
      font-size: 12px;
      color: #909193;
      margin-right: 20rpx;
    }
  }

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

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

      .commodity-type-search-scroll {
      }

      .commodity-type-radio-group {
        margin: 40rpx;

        .commodity-type-radio {
          margin-bottom: 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;
      }
    }
  }

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

      .tips {
        text-align: center;
        color: red;
      }

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

  .no-commodity-type {
    .no-commodity-type-bg {
      margin: 6% 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: 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;
        }
      }
    }
  }

  .bottom {
    position: fixed;
    width: 92%;
    bottom: 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    padding-bottom: 40rpx;
    background: #fff;
    height: 120rpx;

    .save-btn-item {
      margin: 0;
      margin-right: 20rpx;
      width: 100%;
      height: 38px;
      font-size: 28rpx;
      border: none;
      color: #fff;
      background: $base-color;

      &::after {
        border: none;
      }
    }
  }

  .icon-list {
    display: flex;

    .u-icon-jianhao {
      margin-right: 60rpx;

      ::v-deep.custom-icon-jianhao_fangxing {
        color: $base-color !important;
      }
    }
  }
}
</style>
