<template>
  <div class="render-container">
    <div class="home-container">
      <div class="home-top-container flex align-items-c justify-content-b">
        <div class="left-container">
          <span class="title">你好，{{ userInfo.realName }}</span>
          <div class="subtitle">欢迎使用{{ title }}</div>
          <div class="role-info">
            当前角色：{{ userInfo.roleNames[0] || '未指定' }}
          </div>
        </div>
        <div class="right-container">
          <div class="icon-box">
            <i class="el-icon-user-solid"></i>
          </div>
          <!--          <div class="icon-box">-->
          <!--            <i class="el-icon-bell"></i>-->
          <!--          </div>-->
        </div>
      </div>

      <div class="home-center-container">
        <div class="card-container">
          <div class="card-item" @click="jumpUrl('knowledge/list')">
            <span class="card-title">知识库</span>
            <div class="card-content">知识库管理列表</div>
          </div>
          <div class="card-item" @click="jumpUrl('/intelligentAgent/list')">
            <span class="card-title">智能体</span>
            <div class="card-content">智能体管理列表</div>
          </div>
          <div class="card-item" @click="openTag">
            <span class="card-title">操作手册</span>
            <div class="card-content">智能管理平台使用手册</div>
          </div>
        </div>
      </div>
      <div class="home-bottom-container">
        <div class="latest-section flex align-items-c justify-content-b">
          <div class="latest-knowledge">
            <span class="section-title">最近使用知识库</span>
            <div v-if="dataset.name" style="height: 100%;">
              <div
                class="section-content"
                @click="jumpUrl(`/knowledge/detail?datasetId=${dataset.id}`)"
              >
                <div class="knowledge-item flex align-items-c">
                  <div class="knowledge-image">
                    <img :src="dataset.image" alt="Knowledge Image" />
                  </div>
                  <div class="knowledge-details">
                    <div class="knowledge-title">{{ dataset.name }}</div>
                    <div class="knowledge-description mt5">
                      {{ dataset.description }}
                    </div>
                    <div class="knowledge-created-by mt5">
                      创建人：{{ dataset.createdUser }}
                    </div>
                  </div>
                </div>
              </div>

              <lineEcharts
                v-if="dataset.name"
                :key="MatchId"
                :options="options"
                style="width: 100%;height: calc(100% - 120px);background: unset"
              ></lineEcharts>
            </div>
            <div
              style="height: 100%"
              class="flex align-items-c justify-content-c"
              v-else
            >
              <el-empty></el-empty>
            </div>
          </div>
          <div class="latest-agent">
            <span class="section-title">最近使用智能体</span>
            <div v-if="agent.appName" style="height: 100%;">
              <div class="section-content" @click="jumpAgent(agent)">
                <div class="knowledge-item flex align-items-c">
                  <div class="knowledge-image">
                    <div
                      class="folder"
                      :style="
                        `background:${
                          agent.imageType === 'emoji'
                            ? agent.backgroundColor
                            : agent.imageType === 'image'
                            ? '#fff'
                            : ''
                        }`
                      "
                    >
                      <div v-if="agent.imageType === 'image'">
                        <img
                          :src="agent.image"
                          alt=""
                          style="width: 100%;height: 100%"
                        />
                      </div>
                      <div v-else>
                        {{
                          agent.image
                            ? agent.image
                            : agent.appName
                            ? agent.appName[0]
                            : ''
                        }}
                      </div>

                      <!--listItem.name.获取字符串第一个-->
                    </div>
                  </div>
                  <div class="knowledge-details">
                    <div class="knowledge-title">{{ agent.appName }}</div>
                    <div class="knowledge-description mt5">
                      {{ agent.description }}
                    </div>
                    <div class="knowledge-created-by mt5">
                      创建人：{{ agent.createdUser }}
                    </div>
                  </div>
                </div>
              </div>
              <lineEcharts
                :key="MatchId"
                :options="agentOptions"
                style="width: 100%;height: calc(100% - 120px);background: unset"
              ></lineEcharts>
            </div>
            <div
              style="height: 100%"
              class="flex align-items-c justify-content-c"
              v-else
            >
              <el-empty></el-empty>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex'
import { title } from '@/assets/js/utils/settings'
import { docManageDataset } from '@/api/generatedApi'
import lineEcharts from '@/views/intelligent-agent/children/Logs&overview/components/echarts.vue'
import {
  agentDetail,
  agentList,
  getAccessToken
} from '@/api/intelligent-agent/list'

