<template>
  <section class="AppOpenChat">
    <AiLoading :tips="tips" @click="tips=='点击空白处重试'&&execute"/>
  </section>
</template>

<script>
import {mapActions, mapState} from "vuex"

export default {
  name: "AppOpenChat",
  appName: "创建群聊",
  computed: {
    ...mapState(['user'])
  },
  data() {
    return {
      users: {},
      tips: "正在处理..."
    }
  },
  methods: {
    ...mapActions(['injectJWeixin', 'getAccount']),
    getUsers() {
      return Promise.all([
        // this.$http.post("/app/wxcp/wxuser/list", null, {params: {listType: 0}}).then(res => {
        //   if (res?.data) {
        //     return this.users.userIds = res.data.records?.map(e => e.id).join(";")
        //   }
        // }),
        this.$http.post("/app/wxcp/wxcustomer/list", null, {
          params: {
            wxUserId: this.user.wxUserId
          }
        }).then(res => {
          if (res?.data) {
            return this.users.externalUserIds = res.data.records?.filter(e => e.type == 1)?.map(e => e.id).join(";")
          }
        }),
      ])
    },
    handleCreateSuccess() {
      const {groupName} = this.$route.query
      wx.openEnterpriseChat({
        externalUserIds: "wmGBFVDgAAj_krfwaThRm-RRAq9rBeaQ",
        groupName,
        ...this.users,
        success: res => {
          if (res?.chatId) {
            this.handleCreateQrCode(res.chatId)
          }
        }
      })
    },
    handleCreateQrCode(groupId) {
      const {activityType, activityId, groupName} = this.$route.query
      this.$http.post("/api/wxcp/wxgroup/createGroupQrCode", null, {
        params: {groupId, activityType, activityId, groupName}
      })
    },
    execute() {
      return this.getAccount().then(this.getUsers).then(this.handleCreateSuccess)
    },
  },
  created() {
    this.injectJWeixin("openEnterpriseChat").then(() => this.$confirm(`确定创建${this.$route.query.groupName}?`))
    .then(this.execute).catch(err => {
      console.error(err)
      this.tips = "点击空白处重试"
    })
  }
}
</script>

<style lang="scss" scoped>
.AppOpenChat {
}
</style>
