<template>
  <div class="subscribe-container">
    <div class="subscribe-tip mb-3">当您订阅的软件有漏洞预警通知时，将以应用号的方式通知。可在首页查看或取消订阅！</div>
    <div class="subscribe-form">
      <d-form ref="formRef" :data="formData" :rules="rules">
        <d-form-item field="subscribeType" label="通知方式">
          <d-checkbox-group name="subscribeType" v-model="formData.subscribeType" :options="subscribeTypeOptions" direction="row"></d-checkbox-group>
        </d-form-item>
      </d-form>
    </div>
    <div class="subscribe-operation mt-5">
      <d-button @click="confirm" variant="solid" class="mr-2">确定</d-button>
      <d-button @click="$emit('close')">取消</d-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { subscribeSoftware } from '@/api/jyh';
import { computed, ref } from 'vue';
import { Message } from 'vue-devui';
const subscribeTypeOptions = [
  { name: '短信', value: 'mobileSwitch', id: 1 },
  { name: '邮件', value: 'emailSwitch', id: 2 },
  { name: '站内通知', value: 'webSwitch', id: 3 },
]; 
const props = defineProps(['softwareData']);
const emit = defineEmits(['close']);
const formRef = ref(null);
const formData = ref({
  subscribeType: [],
});
const rules = {
  subscribeType: [{ type: 'array', required: true, message: '请至少选择一种通知方式', trigger: 'change' }],
};
const sendSubscribe = async () => {
  let alertType = {};
  formData.value.subscribeType.forEach(item => {
    alertType[item.value] = true;
  })
  const data = await subscribeSoftware({
    softwareId: props.softwareData.id,
    status: '1',
    alertType,
  }).catch(err => {
    Message({
      message: err.error,
      type: 'error'
    })
  });
  if (!data?.data?.data?.data) {
    Message({
      message: data?.data?.data?.msg,
      type: 'error'
    })
  } else {
    Message({
      message: '订阅成功！',
      type: 'success'
    })
    emit('close');
  }
}
const confirm = () => {
  (formRef?.value as any)?.validate((isValid: boolean, invalidFields: any) => {
    if (!isValid) {
      return;
    }
    sendSubscribe();
  });
};
</script>

<style scoped lang="scss">
.subscribe-container {
  width: 600px;
  
  .subscribe-tip {
    color: #191919;
    font-family: HarmonyOS Sans SC;
    font-weight: regular;
    font-size: 14px;
  }

  .subscribe-form {
    display: flex;
    align-items: center;
    border-radius: 4px;
    background: #F2F5FC;
    padding: 20px 32px 0;

    form {
      width: 100%;
    }
  }

  .subscribe-operation {
    text-align: center;
  }
}
</style>