<template>
  <div class="app-container enterprises">
    <Region v-if="province" :province="province" :dataQuery="dataQuery" @addressListbtn="addressListbtn" :type="5"></Region>
    <div class="flex-box eco-header">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="本地企业" name="first"></el-tab-pane>
        <el-tab-pane label="异地备案" name="second"></el-tab-pane>
      </el-tabs>
      <!--<div class="location"><i class="el-icon-location"></i>{{province}}</div>-->
    </div>
    <div class="content">
      <div class="search">
        <el-cascader
          ref="aptitudeCode"
          :options="aptitudeCodeList"
          :props="props"
          :class="[`select-adaptive-${inputID1}`]"
          v-model="queryParams.codeStr"
          @change="iptAdaptive(inputID1,true,'handleChange')"
          placeholder="资质资格"
          collapse-tags
          clearable></el-cascader>
        <custom-time-select
          style="display: inline-block"
          :timeList="timeList"
          :class="[`select-adaptive-${inputID2}`,'custom-select']"
          v-model="queryParams.time"
          :placeholder="timePlaceholder"
          @handle-search="iptAdaptive(inputID2,'','changeSelect')"
        />
        <!--<el-input placeholder="输入关键词查询" v-model="queryParams.ename" clearable @clear="handleSearch()">-->
          <!--<i slot="prefix" class="el-icon-search"></i>-->
          <!--<el-button slot="append" @click="handleSearch()">搜索</el-button>-->
        <!--</el-input>-->
        <!--&lt;!&ndash; 未点击前的输入框样式 &ndash;&gt;-->
        <!--<div class="normal-search-container" @click="showSearchBox = true" v-if="!showSearchBox">-->
          <!--<img src="@/assets/images/enterprise/enterprise-search-icon.svg" alt="">-->
          <!--<span>搜索</span>-->
        <!--</div>-->
        <!--&lt;!&ndash; 输入框展开后样式 &ndash;&gt;-->
        <!--<transition @enter="onEnter" appear mode="out-in">-->
          <!--<div class="cooperate-name enterprise-search-container" id="focus1" v-if="showSearchBox">-->
            <!--<el-input clearable @clear="handleSearch" @focus="clickFocus('focus1')" @blur="clickFocus('focus1')" v-model="queryParams.ename"-->
                      <!--placeholder="输入关键词查询"></el-input>-->
            <!--<span @click="handleSearch">搜索</span>-->
          <!--</div>-->
        <!--</transition>-->
        <!-- 未点击前的输入框样式 -->
        <div class="normal-search-container" :class="{'is-hover-search' : hover}" @mouseover="searchHover($event)"
             @mouseleave="searchUnHover($event,queryParams.ename)">
          <img src="@/assets/images/enterprise/enterprise-search-icon.svg" alt="">
          <span v-show="!hover && !queryParams.ename">搜索</span>
          <el-input v-model="queryParams.ename" placeholder="输入关键词查询"
                    @focus="searchFocus($event)" @blur="searchBlur($event)" @keydown.native.enter="handleSearch"
                    @input="value => searchInput(value)" v-show="hover || queryParams.ename">
            <template slot="suffix">
              <transition mode="out-in" appear name="fade">
                <img src="@/assets/images/enterprise/search-input-clear-icon.svg" alt="" @click.stop="queryParams.ename = '';handleSearch()"
                     v-show="showClearIcon">
              </transition>
            </template>
          </el-input>
        </div>
        <span class="total">共{{tableDataTotal}}条</span>
      </div>
      <skeleton v-if="isSkeleton" style="padding: 16px"></skeleton>
      <div class="table-item">
        <el-table
          :data="tableData"
          v-loading="tableLoading"
          border
          fit
          v-horizontal-scroll="'hover'"
          @sort-change="sortChange"
          highlight-current-row
          v-if="tableDataTotal > 0 && !isSkeleton"
          :default-sort = "{prop: 'skyCount', order: 'descending'}"
        >
          <el-table-column label="序号" width="60" align="left" fixed>
            <template slot-scope="scope">{{ pageIndex * pageSize - pageSize + scope.$index + 1 }}</template>
          </el-table-column>
          <el-table-column label="公司名称" align="left" fixed width="290">
            <template slot-scope="scope">
              <router-link v-if="scope.row.jskEid"  :to="`/company/${encodeStr(scope.row.jskEid)}`" tag="a" class="a-link" v-html="scope.row.name" ></router-link>
              <span v-else v-html="scope.row.name" ></span>
            </template>
          </el-table-column>
          <el-table-column label="注册地址" prop="domicile" width="200" :formatter="formatStatus"/>
          <el-table-column label="资质资格" prop="aptitudeCountNew" sortable="custom" width="120" :formatter="formatStatus"/>
          <el-table-column label="专业人员" prop="persionCount" sortable="custom" width="120" :formatter="formatStatus"/>
          <el-table-column label="中标业绩" prop="recentlyCount" sortable="custom" width="120" :formatter="formatStatus"/>
          <el-table-column label="最大中标金额（万元）" prop="bidMaxAmount" sortable="custom" width="170" :formatter="formatStatus"/>
          <el-table-column label="中标总金额（万元）" prop="bidSumAmount" sortable="custom" width="170" :formatter="formatStatus"/>
          <el-table-column label="四库业绩" prop="skyCount" sortable="custom" width="120" :formatter="formatStatus"/>
          <el-table-column label="公路业绩" prop="roadConservancy" sortable="custom" width="100" :formatter="formatStatus"/>
          <el-table-column label="水利业绩" prop="waterConservancy" sortable="custom" width="100" :formatter="formatStatus"/>
          <el-table-column label="常合作业主" prop="topCustomer" width="290" :formatter="formatStatus">
            <template slot-scope="scope">
              <span style="cursor: pointer;" v-if="scope.row.topCustomerId"  @click="getUipIdByCid(scope.row.topCustomerId)" class="a-link" v-html="scope.row.topCustomer" ></span>
              <span v-else>{{scope.row.topCustomer ? scope.row.topCustomer :'-'}}</span>
            </template>
          </el-table-column>
          <el-table-column label="客户（个）" prop="customerCount" sortable="custom" width="120" :formatter="formatStatus"/>
          <el-table-column label="供应商（个）" prop="supplierCount" sortable="custom" width="150" :formatter="formatStatus"/>
          <el-table-column label="常合作供应商" prop="topSupplier" width="290" :formatter="formatStatus">
            <template slot-scope="scope">
              <router-link v-if="scope.row.topSupplierId"  :to="`/company/${encodeStr(scope.row.topSupplierId)}`" tag="a" class="a-link" v-html="scope.row.topSupplier" ></router-link>
              <span v-else>{{scope.row.topSupplier ? scope.row.topSupplier :'-'}}</span>
            </template>
          </el-table-column>
        </el-table>
        <div class="empty" v-if="tableDataTotal === 0 && !isSkeleton">
          <img class="img" src="@/assets/images/project/empty.png">
          <div class="p1">抱歉，没找到相关数据</div>
          <div class="p2">建议调整关键词或筛选条件，重新搜索</div>
        </div>
      </div>
      <div class="pagination-box" v-if="show_page && tableDataTotal>pageSize">
        <el-pagination background :current-page="pageIndex" :page-size="pageSize" :total="tableDataTotal" layout="prev, pager, next, jumper" @current-change="handleCurrentChange" @size-change="handleSizeChange" />
      </div>
    </div>
    <!--<LocalEnterprises v-if="activeName === 'first'"></LocalEnterprises>-->
    <!--<Offsite v-if="activeName === 'second'"></Offsite>-->
  </div>
