<template>
  <view class="select-container" v-show="show" @touchmove.stop.prevent>
    <view
      class="mask"
      :class="activeClass ? 'mask-show' : ''"
      @tap="onCancel(true)"
    ></view>
    <view class="select-box" :class="activeClass ? 'select-box-show' : ''">
      <div style="height: 900rpx">
        <div style="display: flex">
          <uni-easyinput
            type="text"
            class="searchinput"
            v-model="formData.qymc"
            placeholder="输入关联企业名称（模糊查询）"
            style="height: 70rpx"
          />
          <van-button
            class="searchbutton"
            style="height: 70rpx"
            type="primary"
            @click="getCompaynList()"
            >搜索</van-button
          >
        </div>
        <div class="chooseCompanyTags">
          <scroll-view
            class="body"
            scroll-y="true"
            style="position: absolute; z-index: 1000"
          >
            <div
              v-for="(item, index) in companyList"
              :key="index"
              class="selectlist"
            >
              <div class="title_2">
                {{ item.label }}
              </div>
              <div
                v-if="!item.isSelected"
                class="title_1"
                @click="chosseTags(item, index)"
              >
                <uni-icons type="plusempty" size="30rpx"></uni-icons>
              </div>
            </div>
          </scroll-view>
        </div>
      </div>

      <view class="btn-view">
        <button
          class="btn"
          @click="openTagsDialog()"
          style="
            border-top-left-radius: 5rem;
            border-bottom-left-radius: 5rem;
            background: white;
            color: #1d18bc;
            border: 1px solid;
          "
        >
          已选择（{{ isSelectedList.length }}）<van-icon name="arrow-down" />
        </button>
        <button
          style="
            border-radius: 0;
            border: 1px solid #1d18bc;
            border-top-right-radius: 5rem;
            border-bottom-right-radius: 5rem;
          "
          class="btn"
          @click="updown()"
        >
          确认提交
        </button>
      </view>
    </view>
    <is-selected-tags
      ref="isSelectedTags"
      :isSelectedList="isSelectedList"
      @clearAll="clearAll"
      @updown="updown"
      @spiliceIsSelectedList="spiliceIsSelectedList"
    />
  </view>