export default {
  name: 'Home',
  data() {
    return {
      MatchId: 0,
      options: {
        title: {
          text: ''
        }
      },
      userInfo: {},
      title,
      dataset: {},
      datasetList: [],
      agent: {},
      agentList: [],
      agentOptions: {
        title: {
          text: ''
        }
      }
    }
  },
  components: {
    lineEcharts
  },
  watch: {
    'sidebar.opened': function(val) {
      setTimeout(() => {
        if (this.datasetList.length > 0) {
          this.getEcharts()
        } else {
          this.getKnowledgeList()
        }
      }, 500)
    }
  },
  created() {},
  mounted() {
    let userInfo = sessionStorage.getItem('userInfo')
    if (userInfo) {
      this.userInfo = JSON.parse(userInfo)
    }
    this.getKnowledgeList()
    // this.getAgentList()
    window.addEventListener('resize', () => {
      this.options.title.text = null
      this.agentOptions.title.text = null
      setTimeout(() => {
        if (this.datasetList.length > 0) {
          this.getEcharts()
        } else {
          this.getKnowledgeList()
        }
      }, 300)
    })
  },
  methods: {
    setMatchMedia() {
      //   生成随机数
      return Math.floor(Math.random() * 100)
    },

    getEcharts() {
      // prettier-ignore
      let dataAxis = [];
      let agentDataAxis = []
      let list = JSON.parse(JSON.stringify(this.datasetList)).splice(0, 20)
      list.map(item => {
        dataAxis.push(item.name)
      })
      let agentList = JSON.parse(JSON.stringify(this.agentList)).splice(0, 10)
      agentList.map(item => {
        agentDataAxis.push(item.appName)
      })

      // prettier-ignore
      let data = [220, 182, 191, 234, 290, 330, 310, 123, 442, 321, 90, 149, 210, 122, 133, 334, 198, 123, 125, 220];
      let yMax = 500
      let dataShadow = []
      for (let i = 0; i < data.length; i++) {
        dataShadow.push(yMax)
      }
      this.options = {
        title: {
          text: '知识库使用情况',
          subtext: '拖动或者滑动滚轮可以放大查看',
          textStyle: {
            fontSize: 17,
            fontWeight: 600,
            color: '#000',
            marginLeft: '10px'
          }
        },
        xAxis: {
          data: dataAxis
          // axisLabel: {
          //   inside: true,
          //   color: '#fff'
          // },
          // axisTick: {
          //   show: false
          // },
          // axisLine: {
          //   show: false
          // },
          // z: 10
        },
        yAxis: {
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            color: '#999'
          }
        },
        dataZoom: [
          {
            type: 'inside'
          }
        ],
        series: [
          {
            type: 'bar',
            showBackground: true,
            itemStyle: {
              color: new this.$echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#83bff6' },
                { offset: 0.5, color: '#188df0' },
                { offset: 1, color: '#188df0' }
              ])
            },
            emphasis: {
              itemStyle: {
                color: new this.$echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#2378f7' },
                  { offset: 0.7, color: '#2378f7' },
                  { offset: 1, color: '#83bff6' }
                ])
              }
            },
            data: data
          }
        ]
      }
      this.agentOptions = {
        title: {
          text: '智能体使用情况',
          subtext: '拖动或者滑动滚轮可以放大查看',
          textStyle: {
            fontSize: 17,
            fontWeight: 600,
            color: '#000',
            marginLeft: '10px'
          }
        },
        xAxis: {
          data: agentDataAxis
          // axisLabel: {
          //   inside: true,
          //   color: '#fff'
          // },
          // axisTick: {
          //   show: false
          // },
          // axisLine: {
          //   show: false
          // },
          // z: 10
        },
        yAxis: {
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            color: '#999'
          }
        },
        dataZoom: [
          {
            type: 'inside'
          }
        ],
        series: [
          {
            type: 'bar',
            showBackground: true,
            itemStyle: {
              color: new this.$echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#83bff6' },
                { offset: 0.5, color: '#188df0' },
                { offset: 1, color: '#188df0' }
              ])
            },
            emphasis: {
              itemStyle: {
                color: new this.$echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#2378f7' },
                  { offset: 0.7, color: '#2378f7' },
                  { offset: 1, color: '#83bff6' }
                ])
              }
            },
            data: data
          }
        ]
      }

      this.MatchId = this.setMatchMedia()
    },

    async jumpAgent(item) {
      const { content } = await agentDetail(item.id)
      const thirdContent = await getAccessToken()
      let agent = content.content
      //  刷新的 token 和 一个访问权限的token
      const { refreshToken, accessToken } = thirdContent.content.content
      // 传递新的token
      localStorage.setItem('refresh_token', refreshToken)
      localStorage.setItem('console_token', accessToken)
      // 做成页面跳转
      this.$router.push({
        path: `/agent/${agent.thirdAppId}/workflow`,
        query: {
          name: agent.appName,
          id: agent.id
        }
      })
    },

    async getKnowledgeList() {
      let { content } = await docManageDataset({ nameLike: this.nameLike })
      if (content.content && content.content.length > 0) {
        this.dataset = content.content[0]
        this.datasetList = content.content
      }

      await this.getAgentList()

      this.getEcharts()

      // docManageDataset({ nameLike: this.nameLike }).then(res => {
      //   if (res) {
      //     this.dataset = res.content.content[0]
      //     this.datasetList = res.content.content
      //     this.getAgentList()
      //   }
      // })
    },
    async getAgentList() {
      const { content } = await agentList({
        page: 1,
        pageSize: 1,
        appNameLike: '',
        appType: ''
      })
      this.agent = content.content[0]
      this.agentList = content.content
    },

    success() {},
    jumpUrl(url) {
      this.$router.push({
        path: url
      })
    },
    openTag() {
      window.open(process.env.VUE_APP_DOCS)
    }
  },
  computed: {
    ...mapGetters(['sidebar', 'sidebarList'])
  }
}
</script>

