<template>
  <div id="detailPart" class="sides-container">
    <!-- 搜索栏 -->
    <div class="search-bar-container">
      <el-input placeholder="请输入内容" class="side-input" v-model="searchText" clearable @input="handleSearch(true)"
        @keyup.enter.native="handleSearch()">
        <i slot="prefix" class="el-input__icon el-icon-search" @click="handleSearch()"></i>
      </el-input>
    </div>

    <el-menu ref="sideMenu" :unique-opened="false" :default-active="searchIndex" class="detail-menu" @open="handleOpen">
      <template v-for="(item, index) in sideRoute">

        <!-- 一级菜单 -->
        <el-submenu :index="item.index" :key="item.index" v-if="item.children" class="top-level-menu"
          :disabled="item.disabled || !isCompanyId(item.title) || (item.title=='项目商机'&&statisticObj.business.landInfo<1&&statisticObj.business.busProposedProjectV1<1&&statisticObj.performance.specialDebt<1&&statisticObj.performance.bidPlan<1&&statisticObj.business.biddingAnnouncement<1&&statisticObj.business.proBiddingAnnouncement<1&&statisticObj.business.adminLicensing<1)">
          <template slot="title">
            <div class="top-level-menu-title">
              <svg-icon :iconClass="item.icon"></svg-icon>
              <span>{{item.title}}</span>
            </div>
          </template>

          <template v-for="(subItem,subIndex) of item.children">
            <!-- 二级菜单 -->
            <template v-if="subItem.children && subItem.children.length">
              <el-submenu :index="subItem.index" :key="subItem.index" class="second-level-menu-has-children">
                <template slot="title">
                  <span>{{subItem.title}}</span>
                </template>
                <!-- 三级菜单 -->
                <template v-for="(threeLevelMenu,threeLevelIndex) of subItem.children">
                  <el-menu-item :index="threeLevelMenu.index" :key="threeLevelMenu.index" @click="handleItem(threeLevelMenu)"
                    :disabled="!isCompanyId(threeLevelMenu.title) || threeLevelMenu.disabled" v-if="isCustomerId(threeLevelMenu.pathName)">
                    <span>{{threeLevelMenu.title}}</span>
                  </el-menu-item>
                </template>
              </el-submenu>
            </template>

            <template v-else>
              <el-menu-item class="second-level-menu-no-children" :index="subItem.index" @click="handleItem(subItem)"
                :disabled="!isCompanyId(subItem.title) || subItem.disabled" v-if="isCustomerId(subItem.pathName)">{{subItem.title}}</el-menu-item>
            </template>

          </template>

        </el-submenu>
        <template v-else>
          <el-menu-item class="top-level-menu-no-children" :index="item.index" @click="handleItem(item)"
            :disabled="!isCompanyId(item.title) || item.disabled" v-if="isCustomerId(item.pathName)">{{item.title}}</el-menu-item>
        </template>
      </template>
    </el-menu>
  </div>
</template>