</template>
<!-- 多选组件 -->
<script>
import isSelectedTags from "./isSelectedTags.vue";
export default {
  data() {
    return {
      isSelectedList: [],
      companyList: [],
      isSelectList: [],
      formData: {},
      show: false, //是否显示
      activeClass: false, //激活样式状态
      selectedArr: [], //选择对照列表
      selectedArrOld: [], //选择对照列表上一次的数据
    };
  },
  components: {
    isSelectedTags,
  },
  onShow() {
    this.show = this.value;
  },
  methods: {
    async updown() {
      console.log(this.isSelectedList);
      this.$emit("confirm", this.isSelectedList);
      this.show = false;
    },
    clearAll() {
      this.isSelectedList = [];
      this.companyList.forEach((e) => {
        e.isSelected = false;
        this.$forceUpdate();
      });
    },
    spiliceIsSelectedList(item, index) {
      this.isSelectedList.splice(index, 1);
      let changeIndex = this.companyList.findIndex(
        (e) => e.tagCategoryId == item.tagCategoryId
      );
      this.companyList[changeIndex].isSelected = false;
      this.$forceUpdate();
    },
    chosseTags(item, index) {
      let filterIndex = this.isSelectedList.findIndex(
        (e) => e.value == item.value
      );
      if (filterIndex != -1) {
        this.$showToast("该标签与已选择标签重复");
        return;
      }
      if (item.isEffective == 1) {
        this.openChooseTimeDialog(item, index);
      } else {
        this.isSelectedList.push(this.companyList[index]);
        this.companyList[index].isSelected = true;
        this.companyList = [...this.companyList];
      }
    },
    openTagsDialog() {
      this.$refs.isSelectedTags.onOpen([]);
    },
    getAllList(data) {
      this.companyList = data;
    },
    getCompaynList() {
      console.log(this.companyList);
      console.log(this.selectedArr);
      this.$emit("getCompanyAll", this.formData.qymc);
    },
    // 设置默认选中通用办法
    setItemActiveState() {
      if (this.companyList.length && this.defaultSelected.length) {
        this.companyList.forEach((item, i) => {
          for (let n = 0; n < this.defaultSelected.length; n++) {
            if (
              !item.disabled &&
              item[this.valueName] === this.defaultSelected[n]
            ) {
              this.selectedArr.splice(i, 1, true);
              break;
            }
          }
        });
      }
    },
    /**
     * 选择事件
     * @index {Number} 点击下标
     */
    onSelected(index) {
      if (this.companyList[index].disabled) return;
      console.log(this.companyList[index]);
      if (!this.companyList[index].isSelect) {
        this.isSelectList.push(this.companyList[index].value);
        this.companyList[index].isSelect = true;
      } else {
        let deleteIndex = this.isSelectList.findIndex(
          (e) => e.value == this.companyList[index].value
        );
        this.isSelectList.splice(deleteIndex, 1);
        this.companyList[index].isSelect = false;
      }
      this.$forceUpdate();
      this.companyList = [...this.companyList];
      //   let index2Active = this.selectedArr[index];
      //   this.selectedArr.splice(index, 1, !index2Active);
    },
    // 取消事件
    onCancel(isMask) {
      if (!isMask || this.maskCloseAble) {
        this.show = false;
        this.selectedArr = JSON.parse(JSON.stringify(this.selectedArrOld));
      } else {
        return;
      }
      this.$emit("cancel");
    },
    // 返回去除了disabled状态后的对照列表
    returnWipeDisabledList() {
      let arr = [];
      this.selectedArr.forEach((el, index) => {
        if (!this.companyList[index].disabled) arr.push(el);
      });
      return arr;
    },
    // 全选/非全选事件
    onAllToggle() {
      let wipeDisabledList = this.returnWipeDisabledList();
      // 如果去除了disabled的对照列表有false的数据，代表未全选
      if (wipeDisabledList.includes(false)) {
        this.selectedArr.forEach((el, index) => {
          if (!this.companyList[index].disabled)
            this.selectedArr.splice(index, 1, true);
        });
      } else {
        this.selectedArr.forEach((el, index) => {
          if (!this.companyList[index].disabled)
            el = this.selectedArr.splice(index, 1, false);
        });
      }
    },
    // 确定事件
    onConfirm() {
      this.show = false;
      let selectedData = [];
      this.companyList.forEach((e, index) => {
        if (e.isSelect) {
          selectedData.push(this.companyList[index]);
        }
      });
      if (this.mode === "multiple") {
        this.$emit("confirm", selectedData);
      } else {
        let backData = selectedData[0] || {};
        this.$emit("confirm", backData);
      }
    },
  },
  computed: {
    // 返回是否全选
    isAll() {
      let wipeDisabledList = this.returnWipeDisabledList();
      if (!wipeDisabledList.length) return false;
      return !wipeDisabledList.includes(false);
    },
  },
  props: {
    // 双向绑定
    value: {
      type: Boolean,
      default: false,
    },
    // 取消按钮文字
    cancelText: {
      type: String,
      default: "取消",
    },
    // 确认按钮文字
    confirmText: {
      type: String,
      default: "确认",
    },
    // label对应的key名称
    labelName: {
      type: String,
      default: "label",
    },
    // value对应的key名称
    valueName: {
      type: String,
      default: "value",
    },
    // 是否允许点击遮罩层关闭
    maskCloseAble: {
      type: Boolean,
      default: true,
    },
    // 是否显示全选
    allShow: {
      type: Boolean,
      default: true,
    },
    // 模式
    mode: {
      type: String,
      default: "multiple",
    },
    // 默认选中值
    defaultSelected: {
      type: Array,
      default: function () {
        return [];
      },
    },
    // 数据源
    // data: {
    //   type: Array,
    //   required: true,
    //   default: () => {
    //     return [];
    //   },
    // },
  },
  watch: {
    async value(newVal) {
      this.show = newVal;
      await this.$nextTick();
      this.activeClass = newVal;
      if (newVal) {
        this.selectedArrOld = JSON.parse(JSON.stringify(this.selectedArr));
      }
    },
    show(newVal) {
      this.$emit("input", newVal);
      this.$emit("change", newVal);
    },

    defaultSelected: {
      handler() {
        this.setItemActiveState();
      },
      deep: true,
      immediate: true,
    },
  },
};
</script>
<style lang="scss">
.searchbutton {
  button {
    height: 69rpx;
    line-height: 69rpx;
  }
}
.searchinput {
  .uni-easyinput__content-input {
    height: 70rpx;
  }
}

