<!-- 编辑弹窗 -->
<template>
  <ele-modal
    :width="800"
    :visible="visible"
    :maskClosable="false"
    :maxable="maxable"
    :title="isUpdate ? '编辑ssl证书' : '添加ssl证书'"
    :body-style="{ paddingBottom: '28px' }"
    @update:visible="updateVisible"
    @ok="save"
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="styleResponsive ? { md: 4, sm: 5, xs: 24 } : { flex: '90px' }"
      :wrapper-col="
        styleResponsive ? { md: 19, sm: 19, xs: 24 } : { flex: '1' }
      "
    >
      <a-form-item label="绑定域名" name="name">
        <a-input
          allow-clear
          placeholder="请输入证书绑定的域名"
          v-model:value="form.name"
        />
      </a-form-item>
      <a-form-item label="上传ssl证书" name="certUrl">
        <a-upload
          v-model:file-list="fileList"
          name="file"
          action="http://192.168.222.129:8000/api/oss/upload"
          :headers="headers"
          @change="onUpload"
        >
          <a-button>
            <UploadOutlined />
            上传证书
          </a-button>
        </a-upload>
      </a-form-item>
      <a-form-item label="证书key" name="certKey">
        <a-textarea
          :rows="10"
          placeholder="请粘贴证书.key文件内容"
          v-model:value="form.certKey"
        />
      </a-form-item>
      <a-form-item label="证书pem" name="certPem">
        <a-textarea
          :rows="10"
          placeholder="请粘贴证书.pem文件内容"
          v-model:value="form.certPem"
        />
      </a-form-item>
<!--      <a-form-item label="证书crt" name="certCrt">-->
<!--        <a-input-->
<!--          allow-clear-->
<!--          placeholder="请输入证书crt"-->
<!--          v-model:value="form.certCrt"-->
<!--        />-->
<!--      </a-form-item>-->
      <a-form-item label="品牌厂商" name="brand">
        <DictSelect
          dict-code="serverBrand"
          placeholder="请选择品牌厂商"
          v-model:value="form.brand"
        />
      </a-form-item>
      <a-form-item label="证书价格" name="price">
        <a-input-number
          allow-clear
          style="width: 240px;"
          placeholder="请输入价格"
          v-model:value="form.price"
        />
      </a-form-item>
      <a-form-item label="购买时间" name="startTime">
        <a-date-picker
          v-model:value="form.startTime"
          placeholder="购买时间"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </a-form-item>
      <a-form-item label="到期时间" name="endTime">
        <a-date-picker
          v-model:value="form.endTime"
          placeholder="到期时间"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </a-form-item>
      <a-form-item label="租户ID" name="tenantId">
        <SelectCompany
          :placeholder="`选择所属租户`"
          v-model:value="form.tenantId"
          @done="chooseTenant"
        />
      </a-form-item>
      <a-form-item label="排序" name="sortNumber">
        <a-input-number
          :min="0"
          :max="9999"
          class="ele-fluid"
          placeholder="请输入排序号"
          v-model:value="form.sortNumber"
        />
      </a-form-item>
      <a-form-item label="备注" name="comments">
        <a-textarea
          :rows="4"
          :maxlength="200"
          placeholder="请输入描述"
          v-model:value="form.comments"
        />
      </a-form-item>
    </a-form>
  </ele-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import { Form, message } from 'ant-design-vue';
  import { assignObject } from 'ele-admin-pro';
  import { UploadOutlined } from '@ant-design/icons-vue';
  import { addOaAssetsSsl, updateOaAssetsSsl } from '@/api/oa/oaAssetsSsl';
  import { OaAssetsSsl } from '@/api/oa/oaAssetsSsl/model';
  import { useThemeStore } from '@/store/modules/theme';
  import { storeToRefs } from 'pinia';
  import { ItemType } from 'ele-admin-pro/es/ele-image-upload/types';
  import { FormInstance } from 'ant-design-vue/es/form';
  import {Company} from "@/api/system/company/model";

  // 是否是修改
  const isUpdate = ref(false);
  const useForm = Form.useForm;
  // 是否开启响应式布局
  const themeStore = useThemeStore();
  const { styleResponsive } = storeToRefs(themeStore);

  const props = defineProps<{
    // 弹窗是否打开
    visible: boolean;
    // 修改回显的数据
    data?: OaAssetsSsl | null;
  }>();

  const emit = defineEmits<{
    (e: 'done'): void;
    (e: 'update:visible', visible: boolean): void;
  }>();

  // 提交状态
  const loading = ref(false);
  // 是否显示最大化切换按钮
  const maxable = ref(true);
  // 表格选中数据
  const formRef = ref<FormInstance | null>(null);
  const images = ref<ItemType[]>([]);
  const fileList = ref<any[]>([]);
  const headers = ref<any>({
    Authorization: localStorage.getItem('access_token'),
    TenantId: localStorage.getItem('TenantId')
  })

  // 用户信息
  const form = reactive<OaAssetsSsl>({
    sslId: undefined,
    name: undefined,
    code: undefined,
    type: undefined,
    brand: undefined,
    price: undefined,
    content: undefined,
    certKey: undefined,
    certPem: undefined,
    certUrl: undefined,
    certCrt: undefined,
    startTime: undefined,
    endTime: undefined,
    isTop: undefined,
    comments: undefined,
    userId: undefined,
    userIds: undefined,
    status: 0,
    sortNumber: 100,
    tenantId: undefined
  });

  /* 更新visible */
  const updateVisible = (value: boolean) => {
    emit('update:visible', value);
  };

  // 表单验证规则
  const rules = reactive({
    name: [
      {
        required: true,
        type: 'string',
        message: '请填写绑定的域名',
        trigger: 'blur'
      }
    ],
    certUrl: [
      {
        required: true,
        type: 'string',
        message: '请上传证书文件',
        trigger: 'blur'
      }
    ]
  });

  const onUpload = ({file}) => {
    form.name = file.name;
    form.certUrl = file.response?.data.downloadUrl
  }

  const chooseTenant = (data: Company) => {
    form.tenantName = data.shortName;
    form.tenantId = data.tenantId;
  };

  const { resetFields } = useForm(form, rules);

  /* 保存编辑 */
  const save = () => {
    if (!formRef.value) {
      return;
    }
    formRef.value
      .validate()
      .then(() => {
        loading.value = true;
        const formData = {
          ...form
        };
        const saveOrUpdate = isUpdate.value ? updateOaAssetsSsl : addOaAssetsSsl;
        saveOrUpdate(formData)
          .then((msg) => {
            loading.value = false;
            message.success(msg);
            updateVisible(false);
            emit('done');
          })
          .catch((e) => {
            loading.value = false;
            message.error(e.message);
          });
      })
      .catch(() => {});
  };

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        images.value = [];
        fileList.value = [];
        if (props.data) {
          assignObject(form, props.data);
          if(props.data.certUrl){
            fileList.value = [{
              name: props.data.name,
              url: props.data.certUrl
            }]
          }
          isUpdate.value = true;
        } else {
          isUpdate.value = false;
        }
      } else {
        resetFields();
      }
    },
    { immediate: true }
  );
</script>
