<template>
  <div class="es-public-search-box">
    <el-input
      class="es-public-search-input"
      placeholder="请输入关键字"
      clearable
      prefix-icon="el-icon-search"
      v-model="keyWords"
      round
    ></el-input>
    <el-tabs class="es-public-search-tabs" v-model="active">
      <el-tab-pane label="综合" name="0">
        <el-scrollbar class="es-scrollbar">
          <template v-for="(item, index) in types">
            <div
              v-if="item.records && item.records.length"
              class="es-public-search-content"
              :key="item.id"
            >
              <div class="es-public-search-title">{{ item.name }}</div>
              <ul class="es-public-search-list">
                <li
                  v-for="(ele, idx) in item.records.slice(0, 3)"
                  class="es-public-search-list-item"
                  :key="ele.id || `${item.id}_${ele.title}_${idx}`"
                  @click="handleClick(ele, item)"
                >
                  <es-icon
                    class="es-public-search-item-icon"
                    v-bind="getIcon(ele, item)"
                    :style="setStyle(ele, index)"
                  ></es-icon>
                  <div class="es-public-search-item-name">
                    {{ ele.name || ele.title || ele.text }}
                  </div>
                  <div class="es-public-search-item-texts" v-if="ele.summary">
                    {{ ele.summary }}
                  </div>
                  <div class="es-public-search-item-texts">
                    <template v-if="Array.isArray(ele.infos || ele.footer)">
                      <span
                        v-for="(text, idx) in ele.infos || ele.footer"
                        class="es-public-search-item-text"
                        :key="idx"
                        >{{ text }}</span
                      >
                    </template>
                    <template v-else>{{ ele.infos || ele.footer }}</template>
                  </div>
                </li>
              </ul>
              <div class="es-public-search-more">
                <span
                  class="es-public-search-more-text"
                  @click="handleTabs(item, index)"
                  >在<span class="es-public-search-more-quote">{{
                    item.name
                  }}</span
                  >中搜索全部</span
                >
              </div>
            </div>
          </template>
        </el-scrollbar>
      </el-tab-pane>
      <template v-for="(item, index) in types">
        <el-tab-pane
          :label="item.name"
          :name="item.id || String(index + 1)"
          :key="item.id"
          lazy
          v-loading="loadings[item.id || String(index)]"
          element-loading-background="rgba(0, 0, 0, 0.01)"
          element-loading-text="加载中..."
          v-if="!hides.includes(item.name) && !item.hide"
        >
          <el-scrollbar
            class="es-scrollbar es-public-search-scrollbar"
            :infinite-scroll="
              () => {
                handleSearchd(item, index);
              }
            "
            :infinite-scroll-disabled="disabled"
            :infinite-scroll-immediate="false"
          >
            <div class="es-public-search-info" v-show="keyWords">
              {{ item.totalCount }}条与"<span
                class="es-public-search-more-quote"
                >{{ keyWords }}</span
              >"相关的搜索结果
            </div>
            <ul class="es-public-search-lists">
              <li
                v-for="(ele, idx) in item.records"
                class="es-public-search-list-item"
                :key="ele.id || `${item.id}_${ele.title}_${idx}`"
                @click="handleClick(ele, item)"
              >
                <es-icon
                  class="es-public-search-item-icon"
                  v-bind="getIcon(ele, item)"
                  :style="setStyle(ele, index)"
                ></es-icon>
                <div class="es-public-search-item-name">
                  {{ ele.name || ele.title || ele.text }}
                </div>
                <div class="es-public-search-item-texts" v-if="ele.summary">
                  {{ ele.summary }}
                </div>
                <div class="es-public-search-item-texts">
                  <template v-if="Array.isArray(ele.infos || ele.footer)">
                    <span
                      v-for="(text, idx) in ele.infos || ele.footer"
                      class="es-public-search-item-text"
                      :key="idx"
                      >{{ text }}</span
                    >
                  </template>
                  <template v-else>{{ ele.infos || ele.footer }}</template>
                </div>
              </li>
            </ul>
            <p
              class="es-public-search-no-more"
              v-if="noMore[item.id || String(index)]"
            >
              没有更多了
            </p>
          </el-scrollbar>
        </el-tab-pane>
      </template>
    </el-tabs>
    <es-dialog :title="title" :visible.sync="visible" size="max">
      <iframe width="100%" height="100%" frameborder="0" :src="url"></iframe>
    </es-dialog>
  </div>
</template>

