<script>
import {
  agentDelete,
  agentDetail,
  agentList,
  getAccessToken
} from '@/api/intelligent-agent/list'
import Info from '@/views/intelligent-agent/components/info'
import agent from '@/views/agent'
import { agentType } from '@/assets/js/utils/utilOptions'
export default {
  name: 'intelligent-agent',
  components: {
    Info,
    agent
  },
  data() {
    return {
      agentConfig: {
        title: '',
        component: 'agent',
        visible: false,
        agent: {
          id: '',
          thirdAppId: '',
          visibleRange: 0
        }
      },
      searchOption: {
        nameLike: '',
        handleSearch: async () => {
          this.page = 1
          this.list = []
          await this.fetchAgentList({ nameLike: this.searchOption.nameLike })
        }
      },
      /**
       * @type {{name: string, url: string, id: string}[]}
       */
      list: [],
      page: 1,
      pageSize: 99999999,
      total: -1,
      dialog: {
        visible: false,
        title: '',
        agent: {
          id: ''
        },
        component: 'info',
        type: 'edit'
      }
    }
  },
  provide() {
    return {
      dialog: this.dialog,
      fetchAgentList: this.fetchAgentList,
      resetList: this.resetList
    }
  },
  methods: {
    findAppTypeLabel(item) {
      return agentType.find(it => it.value === item).label
    },

    resetList() {
      this.list = []
      this.page = 1
    },
    load() {
      if (this.total === this.list.length) {
        return false
      }
      this.page = 1
      this.fetchAgentList({
        page: this.page,
        pageSize: this.pageSize
      })
    },
    /**
     * 获取所有的智能体列表
     */
    async fetchAgentList(params = {}) {
      const { content } = await agentList({
        page: this.page,
        pageSize: this.pageSize,
        appNameLike: params.nameLike ? params.nameLike : '',
        appType: params.appType ? params.appType : ''
      })
      this.list.push(...content.content)
      this.total = content.content.total
    },

    jumpToLogs(id) {
      this.$router.push({
        path: `/intelligentAgent/logs-overview`,
        query: {
          appId: id
        }
      })
    },

    /**
     * 编辑智能体
     */
    async handleEditAgent(id) {
      const { content } = await agentDetail(id)
      if (!content.content.backgroundColor) {
        content.content.backgroundColor = '#d1e9ff'
      }
      if (!content.content.visibleRange) {
        content.content.visibleRange = 0
      }
      this.$set(this.dialog, 'agent', content.content)
      this.dialog.type = 'edit'
      this.dialog.title = '编辑智能体'
      // 获取数据之后打开内容详情
      this.dialog.visible = true
    },
    /**
     * 删除智能体
     */
    handleDeleteAgent(id) {
      // 删除之后重新获取内容
      this.$messageBox(
        () => {
          agentDelete([id]).then(res => {
            this.page = 1
            this.list = []
            this.fetchAgentList()
          })
        },
        '是否删除当前智能体',
        'warning',
        '提示'
      )
    },
    /**
     * 创建智能体
     */
    async createdIntelligentAgent() {
      this.dialog.type = 'add'
      // 重置状态，防止其他状态影响导致表单内容异常
      this.dialog.agent = {
        appName: '',
        appType: '',
        description: '',
        imageType: '',
        image: '',
        backgroundColor: '#d1e9ff',
        visibleRange: 0,
        userIds: []
      }
      this.dialog.title = '创建智能体'
      this.dialog.visible = true
    },
    async handleClickAgent(item) {
      const { content } = await agentDetail(item.id)
      const thirdContent = await getAccessToken()
      let agent = content.content
      this.agentConfig.title = agent.appName + ' -  智能体详情'
      this.agentConfig.agent = agent

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

    //   创建智能体弹窗确认
    infoConfirm() {
      this.$refs.infoDialog.validateForm()
    }
  },
  created() {
    this.fetchAgentList()
  }
}
</script>

<template>
  <div id="index-container" class="container index-container">
    <el-row>
      <el-col :span="8">
        <el-input
          placeholder="输入智能体名称"
          clearable
          v-model="searchOption.nameLike"
          size="medium"
          class="underBorder"
          @keydown.enter.native="searchOption.handleSearch"
        >
          <template slot="prepend">
            <el-button slot="append" icon="el-icon-search"></el-button>
          </template>
        </el-input>
      </el-col>
      <el-col :span="16" class="text-right">
        <el-button
          class="render-button line-button pv8 ph10"
          icon="el-icon-plus"
          @click="createdIntelligentAgent()"
          >创建智能体
        </el-button>
      </el-col>
    </el-row>

    <div slot="header" class="clearfix mt30 flex mb20">
      <div>
        <h3>智能体列表</h3>
      </div>
    </div>
    <!--    <ul class="infinite-list"  style="overflow:auto">-->
    <!--      <li v-for="i in count" class="infinite-list-item">{{ i }}</li>-->
    <!--    </ul>-->

    <div class="card-body">
      <div class="ledge-list ">
        <el-card
          v-for="(listItem, index) in list"
          class="item datasetList"
          shadow="hover"
          :key="index"
          @click.native.stop="handleClickAgent(listItem)"
        >
          <div class="dataset-header">
            <div class="folder-content">
              <div
                class="folder"
                :style="
                  `background:${
                    listItem.imageType === 'emoji'
                      ? listItem.backgroundColor
                      : listItem.imageType === 'image'
                      ? '#fff'
                      : ''
                  }`
                "
              >
                <div
                  v-if="listItem.imageType === 'image'"
                  style="width: 100%;height: 100%"
                >
                  <img
                    :src="listItem.image"
                    alt=""
                    style="width: 100%;height: 100%"
                  />
                </div>
                <div v-else>
                  {{ listItem.image ? listItem.image : listItem.appName[0] }}
                </div>

                <!--listItem.name.获取字符串第一个-->
              </div>
              <div>
                <svg-icon
                  :icon-class="listItem.appType"
                  class-name="appType"
                  :style="{
                    background: listItem.backgroundColor ? '#fff' : '#fff'
                  }"
                ></svg-icon>
              </div>
            </div>
            <div class="dataset-body" style="flex:1">
              <h4 class="dataset-title">{{ listItem.appName }}</h4>
              <div class="mt10">
                <span class="theme-primary-desc-text-drank fs12 mt20 tag">
                  {{ findAppTypeLabel(listItem.appType) }}
                </span>

                <span
                  class="tag ml10 theme-primary-desc-text-drank fs12 mt10 fw500"
                >
                  User：{{ listItem.createdUser }}
                </span>
              </div>
            </div>
          </div>
          <div class="mh20 mv15 flex justify-content-b">
            <p
              class="dataset-desc theme-primary-desc-text-drank fs13"
              style="line-height:25px;height:20px"
            >
              {{ listItem.description }}
            </p>
          </div>
          <div
            class="opacity-button flex align-items-c mh20 mb10"
            style="justify-content: flex-end"
          >
            <el-button
              class="default "
              size="medium"
              icon="el-icon-delete"
              @click.stop="handleDeleteAgent(listItem.id)"
              >删除
            </el-button>
            <el-button
              class="line-button"
              size="medium"
              icon="el-icon-edit"
              @click.stop="handleEditAgent(listItem.id)"
              type="primary"
              >修改
            </el-button>
            <el-button
              class="line-button"
              size="medium"
              icon="el-icon-more"
              @click.stop="jumpToLogs(listItem.id)"
              type="primary"
              >更多
            </el-button>
          </div>
        </el-card>
      </div>
    </div>

    <!-- dialog 内容。 现在主要是编辑 -->
    <r-dialog
      :visible.sync="dialog.visible"
      :title="dialog.title"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @confirm="infoConfirm"
      width="50vw"
    >
      <component :is="dialog.component" ref="infoDialog" />
    </r-dialog>

    <!--    <el-drawer-->
    <!--      :visible.sync="agentConfig.visible"-->
    <!--      :title="agentConfig.title"-->
    <!--      size="90%"-->
    <!--      :wrapperClosable="false"-->
    <!--    >-->
    <!--      <component-->
    <!--        :is="agentConfig.component"-->
    <!--        :key="agentConfig.agent.thirdAppId"-->
    <!--        :thirdAppId="agentConfig.agent.thirdAppId"-->
    <!--      />-->
    <!--    </el-drawer>-->
  </div>
