<template>
  <div style="width: 100%">
    <van-popup
      v-model="popUpVisible"
      round
      position="bottom"
      :style="popStyle"
      @close="onClosePopup"
      overlay-class="overlay"
    >
      <LimitedTimeFreeTag class="free-tag" v-if="needFreeTag" />
      <div class="search-list-content-wrap">
        <div class="operation-wrap">
          <div class="search-wrap">
            <WlSearch
              closable
              closeIconSize="12px"
              v-model="searchValue"
              placeholder="输入企业名称"
              @onChange="onChange"
              @onClear="onClear"
            />
          </div>
          <div class="cancel-btn" @click="onClosePopup">取消</div>
        </div>
        <div
          class="recommend-list"
          v-if="!searchValue && recommendList.length !== 0"
        >
          <span class="title">推荐：</span>
          <span
            @click="onSelectRecommend(item, index)"
            class="item"
            v-for="(item, index) in recommendList"
            :key="index"
          >
            {{ item }}
          </span>
        </div>
        <div class="search-result" v-else>
          <template v-if="searchResult.length !== 0 && !searchFlag">
            <div
              class="search-result-item"
              v-for="item in searchResult"
              :key="item.value"
              @click="onChoose(item)"
            >
              <div class="content">
                <div class="company-name">
                  <span v-html="item.highlightLabel" class="name"></span>
                  <span v-if="item.isExist" class="is_exist">已存在</span>
                  <span
                    v-if="
                      item.match_type &&
                      !hidden_mathch_type.includes(item.match_type)
                    "
                    class="matching-reason"
                    >{{ item.match_type }}</span
                  >
                </div>
                <p v-if="item.oper_name" class="oper-name-wrap">
                  <span>法人：</span>
                  <span v-if="item.match_type !== '法定代表人匹配'">{{
                    item.oper_name
                  }}</span>
                  <span v-else v-html="item.highlightOper">{{
                    item.oper_name
                  }}</span>
                </p>
              </div>
            </div>
          </template>
          <div v-else-if="searchFlag" class="loading">
            <div class="loading-pic">
              <WlPic :src="require('@packages/assets/images/loading.png')" />
            </div>
          </div>
          <!-- <div
            v-else-if="searchValue && searchResult.length === 0 && !searchFlag"
            class="no-result"
          >
            <div class="pic">
              <WlPic
                :src="
                  require('@packages/assets/images/search-company-none.png')
                "
              />
            </div>
          </div> -->
        </div>
      </div>
    </van-popup>
    <Tip
      v-model="matching"
      :company_name="searchValue"
      @close_tip_visible="close_tip_visible"
    />
  </div>
</template>

<script>
import { onDebounce } from "@packages/utils/index.js";
import LimitedTimeFreeTag from "./components/LimitedTimeFreeTag/index.vue";
import Tip from "./components/Tip/index.vue";
import WlPic from "@packages/components/Common/WlPic/src/index.vue";
import WlSearch from "@packages/components/Common/WlSearch/src/index.vue";
import Api from "./http/api";
export default {
  name: "EnSearchEnterprise",
  components: { WlPic, LimitedTimeFreeTag, WlSearch, Tip },
  props: {
    defaultSearchVal: {
      type: String,
      default: "",
    },
    value: {
      type: Boolean,
      default: false,
    },
    recommendList: {
      type: Array,
      default: () => {
        return [];
      },
    },
    needFreeTag: {
      type: Boolean,
      default: true,
    },
    hidden_mathch_type: {
      type: Array,
      default: () => ["公司名称匹配", "法定代表人匹配"],
    },
    node_env: {
      type: String,
      default: "uat",
    },
  },
  data() {
    return {
      searchResult: [],
      popUpVisible: false,
      searchValue: "",
      searchFlag: false,
      matching: false,
    };
  },
  watch: {
    value: {
      handler(val) {
        this.popUpVisible = val;
        val && this.checkTipCondition();
        if (!val) {
          this.matching = val;
        }
      },
      immediate: true,
    },
    defaultSearchVal: {
      handler(val) {
        this.searchValue = val;
        // this.onDebounceChange(val);
      },
      immediate: true,
    },
    searchResult: {
      handler() {
        this.checkTipCondition();
      },
      deep: true,
      immediate: true,
    },
    searchValue: {
      handler(val) {
        if(!val){
          this.searchResult = []
        }
      },
      deep: true,
      immediate: true,
    },
  },
  computed: {
    popStyle() {
      return {
        height: "75%",
        "border-top-left-radius": this.needFreeTag ? 0 : "",
        overflow: "initial",
        zIndex: "2500",
      };
    },
  },
  methods: {
    //关闭提示弹窗
    close_tip_visible(flag) {
      this.matching = flag;
      this.popUpVisible = flag;
      this.$emit("sendSearchValue", this.searchValue);
    },
    //判断是否需要开启tip弹窗
    checkTipCondition() {
      if (this.searchResult.length > 0) {
        this.matching = !this.searchResult.some(
          (i) => i.label === this.searchValue
        );
      } else {
        if (this.searchValue !== "") {
          this.matching = true;
          return;
        }
        this.matching = false;
      }
    },
    onClosePopup() {
      this.$emit("input", false);
      this.$nextTick(function () {
        this.popUpVisible = false;
      });
    },
    onClearSearchContent(content = "") {
      this.$nextTick(function () {
        this.searchValue = content;
        this.searchFlag = false;
      });
    },
    onClear() {
      this.$emit("onChange", "");
      this.searchValue = "";
      this.searchFlag = false;
      this.onClearList();
    },
    onChange(val) {
      if (val.trim()) {
        this.searchFlag = true;
      }
      if (val && !val.trim()) {
        this.searchValue = "";
      }
      !!val && this.onDebounceChange(val.trim());
    },
    onDebounceChange: onDebounce(
      function (val) {
        this.getData();
        this.$emit("onChange", val);
      },
      800,
      false
    ),
    onChoose(item) {
      this.$emit("onChoose", item);
      this.matching = false;
      this.popUpVisible = false;
    },
    onSelectRecommend(item) {
      this.searchValue = item;
      this.$emit("onChange", item);
      this.searchFlag = true;
      this.getData();
    },
    onClearList() {
      this.searchResult = [];
    },
    async getData() {
      const res = await Api.getCompanySearchList(
        {
          keyword: this.searchValue,
          ...this.$attrs,
        },
        this.node_env
      );
      const { data = [] } = res;
      const list = data.map((ele) => {
        const {
          name,
          company_id: value,
          start_date,
          status,
          credit_code: creditCode,
          flag,
          oper_name,
          match_type,
          platform_id,
          company_id,
        } = ele;
        return {
          ...ele,
          label: name,
          value,
          isExist: flag === 1,
          startDate: start_date,
          status,
          creditCode,
          oper_name,
          match_type,
          platform_id,
          company_id,
          highlightLabel: name.replace(
            this.searchValue,
            `<span class="search-text">${this.searchValue}</span>`
          ),
          highlightOper: oper_name?.replace(
            this.searchValue,
            `<span class="search-text">${this.searchValue}</span>`
          ),
        };
      });
      this.searchResult = list;
      this.searchFlag = false;
    },
  },
};
</script>