<script>
import util from 'eoss-ui/src/utils/util';
import { searchType } from 'eoss-ui/src/config/api.js';
import { debounce } from 'throttle-debounce';
export default {
  name: 'Search',
  components: {},
  props: {
    menuIcon: {
      type: String,
      default: 'es-icon-application'
    },
    menus: {
      type: Array,
      default() {
        return [];
      }
    },
    apps: {
      type: Array,
      default() {
        return [];
      }
    },
    searchType: {
      type: String,
      default: searchType
    },
    pageSize: {
      type: Number,
      default: 10
    },
    hides: {
      type: Array,
      default() {
        return [];
      }
    }
  },
  data() {
    return {
      icons: {
        ppt: 'es-icon-ppt',
        png: 'es-icon-solid-tupian',
        gif: 'es-icon-solid-tupian',
        jpg: 'es-icon-solid-tupian',
        xls: 'es-icon-excel',
        xlsx: 'es-icon-excel',
        docx: 'es-icon-word',
        doc: 'es-icon-word',
        rar: 'es-icon-zip',
        zip: 'es-icon-zip',
        txt: 'es-icon-txt',
        ipa: 'es-icon-pingguo',
        apk: 'es-icon-anzhuo',
        mp4: 'es-icon-video',
        avi: 'es-icon-video',
        mp3: 'es-icon-audio',
        wma: 'es-icon-audio',
        pdf: 'es-icon-pdf'
      },
      colors: [
        '#46D3BA',
        '#2591F7',
        '#40C274',
        '#E34D59',
        '#FF9C52',
        '#17C27B'
      ],
      keyWords: '',
      active: '0',
      types: [],
      lists: [],
      loadings: {},
      noMore: {},
      isLoading: false,
      title: '',
      visible: false,
      url: ''
    };
  },
  computed: {
    loading() {
      return this.active == '0' && this.isLoading;
    },
    disabled() {
      return this.loadings[this.active] || this.noMore[this.active];
    }
  },
  watch: {
    keyWords(val) {
      this.handleSearchAll(val);
    }
  },
  beforeCreate() {
    this.handleSearchAll = debounce(1000, (res) => {
      this.searchAll(res);
    });
    this.handleSearchd = debounce(500, (obj, index) => {
      this.handleSearch(obj, index, false);
    });
  },
  created() {
    this.getTypes();
  },
  mounted() {},
  methods: {
    getIcon(res, item) {
      let icon;
      let cls;
      if (res.icon || res.icons) {
        icon = this.icons[(res.icon || res.icons).toLowerCase()];
        if (!icon) {
          if (res.icon == '#last' || res.icons == '#last') {
            let title = res.title || res.name || res.text;
            icon = title.substr(-1, 1);
            cls = 'es-public-search-item-icon-text';
          } else {
            cls = 'es-public-search-item-icons';
            icon = res.icon || res.icons;
          }
        }
      } else {
        let title = res.title || res.name || res.text;
        let key = title.split('.')[1];
        icon = key ? this.icons[key.toLowerCase()] : '';
        if (!icon) {
          icon =
            item.name == '菜单' || item.name == '应用'
              ? this.menuIcon
              : title.substr(-1, 1);
          cls = 'es-public-search-item-icon-text';
        }
      }
      return { class: cls, contents: icon };
    },
    setStyle(res, index) {
      if (res.icon || res.icons) {
        let icon = this.icons[(res.icon || res.icons).toLowerCase()];
        if (!icon && res.icon != '#last') {
          return { backgroundColor: this.colors[index % this.colors.length] };
        }
      } else {
        return { backgroundColor: this.colors[index % this.colors.length] };
      }
      return {};
    },
    getTypes() {
      util
        .ajax({
          url: this.searchType,
          method: 'post',
          format: false,
          data: {
            terminalType: 'web'
          }
        })
        .then((res) => {
          if (res.rCode == 0) {
            let { results } = res;
            let loadings = {};
            let noMore = {};
            let types = results.catalog.map((item, index) => {
              loadings[item.id || String(index)] = false;
              noMore[item.id || String(index)] = false;
              return {
                ...item,
                pageNum: 0,
                pageCount: 1,
                records: [],
                hide:
                  item.name == '应用' && this.apps.length == 0 ? true : false
              };
            });
            this.types = types;
            this.loadings = loadings;
            this.noMore = noMore;
          }
        });
    },
    searchAll(keyWords) {
      for (let i = 0; i < this.types.length; i++) {
        let item = this.types[i];
        if (keyWords && !this.hides.includes(item.name) && !item.hide) {
          this.types[i].records = [];
          this.types[i].totalCount = 0;
          this.types[i].pageCount = 1;
          this.types[i].pageNum = 0;
          this.$set(this.loadings, item.id || String(i), true);
          this.$set(this.noMore, item.id || String(i), false);
          if (item.name == '菜单' && this.menus.length) {
            this.isLoading = false;
            this.types[i].records = this.searchData(this.menus, keyWords);
            this.types[i].totalCount = this.types[i].records.length;
            this.types[i].pageCount = 1;
            this.types[i].pageNum = 1;
            this.$set(this.loadings, item.id || String(i), false);
            this.$set(this.noMore, item.id || String(i), true);
          } else if (item.name == '应用' && this.apps.length) {
            this.isLoading = false;
            this.types[i].records = this.searchData(this.apps, keyWords);
            this.types[i].totalCount = this.types[i].records.length;
            this.types[i].pageCount = 1;
            this.types[i].pageNum = 1;
            this.$set(this.loadings, item.id || String(i), false);
            this.$set(this.noMore, item.id || String(i), true);
          } else if (item.dataRequestUrl) {
            this.isLoading = true;
            this.handleSearch(item, i, true);
          } else {
            this.types[i].records = [];
            this.types[i].totalCount = 0;
            this.types[i].pageCount = 1;
            this.types[i].pageNum = 0;
            this.$set(this.loadings, item.id || String(i), false);
            this.$set(this.noMore, item.id || String(i), true);
          }
        } else {
          this.isLoading = false;
          this.types[i].records = [];
          this.types[i].totalCount = 0;
          this.types[i].pageCount = 1;
          this.types[i].pageNum = 0;
          this.$set(this.loadings, item.id || String(i), false);
          this.$set(this.noMore, item.id || String(i), true);
        }
      }
    },
    searchData(data, name) {
      let records = [];
      data.forEach((item) => {
        let words = item.name || item.text;
        if (words.indexOf(name) > -1 && item.permission !== false) {
          records.push(item);
        }
        if (item.children && item.children.length) {
          records = records.concat(this.searchData(item.children, name));
        }
        if (item.fourthTabs && item.fourthTabs.length) {
          records = records.concat(this.searchData(item.fourthTabs, name));
        }
      });
      return records;
    },
    handleSearch(obj, index, reset) {
      if (obj.pageNum < obj.pageCount && this.keyWords) {
        this.$set(this.loadings, obj.id || String(index), true);
        if (this.active == '0') {
          this.isLoading = true;
        }
        util
          .ajax({
            url: obj.dataRequestUrl,
            method: 'post',
            format: false,
            data: {
              pageNum: obj.pageNum + 1,
              pageSize: this.pageSize,
              search: this.keyWords,
              terminalType: 'web'
            }
          })
          .then((res) => {
            this.$set(this.loadings, obj.id || String(index), false);
            let flag = false;
            for (let i in this.loadings) {
              if (this.loadings[i]) {
                flag = true;
                break;
              }
            }
            if (!flag) {
              this.isLoading = false;
            }
            if (res.rCode == 0) {
              let { results } = res;
              obj.totalCount = results.totalCount;
              obj.pageCount = results.pageCount;
              obj.pageNum = results.pageNum;
              obj.records = reset
                ? results.records
                : obj.records.concat(results.records);
              this.$set(
                this.noMore,
                obj.id || String(index),
                results.pageNum >= results.pageCount
              );
            } else {
              this.types[index].records = [];
              this.types[index].totalCount = 0;
              this.types[index].pageCount = 1;
              this.types[index].pageNum = 0;
              this.$set(this.loadings, obj.id || String(index), false);
              this.$set(this.noMore, obj.id || String(index), true);
            }
          })
          .catch((err) => {
            this.isLoading = false;
            this.types[index].records = [];
            this.types[index].totalCount = 0;
            this.types[index].pageCount = 1;
            this.types[index].pageNum = 0;
            this.$set(this.loadings, obj.id || String(index), false);
            this.$set(this.noMore, obj.id || String(index), true);
            if (err.message && err.message !== 'canceled') {
              this.$message.error(err.message);
            }
          });
      }
    },
    handleTabs(res, index) {
      this.active = res.id || String(index + 1);
    },
    handleClick(res, parent) {
      if (res.detailUrl) {
        this.title = res.title;
        this.url = res.detailUrl;
        this.visible = true;
      } else {
        this.$emit('select', res, parent);
      }
    }
  }
};
</script>