<script>
import { financial } from '@/api/detail/party-a/financial';
import { detailSideBar } from "@/utils";
import { v4 } from "uuid";
import SvgIcon from "@/components/SvgIcon";
export default {
  name: 'Sidebar',
  props: {
    partBoxHeight: {
      type: Number,
      default: null
    },
    pathName: {
      type: String,
      default: null
    },
    customerId: {
      type: String,
      default: ''
    },
    isCompany: {
      type: Boolean,
      default: true
    },
    statisticObj: {
      type: Object,
      default: {}
    },
    isCustomer: {
      type: Boolean,
      default: false
    }
  },
  components: {
    SvgIcon
  },
  data() {
    return {
      searchText: '',
      sideRoute: [
        {
          title: "企业经营", icon: "enterprise-management-detail-side", pathName: "", children: [
            {
              title: '企业概要', pathName: '', children: [
                { title: '企业速览', pathName: 'overview' },
                { title: '资质资格', pathName: 'qualification' },
                { title: '工商信息', pathName: 'businfo' },
                { title: '股东信息', pathName: 'holderinfo' },
                { title: '高管信息', pathName: 'execuinfo' },
                { title: '对外投资', pathName: 'overseas' },
                { title: '分支机构', pathName: 'branch' }
              ]
            },
            { title: '财务简析', pathName: 'financial' },
            // {
            //   title: '项目商机', pathName: '', children: [
            //     { title: '重点项目', pathName: 'majorProject' },
            //     { title: '土地交易', pathName: 'landtransaction' },
            //     { title: '拟建项目', pathName: 'proposed' },
            //     { title: '专项债项目', pathName: 'bond' },
            //     { title: '招标计划', pathName: 'biddingplan' },
            //     { title: '招标公告', pathName: 'announcement' },
            //     { title: '标讯Pro', pathName: 'tencent' },
            //     { title: '行政许可', pathName: 'administrative' }
            //   ]
            // },
            // {
            //   title: '业务往来', pathName: '', children: [
            //     { title: '客户', pathName: 'custom' },
            //     { title: '供应商', pathName: 'supplier' },
            //     { title: '招标代理', pathName: 'bidagency' },
            //     { title: '历史发包', pathName: 'hiscontract' },
            //     { title: '开标记录', pathName: 'bidrecords' }
            //   ]
            // },
            {
              title: '咨询业务往来', pathName: '', children: [
                { title: '常合作业主单位', pathName: 'cooperativeOwnerUnits' },
                { title: '常合作施工单位', pathName: 'cooperativeConstructionUnit' },
                { title: '常合作集团', pathName: 'cooperativeGroup' },
              ]
            },
            // {
            //   title: '城投分析', pathName: '', children: [
            //     { title: '区域经济', pathName: 'regionalEconomies' },
            //     { title: '城投拿地', pathName: 'landAcquisition' },
            //     { title: '同地区城投', pathName: 'sameRegion' }
            //   ]
            // },
            {
              title: '信用行为', pathName: '', children: [
                { title: '信用中国', pathName: 'credit' },
                { title: '行政处罚', pathName: 'punish' },
                { title: '经营异常', pathName: 'businessAnomaly' },
                { title: '被执行人', pathName: 'ifThePerson' },
                { title: '失信被执行人', pathName: 'dishonesty' },
                { title: '限制高消费', pathName: 'limitHighConsumption' },
                { title: '股权冻结', pathName: 'equityFreezing' },
                // { title: '裁判文书', pathName: 'judgment' },
                // { title: '法院公告', pathName: 'courtNotice' },
                // { title: '开庭公告', pathName: 'openacourtsessionNotice' },
                // {title: '信用中国', pathName: ''}
              ]
            },
            { title: '商务信息', pathName: 'business' },
            { title: '招标偏好', pathName: 'preference' },
            { title: '合作情况', pathName: 'cooperate' },
            { title: '联系人', pathName: 'decisionMaking' },
            { title: '跟进记录', pathName: 'gjjl' }
          ]
        },
        {
          title: "内部合作", icon: "internal-cooperation-detail-side", pathName: "", children: [
            { title: '咨询机构合作', pathName: 'consultingAgencyCooperation' },
            {
              title: '供应商合作记录', pathName: '', children: [
                { title: '准入情况', pathName: 'accessCondition' },
                { title: '管理人员信息', pathName: 'managerial' },
                { title: '设备信息', pathName: 'equipment' },
                { title: '工程考察情况记录', pathName: 'projectRecord' },
                { title: '施工业绩', pathName: 'constructionPerformance' },
                { title: '在施工程情况', pathName: 'constructionSituation' },
                { title: '生活保障基地', pathName: 'livingSecurity' },
                { title: '合作记录', pathName: 'cooperationRecord' },
              ]
            },
            {
              title: '供应商评价信息', pathName: '', children: [
                { title: '履约评价', pathName: 'honourAgreement' },
                { title: '信用评价', pathName: 'creditRate' },
                { title: '年度考评', pathName: 'assessMent' },
              ]
            },
            {
              title: '供应商不良行为', pathName: '', children: [
                { title: '不良行为列表', pathName: 'badlist' },
              ]
            },
          ]
        }
      ],
      sideRoute1: [
        {
          title: "企业经营", pathName: "", children: [
            {
              title: '企业概要', pathName: '', children: [
                { title: '企业速览', pathName: 'overview' },
                { title: '资质资格', pathName: 'qualification' },
                { title: '工商信息', pathName: 'businfo' },
                { title: '股东信息', pathName: 'holderinfo' },
                { title: '高管信息', pathName: 'execuinfo' },
                { title: '对外投资', pathName: 'overseas' },
                { title: '分支机构', pathName: 'branch' }
              ]
            },
            { title: '财务简析', pathName: 'financial' },
            // {
            //   title: '项目商机', pathName: '', children: [
            //     { title: '重点项目', pathName: 'majorProject' },
            //     { title: '土地交易', pathName: 'landtransaction' },
            //     { title: '拟建项目', pathName: 'proposed' },
            //     { title: '专项债项目', pathName: 'bond' },
            //     { title: '招标计划', pathName: 'biddingplan' },
            //     { title: '招标公告', pathName: 'announcement' },
            //     { title: '标讯Pro', pathName: 'tencent' },
            //     { title: '行政许可', pathName: 'administrative' }
            //   ]
            // },
            // {
            //   title: '业务往来', pathName: '', children: [
            //     { title: '客户', pathName: 'custom' },
            //     { title: '供应商', pathName: 'supplier' },
            //     { title: '招标代理', pathName: 'bidagency' },
            //     { title: '历史发包', pathName: 'hiscontract' },
            //     { title: '开标记录', pathName: 'bidrecords' }
            //   ]
            // },
            {
              title: '咨询业务往来', pathName: '', children: [
                { title: '常合作业主单位', pathName: 'cooperativeOwnerUnits' },
                { title: '常合作施工单位', pathName: 'cooperativeConstructionUnit' },
                { title: '常合作集团', pathName: 'cooperativeGroup' },
              ]
            },
            // {
            //   title: '城投分析', pathName: '', children: [
            //     { title: '区域经济', pathName: 'regionalEconomies' },
            //     { title: '城投拿地', pathName: 'landAcquisition' },
            //     { title: '同地区城投', pathName: 'sameRegion' }
            //   ]
            // },
            {
              title: '信用行为', pathName: '', children: [
                { title: '信用中国', pathName: 'credit' },
                { title: '行政处罚', pathName: 'punish' },
                { title: '经营异常', pathName: 'businessAnomaly' },
                { title: '被执行人', pathName: 'ifThePerson' },
                { title: '失信被执行人', pathName: 'dishonesty' },
                { title: '限制高消费', pathName: 'limitHighConsumption' },
                { title: '股权冻结', pathName: 'equityFreezing' },
                // { title: '裁判文书', pathName: 'judgment' },
                // { title: '法院公告', pathName: 'courtNotice' },
                // { title: '开庭公告', pathName: 'openacourtsessionNotice' },
                // {title: '信用中国', pathName: ''}
              ]
            },
            { title: '商务信息', pathName: 'business' },
            { title: '招标偏好', pathName: 'preference' },
            { title: '合作情况', pathName: 'cooperate' },
            { title: '联系人', pathName: 'decisionMaking' },
            { title: '跟进记录', pathName: 'gjjl' }
          ]
        },
        {
          title: "内部合作", icon: "internal-cooperation-detail-side", pathName: "", children: [
            { title: '咨询机构合作', pathName: 'consultingAgencyCooperation' },
            {
              title: '供应商合作记录', pathName: '', children: [
                { title: '准入情况', pathName: 'accessCondition' },
                { title: '施工业绩', pathName: 'constructionPerformance' },
                { title: '在施工程情况', pathName: 'constructionSituation' },
                { title: '合作记录', pathName: 'cooperationRecord' },
              ]
            },
          ]
        }
      ],
      defaultRoute: [],
      customer: [
        'business',
        'preference',
        'cooperate',
        'decisionMaking',
        'gjjl'
      ],
      companys: [
        '企业概要',
        '财务简析',
        '项目商机',
        '业务往来',
        '城投分析',
        '风险信息',
      ],
      uniqueOpened: false,
      searchIndex: ''
    };
  },
  computed: {

  },
  created() {
    this.sideBarInit();
  },
  watch: {
    statisticObj: {
      handler(val) {
        this.createSideBarWithServerData(val);
      }
    },
    pathName: {
      handler(newValue) {
        console.log(newValue,"|||||||")
        this.searchIndex = this.findNodeIndex(this.sideRoute, newValue).index;
      }
    }
  },
  methods: {
    sideBarInit() {
      const _temp = this.sideAddUid(JSON.parse(JSON.stringify(this.sideRoute)));
      this.sideRoute = _temp;
      this.defaultRoute = JSON.parse(JSON.stringify(this.sideRoute));
      this.$nextTick(()=>{
        function getindex(data,result=[]) {
          if (data.length) {
            for (const item of data) {
              // 确保打开菜单为目录
              if (item.children && !item.pathName) {
                result.push(item.index);
                getindex(item.children, result);
              }
            }
          }
          return result
        }
        const arrlist = getindex(_temp)
        if(this.$refs.sideMenu){
        arrlist.forEach(item=>{
          this.$refs.sideMenu.open(item)
        })
        }
      })
      // this.searchIndex = this.findNodeIndex(this.defaultRoute, "overview").index;
    },
    // 查找菜单中的元素
    findNodeIndex(tree, key, findKey = "pathName", findParent = false, parenNode = null) {
      let len = tree.length;
      for (let index = 0; index < len; index++) {
        if (tree[index][findKey] === key) {
          console.log(tree[index][findKey], key, "匹配成功");
          return findParent ? parenNode : tree[index];
        };
        if (tree[index]?.children?.length) {
          const result = this.findNodeIndex(tree[index]?.children, key, findKey, findParent, tree[index]);
          if (result) return result;
        }
      }
    },
    sideAddUid(array) {
      return array.map(item => {
        item.index = v4();
        if (item?.children?.length) {
          item.children = this.sideAddUid(item?.children);
        }
        return item;
      });
    },
    getFinancial(id) {
      financial({ cid: String(id) }).then(res => {
        if ((res.code == 200 && !res.data) || !res.data?.totalAssets) {
          // 禁用财务信息
          this.$set(this.findNodeIndex(this.sideRoute, "business"), "disabled", true);
          this.$set(this.findNodeIndex(this.sideRoute, "financial"), "disabled", true);
          this.defaultRoute = JSON.parse(JSON.stringify(this.sideRoute));
        }
      });
    },
    // 菜单关联服务端数据
    createSideBarWithServerData(value) {

      this.sideRoute = JSON.parse(JSON.stringify(this.defaultRoute));

      // server返回菜单统计数据
      const _sideBarData = JSON.parse(JSON.stringify(value));

      // {basic,behavior,business,combineMember,credit,evaluation,global,performance,personnel,qualification}
      /**
       * @type {Map<string,string>}
      */
      const _tempMap = detailSideBar;

      _tempMap.forEach((value, key, mapOrigin) => {
        // 找到对应的数据源
        const data = this.findDataOrigin(_sideBarData, key);
        const sideBarOption = this.findSideBarOption(this.sideRoute, value);
        // 禁用菜单 小于一 或 server返回的对象数据不存在
        if (data < 1 || !data) {
          if (sideBarOption) {
            sideBarOption instanceof Array ? sideBarOption.forEach(item => this.$set(item, "disabled", true)) : this.$set(sideBarOption, "disabled", true);
          }
        }
      });

      this.defaultRoute = JSON.parse(JSON.stringify(this.sideRoute));
    },

    findDataOrigin(originData, key) {
      if (originData && Object.keys(originData).length) {
        for (const dataKey in originData) {
          if (originData.hasOwnProperty(dataKey)) {
            if (dataKey == key) {
              return originData[dataKey];
            }
            // 是对象 递归处理
            if (Object.prototype.toString.call(originData[dataKey]) == "[object Object]") {
              const result = this.findDataOrigin(originData[dataKey], key);
              if (result || result == "0") return result;
            }
          }
        }
      }
    },
    // 找菜单对象
    findSideBarOption(sideBarData, key) {
      for (const iterator of sideBarData) {
        if (iterator.pathName === key) {
          return iterator;
        }
        // map的值是数组的情况
        if (key instanceof Array) {
          const _tempArray = [];
          key.forEach(item => {
            // 找到数组中的每一个菜单对象
            const itemNode = this.findSideBarOption(sideBarData, item);
            if (itemNode) _tempArray.push(itemNode);
          });
          if (_tempArray.length == key.length) return _tempArray;
        }
        // 有children 递归处理
        if (iterator?.children?.length) {
          const _result = this.findSideBarOption(iterator?.children, key);
          if (_result) return _result;
        }
      }
    },
    handleOpen(key, keyPath) {

    },
    handleItem(item) {
      console.log(item)
      let obj = item;
      for (var i in this.sideRoute1) {
        if (this.sideRoute1[i].children) {
          for (var j in this.sideRoute1[i].children) {
            if (item.title == this.sideRoute1[i].children[j].title) {
              obj.pathName = this.sideRoute1[i].children[j].pathName;
            }
          }
        } else {
          if (item.title == this.sideRoute1[i].title) {
            obj.pathName = this.sideRoute1[i].pathName;
          }
        }
      }
      this.$emit("currentPath", obj);
    },
    async handleSearch(flag) {
      try {
        // 手动输入时 flag 为true
        if ((this.searchText && !flag) || (!this.searchText && flag)) {
          // 找到唯一标识
          let side = this.findNodeIndex(this.defaultRoute, this.searchText, "title");
          // 需要打开菜单的唯一标识
          let openIndex = null;
          // 右侧打开的菜单对应对象
          let openSide = null;
          // 菜单高亮命中
          let hightLightSide = null;
          if (side) {
            // 判断是否是子级菜单 有children 直接使用当前层级 没有找父级
            if (side?.children?.length) {
              openIndex = side.index;
              openSide = side?.children[0];
              // 打开的菜单有children 表示目录 不高亮显示
              hightLightSide = openSide?.children?.length ? null : side?.children[0]?.index;
              this.sideRoute = [JSON.parse(JSON.stringify(side))];
            } else {
              // 找父节点
              const parent = this.findNodeIndex(this.defaultRoute, side.pathName, "pathName", true);
              openIndex = parent.index;
              hightLightSide = side.index;
              openSide = side;
              this.sideRoute = [JSON.parse(JSON.stringify(parent))];
            }
            await this.$nextTick();
            this.$refs.sideMenu.open(openIndex);
            // 打开查找到的菜单 禁用则不打开
            openSide?.disabled ? null : (hightLightSide ? (this.searchIndex = hightLightSide) : null) && this.handleItem(openSide);
          } else {
            this.sideRoute = JSON.parse(JSON.stringify(this.defaultRoute));
            this.searchText = "";
          }
        }
      } catch (err) {
        console.log(err);
      }
    },
    isCustomerId(name) {
      if (this.customer.indexOf(name) != -1) {
        if (this.customerId && this.isCustomer) {
          return true;
        }
        return false;
      }
      return true;
    },
    isCompanyId(name) {
      if (this.companys.indexOf(name) != -1) {
        if (this.isCompany) {
          return true;
        }
        return false;
      }
      return true;
    }
  }
}
</script>