<style lang="scss">
.overlay {
  z-index: 2000 !important;
}
.search-list-content-wrap {
  height: 100%;
  box-sizing: border-box;
  overflow-y: auto;
  padding: j(16) 0 j(15) j(15);
  @extend %flex-direction-column;
  .operation-wrap {
    flex-shrink: 0;
    padding-bottom: j(10);
    @extend %flex-middle;
    .search-wrap {
      flex: 1;
    }
    .cancel-btn {
      padding: 0 j(15);
      color: #0e0e0e;
      font-size: j(14);
      cursor: pointer;
    }
  }
  .search-result {
    padding-right: j(16);
    box-sizing: border-box;
    flex: 1;
    height: 100%;
    overflow: auto;
    &-item {
      // height: j(44);
      // line-height: j(44);
      // @include textEllipsis(1);
      .content {
        padding: j(10) 0;
        width: 100%;
        box-sizing: border-box;
        @include halfBorder("bottom", #eee);
        .company-name {
          .name {
            line-height: j(25);
          }
          .search-text {
            color: #1c9fff;
          }
          .is_exist,
          .matching-reason {
            display: inline-block;
            font-size: j(12);
            padding: j(2) j(4);
            margin-left: j(6);
            border-radius: j(2);
            height: j(22);
            box-sizing: border-box;
            @extend %flex-middle-center;
          }
          .is_exist {
            color: rgba(255, 148, 68, 1);
            background-color: rgba(255, 245, 232, 1);
          }
          .matching-reason {
            color: rgba(28, 159, 255, 1);
            background-color: rgba(232, 249, 255, 1);
          }
        }
        .oper-name-wrap {
          font-size: j(12);
          color: #303233;
          margin-top: j(9);
          .search-text {
            color: #1c9fff;
          }
        }
      }
    }
    .loading {
      width: 100%;
      height: 100%;
      @extend %flex-middle-center;
      @keyframes roate {
        from {
          transform: rotate(0);
        }
        to {
          transform: rotate(360deg);
        }
      }
      .loading-pic {
        width: j(28);
        height: j(28);
        animation: roate 1s infinite;
      }
    }
    .no-result {
      padding: 0 j(72);
      box-sizing: border-box;
      height: 100%;
      @extend %flex-middle-center;
      .pic {
        height: fit-content;
      }
    }
  }
  .recommend-list {
    font-size: j(14);
    flex: 1;
    height: 100%;
    overflow: auto;
    .title {
      color: #000000;
    }
    .item {
      cursor: pointer;
      margin-right: j(10);
      margin-top: j(10);
      background: #f4f5f6;
      border-radius: 999px;
      padding: j(2) j(12);
      color: #aaafb3;
      width: fit-content;
      @extend %flex-middle-center;
      display: inline-flex;
    }
  }
}
.free-tag {
  position: absolute;
  z-index: 100;
  left: 0;
  transform: translateY(-98%);
}
</style>
