<template>
  <PageContainer :pageHeaderRender="false" style="padding: 0 10px 10px 10px">
    <FullPage>
      <Card>
        <Row :gutter="[24, 24]" style="padding: 24px">
          <Col :span="12">
            <Form
              class="form"
              layout="vertical"
              :model="formData"
              name="basic"
              :label-col="{ span: 8 }"
              :wrapper-col="{ span: 24 }"
              autocomplete="off"
            >
              <FormItem label="证书标准" v-bind="validateInfos.type">
                <RadioGroup v-model:value="formData.type">
                  <RadioButton class="form-radio-button" value="common">
                    <img :src="getImage('/certificate.png')" />
                  </RadioButton>
                </RadioGroup>
              </FormItem>
              <FormItem label="证书名称" v-bind="validateInfos.name">
                <Input placeholder="请输入证书名称" v-model:value="formData.name" />
              </FormItem>
              <FormItem label="证书文件" v-bind="validateInfos['configs.cert']">
                <CertificateFile name="cert" v-model:modelValue="formData.configs.cert" placeholder="请输入证书文件" />
              </FormItem>
              <FormItem label="证书私钥" v-bind="validateInfos['configs.key']">
                <CertificateFile name="key" v-model:modelValue="formData.configs.key" placeholder="请输入证书私钥" />
              </FormItem>
              <FormItem label="说明" name="description">
                <Textarea placeholder="请输入说明" v-model:value="formData.description" :maxlength="200" :rows="3" showCount />
              </FormItem>
              <FormItem>
                <div style="text-align: right">
                  <Space>
                    <JButton @click="close"> 取消 </JButton>
                    <JButton class="form-submit" html-type="submit" type="primary" @click.prevent="onSubmit" :loading="loading">保存</JButton>
                  </Space>
                </div>
              </FormItem>
            </Form>
          </Col>
          <Col :span="12">
            <div class="doc">
              <h1>1. 概述</h1>
              <div>
                证书由受信任的数字证书颁发机构CA，在验证服务器身份后颁发，具有服务器身份验证和数据传输加密功能，保障设备与平台间的数据传输安全。配置后可被网络组件引用。
              </div>
              <h1>2. 配置说明</h1>
              <h2>1、证书文件</h2>
              <div>
                您可以使用文本编辑工具打开PEM格式的证书文件，复制其中的内容并粘贴到该文本框，或者单击该文本框下的上传，并选择存储在本地计算机的证书文件，将文件内容上传到文本框。
              </div>
              <h2>2、证书私钥</h2>
              <div>
                填写证书私钥内容的PEM编码。
                您可以使用文本编辑工具打开KEY格式的证书私钥文件，复制其中的内容并粘贴到该文本框，或者单击该文本框下的上传并选择存储在本地计算机的证书私钥文件，将文件内容上传到文本框。
              </div>
            </div>
          </Col>
        </Row>
      </Card>
    </FullPage>
  </PageContainer>
</template>

<script lang="ts" setup name="CertificateDetail">
import { getImage, onlyMessage } from "@jdlinker/utils";
import CertificateFile from "./CertificateFile.vue";
import type { UploadChangeParam } from "ant-design-vue";
import { queryDetail, save, update } from "../../../../api/link/certificate";
import { FormDataType, TypeObjType } from "../type";
import { FullPage } from "@jdlinker/ui";
// @ts-ignore
import {
  Button as JButton,
  Card,
  Col,
  Form,
  FormItem,
  PageContainer,
  RadioButton,
  RadioGroup,
  Row,
  Space,
  Textarea,
  Input
} from "linker-ui-components";
import { reactive, ref, toRaw } from "vue";

type Emit = {
    (e: 'close'): void;
  };
  const props = defineProps({
    id: {
      type: String,
      defult: ''
    }
  });
  const emit = defineEmits<Emit>();
  // const router = useRouter();

  const useForm = Form.useForm;

  const fileLoading = ref(false);
  const loading = ref(false);

  const formData = ref<FormDataType>({
    type: 'common',
    name: '',
    configs: {
      cert: '',
      key: ''
    },
    description: ''
  });

  const { validate, validateInfos } = useForm(
    formData,
    reactive({
      type: [{ required: true, message: '请选择证书标准', trigger: 'blur' }],
      name: [
        { required: true, message: '请输入证书名称', trigger: 'blur' },
        { max: 64, message: '最多可输入64个字符' }
      ],
      'configs.cert': [{ required: true, message: '请输入或上传文件', trigger: 'blur' }],
      'configs.key': [{ required: true, message: '请输入或上传文件', trigger: 'blur' }],
      description: [{ max: 200, message: '最多可输入200个字符' }]
    })
  );

  const onSubmit = () => {
    validate()
      .then(async () => {
        const params = toRaw(formData.value);
        loading.value = true;
        const response = !props.id ? await save(params).catch(() => {}) : await update({ ...params }).catch(() => {});
        if (response?.code === 200) {
          onlyMessage('操作成功', 'success');
          emit('close');
          // router.push('/linker/certificate');
        }
        loading.value = false;
      })
      .catch(() => {
        loading.value = false;
      });
  };

  const handleChange = (info: UploadChangeParam) => {
    fileLoading.value = true;
    if (info.file.status === 'done') {
      onlyMessage('上传成功！', 'success');
      formData.value.configs.cert = info.file.response?.result;
      fileLoading.value = false;
    }
  };

  const detail = async () => {
    if (props.id) {
      loading.value = true;
      const res: any = await queryDetail(props.id);
      if (res.success) {
        const result: any = res.result;
        const type = result.type.value as TypeObjType;
        formData.value = {
          ...result,
          type
        };
      }
      loading.value = false;
    }
  };

  detail();

  const close = () => {
    emit('close');
  };
</script>

<style lang="less" scoped>
  .form {
    .form-radio-button {
      width: 148px;
      height: 80px;
      padding: 0;
      img {
        width: 100%;
        height: 100%;
      }
    }
  }
</style>
