<script>
import { DIFY_URL } from '@/config/base-url'
import { agentAdd, agentDetail, agentEdit } from '@/api/intelligent-agent/list'
export default {
  name: 'workflow',
  props: {
    thirdAppId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      agentDetail: {},

      resetName: '',
      editName: '',
      editValue: '',
      isLoading: true,
      worker: {
        instance: void 0
      },
      messageChannel: {
        instance: void 0
      },
      agent: {
        // 默认不展示 header 和 sidebar
        params: {
          sidebar: '0',
          header: '0',
          publish: '0'
        },
        isVisible: false,
        // agent 的 workflow 地址格式 http://localhost:3000/agent/app/235427ea-803b-482b-bdff-dd717801ca76/workflow
        //  app 是展示所有的内容
        src: `${DIFY_URL}/app/235427ea-803b-482b-bdff-dd717801ca76/workflow`
      }
    }
  },
  computed: {
    params() {
      const _params = []
      Object.keys(this.agent.params).forEach(key => {
        _params.push(`${key}=${this.agent.params[key]}`)
      })
      return _params.join('&')
    }
  },
  // http://192.168.3.229:3000/apps
  created() {
    // 检测是否存在 workflow id ， 如果不存在则不展示内容
    const { header, sidebar, publish } = this.$route.query
    const { thirdAppId } = this.$route.params
    if (thirdAppId) {
      this.agent.src = `${DIFY_URL}/app/${thirdAppId}/workflow?${this.params}`
      this.agent.isVisible = true
    }

    // 获取 header 和 sidebar 的内容, 重置参数状态
    this.agent.params.header = header || '0'
    this.agent.params.sidebar = sidebar || '0'
    this.agent.params.publish = publish || '0'

    if (this.thirdAppId) {
      this.agent.src = `${DIFY_URL}/app/${this.thirdAppId}/workflow?${
        this.params
      }`
      this.agent.isVisible = true
    }

    //   启用 web worker 和 dify 进行通信
    this.worker.instance = new Worker('/js/message-channel.js')
    this.messageChannel.instance = new MessageChannel()

    // 递交 messageChannel port2的所有权
    this.worker.instance.postMessage('init-worker', [
      this.messageChannel.instance.port2
    ])
  },
  destroyed() {
    //  组件销毁时清除 web worker 和 messageChannel
    this.worker.instance.terminate()
    this.worker.instance = void 0
    this.messageChannel.instance.port1.close()
    this.messageChannel.instance = void 0
  },
  watch: {
    '$route.query': {
      handler() {
        // 获取 header 和 sidebar 的内容, 重置参数状态
        const { thirdAppId } = this.$route.params
        const { header, sidebar, publish } = this.$route.query
        this.agent.params.header = header || '0'
        this.agent.params.sidebar = sidebar || '0'
        this.agent.params.publish = publish || '0'

        // 当路由参数 id 变化时，更新 dify 的 src
        if (thirdAppId) {
          console.log(`current params:`, this.agent.params)

          this.agent.src = `${DIFY_URL}/app/${thirdAppId}/workflow?${
            this.params
          }`
          this.agent.isVisible = true
        } else {
          this.agent.isVisible = false
        }
      },
      deep: true
    }
  },
  methods: {
    handleAgentLoad() {
      // 把 messageChannel port1 的所有权传递给 iframe
      this.$refs.agent.contentWindow.postMessage('init-iframe', '*', [
        this.messageChannel.instance.port1
      ])
      // 隐藏 loading
      this.isLoading = false
    },

    async getQuery() {
      const { content } = await agentDetail(this.$route.query.id)
      this.agentDetail = content.content
      this.editValue = this.agentDetail.appName
      this.resetName = this.agentDetail.appName
    },
    saveUS() {
      // 更新表单之后重新获取列表，然后退出 dialog
      agentEdit({ ...this.agentDetail, appName: this.editValue }).then(res => {
        if (res) {
          this.$message.success('修改成功')
          this.editName = false
          this.resetName = this.editValue
        }
      })
    }
  },
  mounted() {
    this.getQuery()
  }
}
</script>

<template>
  <div class="render-container">
    <div class="flex align-items-c mb10" style="gap: 20px">
      <BackButton></BackButton>
      <span class="fs14 fw600 " v-if="!editName"> {{ editValue }}</span>
      <el-input size="small" style="width: 300px" v-else v-model="editValue" />

      <el-icon
        v-if="!editName"
        class="el-icon-edit fs12"
        @click.native="editName = !editName"
      ></el-icon>
      <div v-else>
        <el-button size="medium" type="primary" @click="saveUS">保存</el-button>
        <el-button
          size="medium"
          @click="
            editName = !editName
            editValue = resetName
          "
          >取消</el-button
        >
      </div>
    </div>
    <div
      v-loading="isLoading"
      style="width: 100%; height: calc(100% - 42px);border-radius: 16px;overflow: hidden"
    >
      <iframe
        @load="handleAgentLoad"
        ref="agent"
        :src="agent.src"
        frameborder="0"
        style="width: 100%; height:100%;"
      />
    </div>
  </div>
</template>