<style lang="scss" scoped>
#app {
  .sides-container {
    width: 160px;
    min-height: calc(100vh - 170px);
    padding-bottom: 20px;
    background: #ffffff;
    border-radius: 4px;

    .search-bar-container {
      padding: 9px 8px;
      box-sizing: border-box;
      ::v-deep .side-input {
        width: 100%;
        border: 0;
        .el-input__inner {
          height: 32px;
          background: #f3f3f4;
          border-radius: 20px;
          border: 0;
          &::placeholder {
            color: #3d3d3d;
          }
        }
        .el-icon-search {
          line-height: 34px;
          color: #0081ff;
          cursor: pointer;
        }
      }
    }

    .detail-menu {
      margin-top: 9px;
      border-right: 0;
      max-height: calc(100% - 50px);
      overflow: auto;
      ::v-deep .el-menu-item,
      ::v-deep .el-submenu__title {
        height: 30px;
        line-height: 30px;
        font-size: 14px;
        color: #232323;
        padding: 0 0 0 16px !important;
        text-align: initial !important;
        &:hover,
        &:focus,
        &.is-active {
          color: #0081ff !important;
          background: linear-gradient(
            91deg,
            rgba(0, 129, 255, 0.1) 0%,
            rgba(0, 129, 255, 0) 100%
          );
        }
        .el-submenu__icon-arrow {
          color: #232323;
          right: 48px;
          margin-top: -5px;
        }
      }
      /* 禁用时 不需要选中文字颜色 */
      ::v-deep .el-menu-item {
        &.is-disabled {
          &:focus {
            color: unset !important;
          }
        }
      }
      .is-disabled:hover {
        color: rgba(35, 35, 35, 0.8) !important;
        &:before {
          color: rgba(35, 35, 35, 0.8) !important;
        }
      }
      ::v-deep .el-submenu .el-menu-item {
        font-size: 12px;
        color: rgba(35, 35, 35, 0.8);
        padding: 0 0 0 27px !important;
        min-width: 144px !important;
        position: relative;
        &:before {
          content: "";
          position: absolute;
          top: 14px;
          left: 21px;
          width: 2px;
          height: 2px;
          background: #0081ff;
          border-radius: 50%;
        }
      }

      ::v-deep .top-level-menu {
        // 重置展开图标位置
        .el-submenu__icon-arrow {
          position: static;
          margin-top: 0px;
        }
        // 顶级菜单标题
        & > .el-submenu__title {
          font-weight: bold;
          color: #232323;
          font-size: 14px;
          height: 40px;
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 9px 8px !important;
          box-sizing: border-box;

          .top-level-menu-title {
            display: flex;
            align-items: center;

            & > span {
              margin-left: 4px;
            }
          }
        }

        // 二级菜单
        & > .el-menu {
          .second-level-menu-no-children,
          .second-level-menu-has-children .el-submenu__title {
            font-size: 14px;
            height: 36px;
            color: #232323;
            font-weight: 400;
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 9px 8px 9px 32px !important;
            box-sizing: border-box;

            &::before {
              display: none;
            }
          }

          .second-level-menu-has-children {
            // 三级菜单
            & > .el-menu {
              & > .el-menu-item {
                font-size: 12px;
                height: 32px;
                color: rgba(35, 35, 35, 0.8);
                font-weight: 400;
                display: flex;
                align-items: center;
                padding: 9px 8px 9px 32px !important;
                box-sizing: border-box;

                & > span {
                  margin-left: 8px;
                }

                &::before {
                  position: static;
                }
              }
            }
          }
        }
      }
    }
  }
}
</style>
