<template>
  <a-form ref="formRef" :model="form" :rules="rules" layout="vertical">
    <a-row :gutter="20">
      <a-col :span="12">
        <a-form-item label="应用名称:" name="clientName">
          <a-input v-model:value="form.clientName" allow-clear placeholder="请输入应用名称" />
        </a-form-item>
      </a-col>
      <a-col :span="12">
        <a-form-item label="应用图标:" name="clientLogoFileId">
          <a-upload
            name="file"
            :multiple="false"
            :action="commonFileUploadUrl"
            v-model:file-list="clientLogoFileIdFileList"
            :default-file-list="clientLogoFileIdFileList"
            :maxCount="1"
            list-type="picture-card"
            :headers="commonUploadFileHeaders"
            :before-upload="beforeUpload"
            accept=".jpeg,.jpg,.png,.tif,.jfif,.webp,.pjp,.apng,.pjpeg,.avif,.ico,.tiff,.bmp,.xbm,.jxl,.jpeg,.svgz,.gif,.svg"
            @preview="handlePreviewPhoto"
            @download="downloadPhoto"
            @change="e => handleFileChange(e, clientLogoFileIdFileList, 'clientLogoFileId')"
            :showUploadList="{
              showDownloadIcon: true
            }"
          >
            <plus-outlined style="font-size: 28px; font-weight: 200" v-if="clientLogoFileIdFileList.length == 0" />
          </a-upload>
        </a-form-item>
      </a-col>
      <a-col :span="12">
        <a-form-item label="登录地址类型:" name="loginPageType">
          <a-radio-group v-model:value="form.loginPageType">
            <a-radio :value="1">应用自定义登录界面</a-radio>
            <a-radio :value="2">使用CA服务统一登录界面</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-col>
      <a-col :span="12">
        <a-form-item label="是否统一退出:" name="unifiedLogoutFlag">
          <a-radio-group v-model:value="form.unifiedLogoutFlag">
            <a-radio value="Y">是</a-radio>
            <a-radio value="N">否</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-col>
      <a-col :span="24" v-if="form.loginPageType == 1">
        <a-form-item name="customLoginUrl">
          <template #label>
            <span style="margin-right: 10px">应用登录地址:</span>
            <a-tooltip>
              <template #title>应用登录的地址，针对自定义登录界面 </template>
              <question-circle-outlined style="margin-top: 2px" />
            </a-tooltip>
          </template>
          <a-input v-model:value="form.customLoginUrl" allow-clear placeholder="请输入应用登录地址" />
        </a-form-item>
      </a-col>
      <a-col :span="24">
        <a-form-item name="ssoCallbackUrl">
          <template #label>
            <span style="margin-right: 10px">业务回调地址:</span>
            <a-tooltip>
              <template #title>单点登录到业务端时，跳转到业务端的地址 </template>
              <question-circle-outlined style="margin-top: 2px" />
            </a-tooltip>
          </template>
          <a-input v-model:value="form.ssoCallbackUrl" allow-clear placeholder="请输入回调业务地址" />
        </a-form-item>
      </a-col>
      <a-col :span="24">
        <a-form-item name="ssoLogoutUrl">
          <template #label>
            <span style="margin-right: 10px">退出地址:</span>
            <a-tooltip>
              <template #title>从认证中心退出后，通知业务端的地址 </template>
              <question-circle-outlined style="margin-top: 2px" />
            </a-tooltip>
          </template>
          <a-input v-model:value="form.ssoLogoutUrl" allow-clear placeholder="请输入退出地址" />
        </a-form-item>
      </a-col>
      <a-col :span="24">
        <a-form-item name="caTokenSecret">
          <template #label>
            <span style="margin-right: 10px">token秘钥:</span>
            <a-tooltip>
              <template #title>针对单点到业务系统的token（对称加密） </template>
              <question-circle-outlined style="margin-top: 2px" />
            </a-tooltip>
          </template>
          <a-input-group compact style="display: flex">
            <a-input v-model:value="form.caTokenSecret" allow-clear placeholder="请输入加密和解密的密钥" />
            <a-button type="primary" @click="generate">生成</a-button>
          </a-input-group>
        </a-form-item>
      </a-col>
      <a-col :span="24">
        <a-form-item label="排序:" name="clientSort">
          <a-input-number v-model:value="form.clientSort" style="width: 100%" placeholder="请输入排序码" allow-clear autocomplete="off" />
        </a-form-item>
      </a-col>
      <a-col :span="24">
        <a-form-item label="描述:" name="clientDescription">
          <a-textarea v-model:value="form.clientDescription" placeholder="请输入应用的描述" :rows="4" />
        </a-form-item>
      </a-col>
    </a-row>

    <!-- 图标预览弹框 -->
    <a-modal :visible="commonPreviewVisible" :footer="null" @cancel="commonPreviewVisible = false">
      <img alt="example" style="width: 100%" :src="commonPreviewImage" />
    </a-modal>
  </a-form>