<style lang="scss" scoped>
@import '@/assets/sass/renderSass/theme.scss';
.render-container {
  background: #f0f4fa;
  padding: 0;
  margin: 10px;
  transition: all 0.5s;

  height: calc(100vh - 20px);

  & .home-container {
    border-radius: 10px;
    height: 100%;
    overflow-y: auto;
    overflow-x: hidden;
    .home-top-container {
      margin-bottom: 10px;
      padding: 20px;
      //background: linear-gradient(135deg, #6a11cb, #2575fc);

      background: #fff;
      border-radius: 10px;
      box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
      overflow: hidden;
      .left-container {
        width: 50%;
        color: #000;

        .title {
          font-size: 18px;
          font-weight: bold;
          margin-bottom: 10px;
          background: linear-gradient(135deg, #6a11cb, #2575fc);
          -webkit-background-clip: text; /* 关键：将背景裁剪为文字 */
          background-clip: text; /* 标准属性 */
          color: transparent; /* 文字颜色透明，显示背景渐变 */
        }

        .subtitle {
          font-size: 13px;
          opacity: 0.8;
          margin-bottom: 5px;
          margin-top: 10px;
        }

        .role-info {
          font-size: 13px;
          opacity: 0.7;
        }
      }

      .right-container {
        display: flex;
        gap: 10px;

        .icon-box {
          width: 40px;
          height: 40px;
          //background: linear-gradient(135deg, #6a11cb, #2575fc);
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          color: #fff;
          font-size: 20px;
          cursor: pointer;

          &:hover {
            //background: linear-gradient(135deg, #2575fc, #6a11cb);
          }
        }
      }
    }

    .home-center-container {
      .card-container {
        display: flex;
        gap: 10px;

        .card-item {
          cursor: pointer;
          flex: 1;
          padding: 40px 20px;
          background-color: #fff;
          border-radius: 10px;
          box-shadow: 0 4px 8px rgba(0, 0, 0, 0.05);
          transition: all 0.3s ease-in-out;
          //&:hover {
          //  transform: translateY(-5px);
          //  box-shadow: 0 6px 10px rgba(0, 0, 0, 0.1);
          //}

          .card-title {
            font-size: 18px;
            font-weight: bold;

            background: linear-gradient(135deg, #6a11cb, #2575fc);
            -webkit-background-clip: text; /* 关键：将背景裁剪为文字 */
            background-clip: text; /* 标准属性 */
            color: transparent; /* 文字颜色透明，显示背景渐变 */
          }

          .card-content {
            font-size: 14px;
            color: #666;
            margin-top: 20px;
          }
        }
      }
    }

    .home-bottom-container {
      //box-shadow: 0 4px 8px rgba(0, 0, 0, 0.05);
      margin-top: 10px;
      border-radius: 8px;
      height: calc(100vh - 290px);
      //background-color: #fff;
      .latest-section {
        display: flex;
        justify-content: space-between;
        margin: 10px 0;
        height: 100%;

        .latest-knowledge,
        .latest-agent {
          height: 100%;
          background: #fff;
          //box-shadow: 0 4px 8px rgba(0, 0, 0, 0.05);
          flex: 1;
          border-radius: 8px;
          padding: 15px;

          .section-title {
            font-size: 17px;
            font-weight: bold;
            margin-left: 2px;

            //background: linear-gradient(135deg, #6a11cb, #2575fc);
            //-webkit-background-clip: text; /* 关键：将背景裁剪为文字 */
            //background-clip: text; /* 标准属性 */
            //color: transparent; /* 文字颜色透明，显示背景渐变 */
          }

          .section-content {
            margin-top: 10px;
            cursor: pointer;
            .knowledge-item {
              display: flex;
              align-items: center;

              .knowledge-image {
                width: 60px;
                height: 60px;
                overflow: hidden;
                border-radius: 8px;
                margin-right: 15px;

                img {
                  width: 100%;
                  height: 100%;
                  object-fit: cover;
                }
                & .folder {
                  width: 60px;
                  height: 60px;
                  line-height: 60px;
                  background: linear-gradient(135deg, #6a11cb, #2575fc);
                  border-radius: 8px;
                  font-size: 40px;
                  overflow: hidden;
                  font-weight: 600;
                  color: #fff;
                  text-align: center;
                }
              }

              .knowledge-details {
                flex: 1;

                .knowledge-title {
                  font-size: 16px;
                  font-weight: 600;
                  margin-bottom: 5px;
                }

                .knowledge-description {
                  font-size: 14px;
                  color: #666;
                }

                .knowledge-created-by {
                  font-size: 12px;
                  color: #999;
                }
              }
            }
          }
        }

        .latest-agent {
          margin-left: 10px;
        }
      }
    }
  }
}
</style>