.btn-view {
  width: 100%;
  height: 100rpx;
  padding: 20rpx 10%;
  background-color: #ffffff;
  position: fixed;
  bottom: 0;
  left: 0;
  z-index: 1000;
  button {
    &::after {
      border: none;
    }
  }
}
</style>
<style lang="scss" scoped>
.selectlist {
  border-bottom: 2rpx solid #cccccc;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.chooseCompanyTags {
  .title_1 {
    font-size: 28rpx;
    font-weight: 500;
    color: #333333;
    text-align: right;
    height: 64rpx;
    line-height: 64rpx;
  }
  .title_2 {
    font-size: 26rpx;
    font-weight: 500;
    color: #777777;
    height: 64rpx;
    line-height: 64rpx;
    text-align: left;
  }
  .title_3 {
    margin-bottom: 12rpx;
    font-size: 26rpx;
    font-weight: 500;
    color: #777777;
  }
  .cell_1 {
    float: left;
    width: 10%;
  }
  .checkbox {
    border: 1px solid #cccccc;
    border-radius: 4rpx  4rpx  4rpx  4rpx;
    height: 30rpx;
    width: 30rpx;
  }
  .cell_2 {
    float: left;
    width: 90%;

    img {
      height: 60rpx;
      width: 60rpx;
      float: right;
      margin: 96rpx 0rpx 94rpx 0;
    }
  }

  .btn {
    width: 40%;
    height: 90rpx;
    background: #1d18bc;
    line-height: 90rpx;
    color: white;
    float: left;
  }
  .jichuback {
    width: calc(100% - 64rpx);
    margin: 32rpx;
    background: white;
    border-bottom: 2rpx solid #cccccc;
  }
  .tags_type {
    width: calc(100% - 64rpx);
    margin: 16rpx;
  }
}
.btn-view {
  width: 100%;
  height: 100rpx;
  padding: 20rpx 10%;
  background-color: #ffffff;
  position: fixed;
  bottom: 0;
  left: 0;
  z-index: 1000;
}
.btn {
  width: 40%;
  height: 90rpx;
  background: #1d18bc;
  line-height: 90rpx;
  color: white;
  float: left;
}
.select-container {
  width: 100vw;
  height: 100vh;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 999;
  $paddingLR: 18rpx;
  .mask {
    width: 100%;
    height: 100%;
    background-color: $uni-bg-color-mask;
    opacity: 0;
    transition: opacity 0.3s;
    &.mask-show {
      opacity: 1;
    }
  }
  // 选择器内容区域
  .select-box {
    width: 100%;
    position: absolute;
    bottom: 0;
    left: 0;
    transform: translate3d(0px, 100%, 0px);
    background-color: $uni-bg-color;
    transition: all 0.3s;
    &.select-box-show {
      transform: translateZ(0);
    }
    .header {
      display: flex;
      box-sizing: border-box;
      width: 100%;
      justify-content: space-between;
      border-bottom: 1px solid $uni-border-color;
      line-height: 76rpx;
      font-size: 30rpx;
      padding: 0 $paddingLR;
      .cancel {
        color: $uni-text-color-grey;
      }
      .all {
        .all-active {
          &::after {
            display: inline-block;
            content: "✔";
            padding-left: 8rpx;
          }
        }
      }
      .confirm {
        color: $uni-color-primary;
      }
    }
    .body-warp {
      width: 100%;
      height: 30vh;
      box-sizing: border-box;
      padding: 20rpx $paddingLR;
    }
    .body {
      width: 96%;
      height: 70%;
      overflow-y: auto;
      padding: 2%;
      .empty-tips {
        margin-top: 25%;
        text-align: center;
        font-size: 26rpx;
        color: $uni-color-error;
      }
    }
  }
}
</style>