<template>
  <div>
    <WlPopup
      v-model="popUpVisible"
      round
      position="bottom"
      :style="popStyle"
      :overlay-style="{
        zIndex: 2000,
      }"
      @onClose="onClosePopup"
      :closeOnClickAction="true"
    >
      <div
        class="search-enterprise-popup"
        data-weiling-mobile-ui-bc-search-enterprise-popup
      >
        <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="showRecommend">
            <span class="title">推荐：</span>
            <span
              @click="onSelectRecommend(item)"
              class="item"
              v-for="(item, index) in recommendList?.list"
              :key="index"
            >
              {{ item }}
            </span>
          </div>
          <div class="search-result" v-else>
            <template v-if="searchResult.length !== 0 && !showLoading">
              <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.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"></span>
                  </p>
                </div>
              </div>
            </template>
            <div v-else-if="showLoading" class="loading">
              <div class="loading-pic">
                <WlPic :src="loading" />
              </div>
            </div>
            <div
              v-else-if="
                !searchValue && searchResult.length === 0 && !showLoading
              "
            >
              <WlPic :src="corp_search_no_result" />
            </div>
          </div>
        </div>
      </div>
    </WlPopup>
    <Tip
      v-model="matching"
      :company_name="searchValue"
      @close_tip_visible="close_tip_visible"
    />
  </div>
</template>

<script lang="ts">
export default {
  name: "BCSearchEnterprisePopup",
};
</script>

<script lang="ts" setup>
import Api from "./http/api";
import Store from "@mobileUI/store";
import { onDebounce } from "@mobileUI/utils/index";
import loading from "@mobileUI/assets/images/loading.png";
import { ref, computed, nextTick, watch, Ref } from "vue";
import WlPic from "@mobileUI/components/WlPic/src/index.vue";
import WlPopup from "@mobileUI/components/WlPopup/src/index.vue";
import WlSearch from "@mobileUI/components/WlSearch/src/index.vue";
import LimitedTimeFreeTag from "./components/LimitedTimeFreeTag/index.vue";
import Tip from "./components/Tip/index.vue";
import { corp_search_no_result } from "@mobileUI/utils/cdn";

//检查搜索值
type CompanyInfo = {
  company_id: string;
  creditCode: number;
  credit_code: string;
  label: string;
  flag: number;
  highlightLabel: string;
  highlightOper: string;
  match_type: string;
  name: string;
  oper_name: string;
  platform_id: string;
  start_date: string;
  status: string;
  isExist: boolean;
  value: string;
  env_data: TEnv.TEnvData;
};
const emit = defineEmits<{
  (e: "onChange", val: string);
  (e: "onChoose", val: any);
  (e: "update:modelValue", val: boolean);
  (e: "onClose");
  (e: "sendSearchValue", val: string);
}>();
let popUpVisible = ref(false);
let searchValue = ref("");
let showLoading = ref(false);
let searchResult: Ref<Array<CompanyInfo>> = ref([]);
type Props = {
  defaultSearchVal?: string;
  modelValue?: boolean;
  recommendList?: Object;
  needFreeTag?: boolean;
  hidden_mathch_type?: Object;
  env_data: TEnv.TEnvData;
};
const props = withDefaults(defineProps<Props>(), {
  defaultSearchVal: "",
  modelValue: false,
  recommendList: () => {
    return { list: [] };
  },
  needFreeTag: true,
  hidden_mathch_type: () => {
    return { type: ["公司名称匹配", "法定代表人匹配"] };
  },
  env_data: () => {
    return {
      sid: "",
      domain: "",
      corp_id: "",
      node_env: "dev",
      app_id: "",
      token: "",
      card_resource: "",
    };
  },
});
const showRecommend = computed(() => {
  return !searchValue.value && props.recommendList?.list?.length !== 0;
});
Store.corp_id = props.env_data.corp_id;
Store.sid = props.env_data.sid;
Store.node_env = props.env_data.node_env;
Store.token = props.env_data.token;
Store.card_resource = props.env_data.card_resource;
const getData = async () => {
  if (!searchValue.value) {
    searchResult.value = [];
    showLoading.value = false;
    onSetTipVisible(searchResult.value);
    return;
  }
  const res = await Api.getCompanySearchList(
    {
      keyword: searchValue.value,
      corp_id: props.env_data.corp_id,
      sid: props.env_data.sid,
    },
    props.env_data.node_env
  );
  const { data = [] } = res;
  const list = data.map((ele: any) => {
    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(
        searchValue,
        `<span class="search-text">${searchValue}</span>`
      ),
      highlightOper: oper_name?.replace(
        searchValue,
        `<span class="search-text">${searchValue}</span>`
      ),
    };
  });
  searchValue.value ? (searchResult.value = list) : (searchResult.value = []);
  showLoading.value = false;
  onSetTipVisible(searchResult.value);
};

const onClosePopup = () => {
  //给350毫秒延迟让动画有时间执行
  setTimeout(() => {
    emit("update:modelValue", false);
  }, 350);
  emit("onClose");
  nextTick(() => {
    popUpVisible.value = false;
  });
};

const onClear = () => {
  searchValue.value = "";
  showLoading.value = false;
  onClearList();
};

const onChange = (val: string) => {
  if (val.trim()) {
    showLoading.value = true;
  }
  if (val && !val.trim()) {
    searchValue.value = "";
  }
  matching.value = false;
  getData();
};
const onChoose = (item: any) => {
  emit("onChoose", item);
  popUpVisible.value = false;
  matching.value = false;
};

const onSelectRecommend = (item: any) => {
  searchValue.value = item;
  emit("onChange", item);
  showLoading.value = true;
  getData();
};

const onClearList = () => {
  searchResult.value = [];
};
const popStyle = computed(() => {
  return {
    height: "75%",
    "border-top-left-radius": props.needFreeTag ? 0 : "",
    overflow: "initial",
    zIndex: 2001,
  };
});

//完全匹配
const matching = ref(false);
//关闭提示弹窗
const close_tip_visible = (flag: boolean) => {
  matching.value = flag;
  popUpVisible.value = flag;
  emit("sendSearchValue", searchValue.value);
};
const onSetTipVisible = (list) => {
  if (searchValue.value) {
    matching.value =
      popUpVisible.value && !list.some((i) => i.label === searchValue.value);
  } else {
    matching.value = false;
  }
};

//初始化
const init = () => {
  //有可能存在默认值需要搜索一下
  if (searchValue.value !== "") {
    showLoading.value = true;
    getData();
  } else {
    onClearList();
  }
};
watch(
  () => props.modelValue,
  () => {
    popUpVisible.value = props.modelValue;
    if (!popUpVisible.value) {
      matching.value = false;
    }
    if (searchValue.value !== props.defaultSearchVal) {
      searchValue.value = props.defaultSearchVal;
      init();
    }
  },
  {
    immediate: true,
  }
);
// init();
</script>

<style lang="scss">
.search-enterprise-popup[data-weiling-mobile-ui-bc-search-enterprise-popup] {
  height: 100%;

  .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 {
        .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: var(--wl-primary-color);
            }

            .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: var(--wl-text-color-title-2);
            margin-top: j(9);

            .search-text {
              color: var(--wl-primary-color);
            }
          }
        }
      }

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

    .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: var(--wl-text-color-disabled);
        width: fit-content;
        @extend %flex-middle-center;
        display: inline-flex;
      }
    }
  }

  .free-tag {
    position: absolute;
    z-index: 100;
    left: 0;
    transform: translateY(-98%);
  }
}
</style>
