<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" max-height="560px" width="900px" scroll>
    <ContentWrap>
      <!-- 搜索工作栏 -->
      <el-form
        class="-mb-15px"
        ref="queryFormRef"
        :inline="true"
        label-width="68px"
      >
        <el-form-item label="关联系统">
          <el-select v-model="clientId" placeholder="请选择关联系统" style="width: 300px;">
            <el-option
              v-for="item in clientList"
              :key="item.id"
              :label="item.name"
              :value="item.id!"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            plain
            v-hasPermi="['system:user-client:create']"
            @click="submitForm"
          >
             添加
          </el-button>
        </el-form-item>
      </el-form>
    </ContentWrap>
    <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="关联系统" align="center" prop="clientName" />
      <el-table-column label="账户同步" align="center" prop="syncStatus" >
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.SYNC_USER_STATUS" :value="scope.row.syncStatus" />
        </template>
      </el-table-column>
      <el-table-column label="关联状态" align="center" prop="status" >
        <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="0"
              :inactive-value="1"
              @click="handleStatusChange2(scope.row)"
            />
<!--          <dict-tag :type="DICT_TYPE.APPLICATION_STATUS" :value="scope.row.status" />-->
        </template>
      </el-table-column>
<!--      <el-table-column label="创建人" align="center" prop="creatorDesc" />-->
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button
            type="primary"
            @click="handleSync(scope.row)"
            v-show = "scope.row.syncStatus!=1"
            v-hasClient="[scope.row.clientId+'']"
          >
            同步
          </el-button>
          <el-button
            type="primary"
            @click="handlerLink(scope.row.clientId)"
            v-show = "scope.row.syncStatus==1 && scope.row.permissionsLink==0"
            v-hasClient="[scope.row.clientId+'']"
          >
            权限设置
          </el-button>
<!--          <el-button-->
<!--            link-->
<!--            type="danger"-->
<!--            @click="handleDelete(scope.row.id)"-->
<!--            v-if = "scope.row.status==0"-->
<!--          >-->
<!--            停用-->
<!--          </el-button>-->
        </template>
      </el-table-column>
    </el-table>
    </ContentWrap>
  </Dialog>
</template>
<script setup lang="ts">
  import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
  import { CommonStatusEnum,ApplicationStatusEnum} from '@/utils/constants'
  import { defaultProps, handleTree } from '@/utils/tree'
  import * as PostApi from '@/api/system/post'
  import * as DeptApi from '@/api/system/dept'
  import * as UserApi from '@/api/system/user'
  import * as ClientApi from '@/api/system/oauth2/client'
  import { FormRules } from 'element-plus'
  import { UserClientApi, UserClientVO } from '@/api/system/userclient'
  import { dateFormatter } from '@/utils/formatTime'
  import * as authUtil from '@/utils/auth'

  defineOptions({ name: 'SystemUserClientForm' })

  const { t } = useI18n() // 国际化
  const message = useMessage() // 消息弹窗

  const dialogVisible = ref(false) // 弹窗的是否展示
  const dialogTitle = ref('') // 弹窗的标题

  const clientList = ref([] as ClientApi.OAuth2ClientVO[]) // 岗位列表

  const list = ref<UserClientVO[]>([]) // 列表的数据
  const loading = ref(true) // 列表的加载中
  const total = ref(0) // 列表的总页数
  const clientId = ref()
  const userId = ref()
  const queryParams = reactive({
    pageNo: 1,
    pageSize: 10,
    userId: undefined,
    clientId: undefined,
    syncStatus: undefined,
    status: undefined,
    additionalInformation: undefined,
    createTime: []
  })

  const handlerLink = async (id) =>{
    try {
      const linkUrl = await UserApi.getLinkInfo(id, authUtil.getAccessToken())
      console.log(linkUrl)
      if (linkUrl != "") {
        window.open(linkUrl);
      }
    }catch (error) {
      console.log(error);
    }
  }

  const clientParams = ref<UserClientVO>()

  const submitForm = async () => {
    if(clientId.value===undefined){
      message.error("未选择关联系统")
      return
    }
    clientParams.clientId = clientId.value
    clientParams.userId = userId.value
    clientParams.syncStatus = 0
    clientParams.status = 1
    await UserClientApi.createUserClient(clientParams)
    getList()
    message.success(t('common.createSuccess'))
  }

  /** 查询列表 */
  const getList = async () => {
    loading.value = true
    try {
      const data = await UserClientApi.getUserClientPage(queryParams)
      list.value = data.list
      total.value = data.total
    } finally {
      loading.value = false
    }
  }

  /** 打开弹窗 */
  const open = async (type: string, id?: number) => {
    clientId.value = undefined
    dialogVisible.value = true
    dialogTitle.value = t('action.' + type)+'用户应用关系'
    queryParams.pageNo = 1
    queryParams.userId = id
    userId.value = id
    getList()
    // 加载岗位列表
    clientList.value = await ClientApi.getSelfNoClientList(id)

  }
  /** 修改用户状态 */
  const handleStatusChange2 = async (row: UserClientVO) => {
    try {
      // 修改状态的二次确认
      const text = row.status === ApplicationStatusEnum.ENABLE ? '启用' : '停用'
      await message.confirm('确认要"' + text + '"用户应用关联关系吗?')
      // 发起修改状态
      await UserClientApi.updateUserClientStatus(row.id, row.status)
      // 刷新列表
      await getList()
    } catch {
      // 取消后，进行恢复按钮
      row.status =
        row.status === ApplicationStatusEnum.ENABLE ? ApplicationStatusEnum.DISABLE : ApplicationStatusEnum.ENABLE
    }
  }
  /** 修改用户状态 */
  const handleSync = async (row: UserClientVO) => {
    try {
      // 修改状态的二次确认
      const text = '同步'
      await message.confirm('确认要"' + text + '"用户信息吗?')
      // 发起修改状态
      await UserClientApi.syncUserInfo(row.userId, row.clientId)
      message.notifySuccess('同步成功')
      // 刷新列表
      await getList()
    } catch {

    }
  }
  defineExpose({ open }) // 提供 open 方法，用于打开弹窗
</script>