</template>

<script>

  // import LocalEnterprises from './component/localEnterprises'
  // import Offsite from './component/offsite'
  import {encodeStr} from "@/assets/js/common.js"
  import aptitudeCode from '@/assets/json/aptitudeCode'
  import CustomTimeSelect from '../component/CustomTimeSelect'
  import { enterprise,location,getUipIdByCid } from '@/api/macro/macro'
  import Region from '../component/region'
  import skeleton from '../component/skeleton'
  import { v4 } from "uuid";
  import gsap from "gsap";
export default {
  name: 'Enterprises',
  components: {Region,skeleton,CustomTimeSelect},
  data() {
    return {
      encodeStr,
      activeName: 'first',
      dataQuery:{},
      queryParams:{
        ename:'',
        codeStr:'',
        time:'',
      },
      props: {
        value: 'id',
        multiple: true,
        checkStrictly:true,
        label:'name',
        children:'list',
        expandTrigger:'hover'
      },
      tableData: [],
      tableLoading: false,
      pageIndex: 1,
      pageSize: 50,
      tableDataTotal: null,
      aptitudeCodeList:[],
      aptitudeType:'',
      province:'',
      provinceId:'',
      show_page:true,
      MaxPage:500,
      isSkeleton:true,
      timeList: ['近半月', '近一月', '近半年', '近一年', '自定义'],
      timePlaceholder:'中标时间',
      inputID1:this.getUid(),
      inputID2:this.getUid(),
      showClearIcon: false,
      hover: false,
    }
  },
  created() {
    location({}).then(res => {
      this.province=res.data.province;
      this.provinceId=res.data.provinceId
      this.querySubmit()
    })
    this.aptitudeCode()

  },
  mounted() {
    // window.addEventListener("scroll",this.scrolling)
  },
  beforeDestroy() {
    // window.removeEventListener("scroll", this.scrolling);
  },
  methods: {
    onEnter(el, done) {
      gsap.from(el, {
        opacity: 0,
        width: 0,
      });
      gsap.to(el, {
        opacity: 1,
        width: 242,
        onComplete() {
          //  完成动画聚焦输入框
          el.querySelector("input").focus();
          done();
        }
      });
    },
    scrolling() {
      let el = document.getElementsByClassName("el-table__fixed-header-wrapper")[0]
      let scrollTop =window.pageYOffset ||document.documentElement.scrollTop ||document.body.scrollTop;
      if (scrollTop>197){
        let top = scrollTop-197
        el.style.top = top+'px'
      }else{
        el.style.top = 0
      }
    },
  //资质Json
    async aptitudeCode() {
      // await axios.post("https://files.jiansheku.com/file/json/common/aptitudeCode.json", {}, {
      //   headers: {
      //     'Content-Type': 'application/json'
      //   }
      // }).then(res => {
      //   if (res.data.code == 200) {
      //     console.log(res.data.data)
      //   }
      // })
      this.aptitudeCodeList=aptitudeCode
    },
    async querySubmit(){
      // this.isSkeleton = true;
      this.tableLoading = true;
      const params = {}
      params.page={
        limit:this.pageSize,
        page:this.pageIndex,
      }
      if(this.queryParams.field){
        params.page.field=this.queryParams.field
      }
      if(this.queryParams.order){
        params.page.order=this.queryParams.order
      }
      params.aptitudeQueryDto={
        filePlaceType:this.activeName === 'first' ? 3 : 2,
        aptitudeSource:'new',
        aptitudeQueryType:'or',
        filePlaceCode:this.provinceId
      }
      if(this.queryParams.ename){
        params.aptitudeQueryDto.ename=this.queryParams.ename
      }
      if(this.queryParams.time.length > 1){
        params.recentlyBidQueryDto=[
          {
            startTenderTime:this.queryParams.time[0],
            endTenderTime:this.queryParams.time[1]
          }
        ]
      }
      if(this.aptitudeType){
        let aptitudeType=[];
        aptitudeType.push({
          codeStr:this.aptitudeType,
          queryType: "and",
          aptitudeType: "qualification"
        })
        params.aptitudeQueryDto.aptitudeDtoList=aptitudeType
      }
      enterprise(params).then(res => {
        this.isSkeleton = false
        this.tableLoading = false
        if(res.code === 200){
          this.tableData=res.data.list;
          this.tableDataTotal=res.data.total;
        }
      })
    },
    // 重置页数
    handleSizeChange(val) {
      // this.pageIndex = 1
      // this.pageSize = val
      // this.querySubmit()
    },
    // 跳转指定页数
    handleCurrentChange(val) {
      if(this.MaxPage<val){
        this.show_page = false
        this.$nextTick(() => {
          this.pageIndex = 1
          this.$message.warning(`对不起，最多只能访问${this.MaxPage}页`)
          this.show_page = true
        })
      }else {
        this.pageIndex = val
        this.querySubmit()
      }
    },
    handleChange(){
      // console.log(this.queryParams.codeStr)
      let codeStr=this.queryParams.codeStr;
      let arr=[]
      for(let i=0; i<codeStr.length; i++){
        arr.push(codeStr[i][codeStr[i].length - 1])
      }
      this.aptitudeType=arr.join(',')
      this.$refs.aptitudeCode.toggleDropDownVisible(false)
      this.pageIndex=1;
      this.querySubmit()
    },
    handleClick(){
      this.queryParams.codeStr=[]
      this.aptitudeType='';
      this.queryParams={
        ename:'',
        codeStr:'',
        time:'',
      }
      this.showSearchBox=false;
      this.pageIndex=1;
      this.querySubmit()
    },
    handleSearch(name){
      if(name === 'handleChange'){
        this.handleChange()
      }else {
        this.pageIndex=1;
        this.querySubmit()
      }
    },
    searchFocus(event) {
      const { target } = event;
      if (target?.value?.length) {
        this.showClearIcon=true
      }
    },
    searchBlur(event) {
      this.showClearIcon=false
    },
    searchInput(value) {
      if (value?.length) {
        this.showClearIcon=true
      }
    },
    searchHover(event) {
      this.hover=true
    },
    searchUnHover(event, value) {
      if (!value) {
        this.hover=false
      }
    },
    formatStatus: function(row, column, cellValue) {
      return cellValue? cellValue : '-'
    },
    sortChange({ column, prop, order }){
      if(prop === 'aptitudeCountNew'){
        this.queryParams.field ='aptitudeCountNew'
      }else {
        this.queryParams.field = prop
      }
      if(column.order === "ascending"){
        this.queryParams.order = 'asc'
      }else if(column.order === "descending"){
        this.queryParams.order = 'desc'
      }else {
        this.queryParams.order=''
        this.queryParams.field=''
      }
      this.pageIndex = 1;
      this.querySubmit()
    },
    getUipIdByCid(companyId){
      var params=[companyId]
      getUipIdByCid(params).then(res=>{
        if (res.code==200) {
          if(res.data&&res.data.length>0&&res.data[0].uipId){
            this.$router.push({path: '/enterprise/'+this.encodeStr(companyId)})
          }else{
            this.$router.push({path: '/company/'+this.encodeStr(companyId)})
          }

        }
      }).catch(error=>{

      });
    },
    addressListbtn(data) {
      this.province=data.province;
      this.provinceId=data.provinceId[data.provinceId.length-1];
      this.dataQuery.province=data.provinces;
      let params={}
      if(data){
        params.provinceId=this.provinceId
      }
      this.querySubmit()
      location(params).then(res => {
        console.log(res.data)
      })
    },
    changeSelect(){
      this.pageIndex=1;
      this.querySubmit()
    },
    getUid() {
      return v4();
    },
    iptAdaptive(uid, multiple = false,name) {
      multiple ? this.multipleAdaptiveHandle(uid,name) : this.iptAdaptiveHandle(uid);
    },
    // 多选处理
    async multipleAdaptiveHandle(uid,name) {
      try {
        await this.$nextTick();
        const dom = document.querySelector(`.select-adaptive-${uid}`);
        const iptChild = dom.querySelector(".el-input__inner");
        if (dom) {
          const textContainer = document.createElement("span");
          const textName = `text-${uid}`;
          textContainer.classList.add(textName);
          const selectChildren = dom.querySelectorAll(".el-tag");
          if (selectChildren.length) {
            let width = 0;
            selectChildren.forEach(item => {
              const text = item.textContent;
              const itemInfo = window.getComputedStyle(item);
              textContainer.style.setProperty("visibility", "hidden");
              textContainer.style.setProperty("display", "inline-block");
              textContainer.style.setProperty("font-size", "14px");
              textContainer.style.setProperty("padding", itemInfo.padding);
              textContainer.style.setProperty("box-sizing", "border-box");
              textContainer.textContent = text;
              document.body.append(textContainer);
              width += textContainer.offsetWidth + parseInt(itemInfo.marginLeft) + parseInt(itemInfo.marginRight);
              textContainer.remove();
            });
            dom.style.setProperty("width", `${width + 50}px`);
            this.handleSearch(name);
            return;
          }
          textContainer.style.setProperty("visibility", "hidden");
          textContainer.style.setProperty("display", "inline-block");
          textContainer.style.setProperty("font-size", "14px");
          textContainer.style.setProperty("padding", "0px 8px");
          textContainer.style.setProperty("box-sizing", "border-box");
          textContainer.textContent = iptChild.getAttribute("placeholder");
          document.body.append(textContainer);
          // let containerWidth = textContainer.offsetWidth + 12 + 8;
          let containerWidth = 110;
          textContainer.remove();
          dom.style.setProperty("width", `${containerWidth}px`);
          this.handleSearch(name);
        }

      } catch (error) {
        console.log(error);
      }
    },
    // 单选处理
    async iptAdaptiveHandle(uid) {
      try {
        await this.$nextTick();
        const dom = document.querySelector(`.select-adaptive-${uid}`);
        const realStyles = window.getComputedStyle(dom);
        if (dom) {
          const iptChild = dom.querySelector(".el-input__inner");
          const textContainer = document.createElement("span");
          const textName = `text-${uid}`;
          textContainer.classList.add(textName);
          textContainer.style.setProperty("visibility", "hidden");
          textContainer.style.setProperty("display", "inline-block");
          textContainer.style.setProperty("font-size", "14px");
          const hasPadding = (parseInt(realStyles.paddingLeft) || parseInt(realStyles.paddingRight)) ? true : false;
          hasPadding ? textContainer.style.setProperty("padding", "0px 8px") : null;
          textContainer.style.setProperty("box-sizing", "border-box");
          textContainer.textContent = iptChild.value ? iptChild.value : iptChild.getAttribute("placeholder");
          document.body.append(textContainer);
          let containerWidth = textContainer.offsetWidth + 50;
          textContainer.remove();
          dom.style.setProperty("width", `${containerWidth}px`);
        }
        this.changeSelect();
      } catch (error) {

      }
    },
    clickFocus(e) {
      document.getElementById(e).classList.toggle('span-ba');
    }
  }
}
</script>