</template>

<style scoped lang="scss">
@import '@/assets/sass/renderSass/theme.scss';
#index-container {
  background-image: url('../../assets/images/backimage.png');
  background-size: 600px 300px;
  background-position-x: right;
  background-position-y: top;
  background-repeat: no-repeat;
}

.ledge-list {
  display: flex;
  flex-wrap: wrap;

  & .item {
    border-radius: 8px;
    width: calc(33.33% - 10px); // 每个项目占 33.33%，并预留间隙
    margin-bottom: 10px;
    margin-left: 0; // 移除左右内边距
    margin-right: 15px;

    /deep/ .el-card__body {
      padding: 0;

      & .item-body {
        padding: 0 20px;
        display: flex;
        height: 119px;
        margin-top: 20px;
      }

      & .item-bottom {
        display: flex;
        justify-content: space-between;
        background: #f7f9fa;
        border-top: 1px solid #eff0f1;
      }
    }
  }

  & .item:nth-child(3n) {
    margin-right: 0;
  }

  & .dashed {
    border: 1px dashed #dedede;
    cursor: pointer;
    text-align: center;
    line-height: 200px;
    color: #6666;

    &:hover {
      color: #409eff;
      border: 1px dashed #409eff;
    }
  }

  & .folder-content {
    text-align: center;
    border-radius: 8px;
    position: relative;
    & .folder {
      width: 50px;
      height: 50px;
      line-height: 50px;
      background: rgb(209, 233, 255);
      border-radius: 8px;
      font-size: 30px;
      overflow: hidden;
      font-weight: 600;
      color: #fff;
    }
    & .appType {
      position: absolute;
      right: 0;
      bottom: -5px;
      z-index: 1;
      width: 20px;
      height: 20px;
      padding: 2px;
      border-radius: 5px;
      color: $--color-primary;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    }
  }
}