</template>

<script setup name="SsoClientForm">
import { reactive, ref } from 'vue';
import { uuid } from '@/utils/common/print';
import { message, Upload } from 'ant-design-vue';
import { getToken } from '@/utils/token-util';
import { API_BASE_PREFIX } from '@/config/setting';
import { FileApi, FileUploadUrl as fileUploadUrlPrefix } from '@/views/system/backend/file/api/FileApi';

const props = defineProps({
  // 表单数据
  form: Object
});

// 验证规则
const rules = reactive({
  clientName: [{ required: true, message: '请输入应用名称', type: 'string', trigger: 'blur' }],
  loginPageType: [
    { required: true, message: '请输入登录地址的类型：1-应用自定义登录界面，2-使用CA服务统一登录界面', type: 'number', trigger: 'blur' }
  ],
  unifiedLogoutFlag: [{ required: true, message: '请输入是否统一退出：Y-是，N-否', type: 'string', trigger: 'blur' }],
  ssoCallbackUrl: [
    { required: true, message: '请输入回调业务地址，单点登录到业务端时，跳转到业务端的地址', type: 'string', trigger: 'blur' }
  ],
  customLoginUrl: [{ required: true, message: '请输入应用登录地址', type: 'string', trigger: 'blur' }],
  ssoLogoutUrl: [{ required: true, message: '请输入退出地址，从认证中心退出后，通知业务端的地址', type: 'string', trigger: 'blur' }],
  caTokenSecret: [
    { required: true, message: '请输入加密和解密的密钥，针对单点到业务系统的token（对称加密）', type: 'string', trigger: 'blur' }
  ]
});
// 上传文件的url
const commonFileUploadUrl = ref(`${API_BASE_PREFIX}${fileUploadUrlPrefix}?secretFlag=N`);

// 上传文件时候要带header
const commonUploadFileHeaders = ref({
  Authorization: getToken()
});

// 是否展示图片预览
const commonPreviewVisible = ref(false);

// 图片地址
const commonPreviewImage = ref(null);

// 应用图标上传图片列表
const clientLogoFileIdFileList = ref([]);

/**
 * 上传文件改变时的回调
 */
const handleFileChange = (info, list, fileFieldName) => {
  if (info.file.status === 'done') {
    // 设置临时fileList的值
    list = [info.file];

    // 将文件属性名和文件编码存入数组中
    message.success(`${info.file.name} 上传成功`);

    // 设置表单对应的文件属性的值
    props.form[fileFieldName] = info.file.response.data.fileId;
  } else if (info.file.status === 'error') {
    message.error(`${info.file.name} 上传失败`);
  }
};

/**
 * 上传之前的回调
 */
const beforeUpload = file => {
  const isJpgOrPng =
    file.type === 'image/jpeg' ||
    file.type === 'image/jpg' ||
    file.type === 'image/png' ||
    file.type === 'image/tif' ||
    file.type === 'image/jfif' ||
    file.type === 'image/webp' ||
    file.type === 'image/pjp' ||
    file.type === 'image/apng' ||
    file.type === 'image/pjpeg' ||
    file.type === 'image/avif' ||
    file.type === 'image/ico' ||
    file.type === 'image/tiff' ||
    file.type === 'image/bmp' ||
    file.type === 'image/xbm' ||
    file.type === 'image/jxl' ||
    file.type === 'image/svgz' ||
    file.type === 'image/gif' ||
    file.type === 'image/svg';
  if (!isJpgOrPng) {
    message.error('只能上传图片!');
    return Upload.LIST_IGNORE; //阻止列表展现
  }
  const isLt5M = file.size / 1024 / 1024 < 5;
  if (!isLt5M) {
    message.error('图片大小不能超过5MB!');
  }
  return isJpgOrPng && isLt5M;
};

/**
 * 点击预览图片
 */
const handlePreviewPhoto = async file => {
  commonPreviewImage.value = file.url || file.preview || file.thumbUrl;
  commonPreviewVisible.value = true;
};

/**
 * 下载图片
 */
const downloadPhoto = file => {
  let id = file.response ? file.response.data.fileId : file.uid;
  FileApi.download({ token: getToken(), fileId: id });
};

const generate = () => {
  props.form.caTokenSecret = uuid();
};

defineExpose({
  clientLogoFileIdFileList
});
</script>

<style></style>
