<template>
  <BasicModal @register="registerModal" :title="title" :width="820" v-bind="$attrs" @ok="onSubmit"
  @close="close">
    <Form
      layout='vertical'
      :colon='false'
    >
      <FormItem name='trigger'>
        <RadioGroup
          v-model:value='trigger'
          :options='[
          { label: "提前通知天数", value: "month" },
        ]'
          option-type='button'
          button-style='solid'
        />
      </FormItem>
      <FormItem name='when'>
        <WhenOption v-model:value='whenObj.when' type='month' @change='updateValue' />
      </FormItem>
    </Form>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch, unref } from 'vue';
  import { BasicModal, useModalInner } from '@jdlinker/ui';
  import WhenOption from './WhenOption.vue'
  import {triggerRule, triggerRuleAdd} from "./template.api";
  import { Form, FormItem, RadioGroup } from 'linker-ui-components';

  const isUpdate = ref(false);
  const triggerRuleId = ref(null);
  const smsTemplateId = ref('');
  const trigger = 'month';
  const  whenObj = reactive({
    when: <Array<number>>[]
  });
  // 声明 emits
  const emit = defineEmits(['success', 'register']);
  const title = ref<string>('');

  watch(
    () => smsTemplateId.value,
    () => {
      getTriggerRule();
    },
    {immediate: true}
  )

  // 注册 modal
  const [registerModal, {setModalProps, closeModal}] = useModalInner( (data) => {
    title.value = unref(data.title);
    smsTemplateId.value = data.record.id;
  });

  function updateValue(data) {
    whenObj.when = data;
    if (Object.keys(data).length === 0) {
      whenObj.when = [0];
    }
  }

  function getTriggerRule() {
    triggerRule({smsTemplateId: smsTemplateId.value}).then(res => {
      if (res && res != '') {
        isUpdate.value = true;
        triggerRuleId.value = res.id;
        whenObj.when = res.advanceDays.split(",").map(item => parseInt(item));
      } else {
        isUpdate.value = false;
        triggerRuleId.value = null;
        whenObj.when.length = 0;
      }
    })
  }

  function close() {
    isUpdate.value = false;
    triggerRuleId.value = null;
  }

  //表单提交事件
  async function onSubmit() {
    try {
      setModalProps({ confirmLoading: true });
      // 提交表单
      let params = {
        id: triggerRuleId.value || null,
        smsTemplateId: smsTemplateId.value,
        advanceDays: whenObj.when.join(",")
      };
      triggerRuleAdd(params, isUpdate.value);
      //关闭弹窗
      closeModal();
      //刷新列表
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
