<template>
  <div class="proDog-setting">
    <a-form
      ref="formRef"
      name="basic"
      :label-col="{ style: { width: '186px' } }"
      :wrapper-col="{ span: 8 }"
      :rules="rules"
      :model="identitySetting"
      autocomplete="off"
    >
      <h4>字段配置</h4>
      <a-divider />
      <a-form-item label="uid(用户ID)" name="uid">
        <a-input
          v-model:value="identitySetting.uid"
          placeholder="必填，IDP 中用户ID"
        />
      </a-form-item>
      <a-form-item label="userName(用户姓名)" name="userName">
        <a-input
          v-model:value="identitySetting.userName"
          placeholder="必填，IDP 中用户姓名"
        />
      </a-form-item>
      <a-form-item label="userNo(员工编号)" name="userNo">
        <a-input
          v-model:value="identitySetting.userNo"
          placeholder="必填，IDP 中员工编号"
        />
      </a-form-item>
      <a-form-item label="nickName(员工昵称)" name="nickName">
        <a-input
          v-model:value="identitySetting.nickName"
          placeholder="选填，IDP 中员工昵称"
        />
      </a-form-item>
      <a-form-item label="email(员工邮箱)" name="email">
        <a-input
          v-model:value="identitySetting.email"
          placeholder="选填，IDP 中员工邮箱"
        />
      </a-form-item>
      <a-form-item label="phoneNumber(员工电话)" name="phoneNumber">
        <a-input
          v-model:value="identitySetting.phoneNumber"
          placeholder="选填，IDP 中员工电话"
        />
      </a-form-item>
      <a-divider />
      <h4>
        权限配置

        <a-button type="link" @click="queryTokenClient">
          查看登录公司
        </a-button>
      </h4>
      <a-divider />
      <a-form-item label="clientId(公司ID)" name="clientId">
        <a-input-number
          v-model:value="identitySetting.clientId"
          :controls="false"
          style="width: 100%"
          placeholder="必填，IDP 中公司ID"
        />
      </a-form-item>
      <a-form-item label="roleTemplateNo(角色模板)" name="roleTemplateNo">
        <a-input
          v-model:value="identitySetting.roleTemplateNo"
          placeholder="必填，如果有多个角色模板编号，使用逗号分隔"
        />
      </a-form-item>

      <a-divider />
      <h4>断言解析配置</h4>
      <a-divider />
      <a-form-item has-feedback label="Prodog 实体ID" name="spEntityID">
        <a-input
          v-model:value="identitySetting.spEntityID"
          placeholder="必填， Prodog 实体 ID "
        />
      </a-form-item>
      <a-form-item
        has-feedback
        label="Prodog断言解析地址"
        name="spAssertionConsumeService"
      >
        <a-input
          v-model:value="identitySetting.spAssertionConsumeService"
          placeholder="必填，Prodog 断言解析地址"
        />
      </a-form-item>
      <a-form-item
        has-feedback
        label="Prodog断言解析成功跳转地址"
        name="spAssertionConsumeSuccessRedirectService"
      >
        <a-input
          v-model:value="
            identitySetting.spAssertionConsumeSuccessRedirectService
          "
          placeholder="必填，Prodog 断言解析成功跳转地址"
        />
      </a-form-item>
    </a-form>
    <div style="margin: 22px 0 -22px 0">
      <a-button @click="prev"> 上一步 </a-button>
      <a-button type="primary" style="margin-left: 8px" @click="createIdentity">
        完成
      </a-button>
    </div>
  </div>
</template>

<script setup>
import Common from '../common/Common';
import { useRouter } from 'vue-router';
import { message } from 'ant-design-vue';
import { saveUpdateAuth } from './configData.js';
import { ref, defineProps, defineEmits, onMounted } from 'vue';
import TokenClientResource from '../api/base/TokenClientResource.js';

const router = useRouter();
const emit = defineEmits(['getDatas']);
const props = defineProps({
  formData: {
    type: Object,
    default: () => ({}),
  },
  identityInfo: {
    type: Object,
    default: () => ({}),
  },
});
const formRef = ref();
const prevDatas = ref({});
const identitySetting = ref({});