.tag {
  padding: 4px 8px;
  background: #f0f4fa;
  border-radius: 5px;
}

.opacity-button {
  opacity: 0;
}

.datasetList {
  position: relative;
  transition: all 0.3s ease;
  overflow: hidden;
  cursor: pointer;

  &:hover {
    background: linear-gradient(211deg, #eef4fd 0%, #ffffff 100%);
    box-shadow: 0px 4px 7px 2px #dbe3f2;
    border-radius: 7px;
    border: 1px solid #635cff;

    .opacity-button {
      display: flex;
      justify-content: space-between;
      transition: all 0.5s ease;
      opacity: 1;

      button {
        max-height: 30px;
      }
    }
  }

  /deep/ .el-card__body {
    padding: 0;
    height: 100%;
    display: flex;
    flex-direction: column;
  }

  .dataset-header {
    padding: 20px 20px 0;
    display: flex;
    justify-content: space-between;
    align-items: flex-start;

    .folder-content {
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .dataset-type {
      font-size: 12px;
      border-radius: 4px;
    }
  }

  .dataset-body {
    flex: 1;
    max-width: 90%;
    padding: 0 10px;

    .dataset-title {
      font-family: PingFangSC, PingFang SC;
      font-weight: 600;
      font-size: 16px;
      color: #000000;
      line-height: 22px;
      text-align: left;
      font-style: normal;

      margin: 0 0 5px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      max-width: 100%;
    }
  }
  .dataset-desc {
    font-family: PingFangSC, PingFang SC;
    font-weight: 400;
    font-size: 13px;
    color: #666666;
    line-height: 18px;
    text-align: left;
    font-style: normal;

    height: 35px;
    margin: 0;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 100%;
  }
  .dataset-footer {
    margin-top: auto;
    display: flex;
    border-top: 1px solid #f0f2f5;
    background: linear-gradient(to bottom, #fafbfc, #f5f7fa);
  }
}
.container {
}
</style>