<style lang="scss" scoped>
  .app-container{
    padding: 0;
  }
  .enterprises{
    @import "@/assets/styles/search-common.scss";
    .eco-header{
      justify-content: space-between;
      height: 48px;
      background: #FFFFFF;
      border-radius: 4px;
      padding:0 16px;
      color: #232323;
      ::v-deep .el-tabs{
        height: 48px;
        line-height: 48px;
        .el-tabs__nav-wrap::after {
          position: static !important;
        }
        .el-tabs__header{
          margin: 0;
          .el-tabs__item{
            padding: 0 16px;
            font-size: 16px;
          }
          .is-active{
            font-weight: bold;
          }
        }
        .el-tabs__content{
          width: 100%;
        }
      }
      .location{
        font-size: 14px;
        color: #0081FF;
        i{
          margin-right: 6px;
          font-size: 16px;
        }
      }
    }
    .content{
      background: #FFFFFF;
      border-radius: 4px;
      margin-top: 12px;
      padding: 16px;
      .search{
        height: 34px;
        >div{
          float: left;
        }
        ::v-deep .el-cascader{
          width: 110px;
          margin-right: 12px;
          height: 34px;
          line-height: 34px !important;
          .el-input{
            width: 100%;
            height: 100%;
            .el-input__inner{
              border: 0;
              width: 100%;
              height: 100%;
            }
          }
          .is-focus{
            .el-input__inner {
              background: #F4F6F9;
            }
          }
          .el-cascader__tags{
            flex-wrap: inherit;
            .el-tag{
              /*max-width: 100px;*/
              margin: 5px 0 2px 6px;
            }
          }
        }
        ::v-deep .el-input.el-input-group:has(:focus){
          border-color: #0081FF;
        }
        ::v-deep .el-input.el-input-group{
          width: 240px;
          height: 34px;
          border-radius:2px;
          margin-left: 12px;
          border: 1px solid #e0e0e0;
          .el-input__inner{
            width: 100%;
            height: 100%;
            border: 0;
          }
          .el-input__suffix{
            margin-top: -1px;
          }
          .el-icon-search{
            font-size: 14px;
            line-height: 32px;
            color:#0081FF;
            margin-left: 6px;
            margin-right: 4px;
          }
          .el-input__inner:focus ~.el-input-group__append{
            border: 1px solid #0081FF;
            color: #ffffff;
            background: #0081FF;
          }
          .el-input-group__append{
            width: 60px;
            padding: 0;
            text-align: center;
            background: #F5F5F5;
            color:#0081FF;
            border-radius:0 2px 2px 0;
            border: 0;
            &:hover{
              color: #ffffff;
              background: #0081FF;
            }
          }
        }
        .total{
          float: right;
          color: #3D3D3D;
          font-size: 12px;
          line-height: 36px;
          &:before{
            content: "";
            display: inline-block;
            width: 2px;
            height: 2px;
            background: rgba(35, 35, 35, 0.4);
            margin-right: 4px;
            margin-bottom: 3px;
          }
        }
        ::v-deep .normal-search-container {
          display: flex;
          align-items: center;
          line-height: 32px;
          height: 32px;
          &.is-hover-search {
            width: 238px;
            background: #f4f6f9;
            border-radius: 4px 4px 4px 4px;

            & > img {
              cursor: unset;
            }
          }

          &:hover {
            & > span {
              color: #0081ff;
            }
          }

          & > img {
            width: 16px;
            height: 16px;
            margin-left: 12px;
            cursor: pointer;
          }

          & > span {
            color: rgba(35, 35, 35, 0.8);
            font-weight: 400;
            margin-left: 8px;
            line-height: 22px;
            font-size: 14px;
            cursor: pointer;
          }

          .el-input {
            & > .el-input__inner {
              border: none;
              height: 32px;
              line-height: 32px;
              caret-color: #0081ff;
              color: rgba(35, 35, 35, 0.8);
              font-size: 14px;
              background: #f4f6f9;
              padding-right: 26px;
              padding-left: 8px;

              &::placeholder {
                color: rgba(35, 35, 35, 0.4) !important;
                font-size: 14px !important;
                line-height: 32px;
              }
            }
            .el-input__suffix {
              right: 12px;
              display: flex;
              align-items: center;

              .el-input__suffix-inner {
                height: 14px;
                width: 14px;
              }

              img {
                cursor: pointer;
                vertical-align: unset;
                margin-bottom: 14px;
              }
            }
          }
        }
        .cooperate-name {
          margin-left: 12px;
          display: flex;
          border-radius: 2px;
          border: 1px solid #d9d9d9;
          line-height: 34px;
          height: 34px;
          float: left;
          span {
            width: 60px;
            height: 32px;
            line-height: 32px;
            font-size: 14px;
            background: #f5f5f5;
            text-align: center;
            color: #0081ff;
            border: 1px solid #efefef;
            border-left: 0;
            cursor: pointer;
          }
          &.span-ba {
            border: 1px solid #0081ff;
            span {
              color: #ffffff;
              background: #0081ff;
              border: 1px solid #0081ff;
            }
          }
          ::v-deep .el-input {
            flex: 1;
          }
          ::v-deep .el-input__inner {
            border: 0;
            line-height: 32px;
            height: 32px;
            position: absolute;
            top: 0;
            padding-right: 28px;
            font-size: 12px;
            padding-left: 8px;
          }
        }
      }
      .table-item{
        margin-top: 14px;
        .empty{
          margin: 0 auto;
          height: 600px;
          text-align: center;
          border-top: 1px solid #EFEFEF;
          .img{
            width: 108px;
            height: 108px;
            margin-bottom: 24px;
            margin-top: 150px;
          }
          .p1{
            color: #333333;
            font-size: 16px;
          }
          .p2{
            color: #999999;
            font-size: 14px;
            margin-top: 8px;
          }
        }
        ::v-deep .el-table{
          overflow:visible;
          .el-table__header-wrapper{
            position: sticky;
            top:56px;
            z-index: 9;
          }
          .el-table__fixed-header-wrapper{
            position: sticky;
            z-index: 9;
            top: 56px;
          }
          .el-table__fixed{
            overflow-x: clip;
            overflow-y: clip;
          }
          th{
            font-size: 13px !important;
            font-weight: 400 !important;
          }
          .el-table__fixed-header-wrapper th{
            background: #F0F3FA;
          }
          td.el-table__cell{
            border-bottom: 0;
          }
          .caret-wrapper{
            width: 10px;
          }
        }
      }
    }
  }

</style>