onMounted(() => {
  prevDatas.value = props.identityInfo;
  identitySetting.value = props.formData;
});

// 新建或更新认证源
const createIdentity = () => {
  formRef.value.validate().then(success => {
    const jsonStr = JSON.stringify(identitySetting.value);
    const formData = new FormData();
    formData.append('attribute', jsonStr);
    formData.append('id', prevDatas.value.id);
    formData.append('name', prevDatas.value.name);
    formData.append('no', prevDatas.value.no);
    formData.append('logo', prevDatas.value.file);
    formData.append('active', prevDatas.value.active);
    formData.append('authType', prevDatas.value.authType);
    formData.append('description', prevDatas.value.description);
    saveUpdateAuth(formData).then(
      success => {
        if (success.errorCode === 0) {
          if (!prevDatas.value.id) {
            message.success('新建认证源成功！');
          } else {
            message.success('更新认证源成功！');
          }
          router.push('/desktop/identityManager');
        } else {
          message.error(success.errorMessage);
        }
      },
      error => {
        Common.processException(error);
      },
    );
  });
};

const prev = () => {
  const datas = {
    current: 2,
    formData: identitySetting.value,
  };
  emit('getDatas', datas);
};

// 验证断言解析地址结束字符是否正确
let validateService = async (_rule, value) => {
  if (!value) {
    return Promise.reject('请输入 Prodog 断言解析地址');
  }
  let no = prevDatas.value.no;
  if (!value.endsWith('/api/saml/sso/' + no)) {
    return Promise.reject('断言解析地址必须以/api/saml/sso/' + no + '结束，' + no + '为认证源标识');
  }
};
// 验证断言解析成功跳转地址结束字符是否正确
let redirectService = async (_rule, value) => {
  if (!value) {
    return Promise.reject('请输入 Prodog 断言解析成功跳转地址');
  }
  if (!value.endsWith('index.html#/samlLogin')) {
    return Promise.reject(
      '断言解析成功跳转地址必须以index.html#/samlLogin结束',
    );
  }
};
const rules = {
  uid: [
    {
      required: true,
      message: '请输入"用户ID"对应的字段名称',
    },
  ],
  userName: [
    {
      required: true,
      message: '请输入"用户姓名"对应的字段名称',
    },
  ],
  userNo: [
    {
      required: true,
      message: '请输入"员工编号"对应的字段名称',
    },
  ],
  clientId: [
    {
      required: true,
      message: '请输入公司Id',
    },
  ],
  roleTemplateNo: [
    {
      required: true,
      message: '请输入角色模板编号',
    },
  ],
  spEntityID: [
    {
      required: true,
      message: '请输入 Prodog 实体 ID',
    },
  ],
  spAssertionConsumeService: [
    {
      required: true,
      validator: validateService,
      trigger: 'change',
    },
  ],
  spAssertionConsumeSuccessRedirectService: [
    {
      required: true,
      validator: redirectService,
      trigger: 'change',
    },
  ],
};

/**
 * 查询设置的公司
 */
const queryTokenClient = () => {
  TokenClientResource.queryTokenClient().then(
    baseObjectResponse => {
      if (baseObjectResponse.errorCode == 0) {
        message.success(
          '当前登录公司id:' +
            baseObjectResponse.data.clientId +
            '。公司名称:' +
            baseObjectResponse.data.clientName,
        );
      }
    },
    errorData => {
      Common.processException(errorData);
    },
  );
};
</script>

<style scoped>
.proDog-setting > h3 {
  font-size: 14px !important;
  font-weight: 700;
}
:deep(.ant-form-item-control-input-content) {
  display: flex;
  align-items: center;
}
:deep(.ant-form-item-label > label) {
  font-size: 12px !important;
  color: rgba(0, 0, 0, 0.4);
}
.ant-form-item {
  margin-bottom: 4px;
}
.ant-divider-horizontal {
  margin: 0 0 5px 0 !important;
}
</style>