<template>
  <Modal :centered="true" title="执行动作" visible :width="820" @cancel="onCancel" @ok="onOk" :maskClosable="false">
    <div class="steps-steps">
      <Steps :current="current" size="small" @change="onChange">
        <Step title="通知方式" key="way" />
        <Step title="通知配置" key="config" />
        <Step title="通知模板" key="template" />
        <Step title="模板变量" key="variable" />
      </Steps>
    </div>
    <div class="steps-content">
      <Form ref="actionForm" :model="formModel" layout="vertical">
        <template v-if="current === 0">
          <FormItem
            label="应用"
            name="notifyType"
            :rules="[
              {
                required: true,
                message: '请选择通知方式'
              }
            ]"
          >
            <NotifyWay v-model:value="formModel.notifyType" @change="(val) => onValChange(val, 'notifyType')" />
          </FormItem>
        </template>
        <template v-if="current === 1">
          <FormItem name="notifierId">
            <NotifyConfig
              v-model:value="formModel.notifierId"
              :notifyType="formModel.notifyType"
              @change="(val) => onValChange(val, 'notifierId')"
            />
          </FormItem>
        </template>
        <template v-if="current === 2">
          <FormItem name="templateId">
            <NotifyTemplate
              v-model:value="formModel.templateId"
              v-model:detail="template"
              :notifyType="formModel.notifyType"
              :notifierId="formModel.notifierId"
              @change="(val) => onValChange(val, 'templateId')"
            />
          </FormItem>
        </template>
        <template v-if="current === 3">
          <FormItem name="variables">
            <VariableDefinitions
              :variableDefinitions="variable"
              :value="formModel.variables"
              :notify="formModel"
              :template="template"
              :options="formModel.options"
              @change="(val) => onValChange(val, 'variables')"
              ref="variableRef"
            />
          </FormItem>
        </template>
      </Form>
    </div>
    <template #footer>
      <Space>
        <Button v-if="current === 0" @click="onCancel">取消</Button>
        <Button v-if="current > 0" @click="prev">上一步</Button>
        <Button v-if="current < 3" type="primary" @click="next">下一步</Button>
        <Button v-if="current === 3" type="primary" @click="onOk">确定</Button>
      </Space>
    </template>
  </Modal>
</template>

<script lang="ts" setup name="NotifyIndex">
  import NotifyWay from './NotifyWay.vue';
  import NotifyConfig from './NotifyConfig.vue';
  import NotifyTemplate from './NotifyTemplate.vue';
  import VariableDefinitions from './VariableDefinitions.vue';
  import { onlyMessage } from '@jdlinker/utils';
  import Template from '../../../../../../api/notice/template';
  import { PropType, ref, watch, reactive, watchEffect, unref } from 'vue';
  import { NotifyProps } from '../../../typings';
  import { Button, Modal, Space, Form, FormItem, Steps, Step } from 'linker-ui-components';

  const props = defineProps({
    value: {
      type: Object as PropType<Partial<NotifyProps>>,
      default: () => undefined
    },
    options: {
      type: Object,
      default: () => ({})
    },
    name: {
      type: Number,
      default: 0
    }
  });

  const emit = defineEmits(['cancel', 'save']);

  const current = ref(0);

  const formModel = reactive({
    notifyType: '',
    notifierId: '',
    templateId: '',
    variables: {},
    options: {}
  });

  const variable = ref([]);
  const variableRef = ref();
  const template = ref();

  watch(
    () => props.value,
    (newVal) => {
      Object.assign(formModel, newVal);
      if (newVal?.templateId) {
        Template.detail(newVal?.templateId).then((resp: any) => {
          if (resp.code === 200) {
            template.value = resp.result;
          }
        });
      }
    },
    { deep: true, immediate: true }
  );

  watchEffect(() => {
    formModel.options = props.options || {};
  });

  const onValChange = (val: any, type: string) => {
    if (type === 'notifyType') {
      formModel.templateId = '';
      formModel.variables = [];
      formModel.notifierId = '';
      formModel.options = {};
    } else if (type === 'notifierId') {
      formModel.templateId = '';
      formModel.variables = [];
      formModel.options = {
        ...val
      };
    } else if (type === 'templateId') {
      formModel.variables = [];
      formModel.options = {
        provider: formModel?.options?.provider || '',
        ...val
      };
    }
    formModel.options = {
      ...unref(formModel.options),
      ...val
    };
  };

  const jumpStep = async (val: number) => {
    if (val === 0) {
      current.value = val;
    } else if (val === 1) {
      if (formModel.notifyType) {
        current.value = val;
      } else {
        onlyMessage('请选择通知方式', 'error');
      }
    } else if (val === 2) {
      if (formModel.notifierId) {
        current.value = val;
      } else {
        onlyMessage('请选择通知配置', 'error');
      }
    } else if (val === 3) {
      if (formModel.templateId) {
        const resp = await Template.getTemplateDetail(formModel.templateId);
        console.log('Notify...', resp);
        if (resp.code === 200) {
          variable.value = resp.result?.variableDefinitions || [];
          current.value = val;
        }
      } else {
        onlyMessage('请选择通知模板', 'error');
      }
    }
  };

  const onChange = (cur: number) => {
    jumpStep(cur);
  };

  const prev = () => {
    current.value -= 1;
  };

  const next = async () => {
    jumpStep(current.value + 1);
  };

  const onCancel = () => {
    emit('cancel');
  };
  const onOk = async () => {
    let _data = null;
    if (variable.value.length) {
      _data = await variableRef.value.onSave();
    }
    formModel.variables = _data;
    const { options, ...extra } = formModel;
    emit('save', { ...extra }, { ...options });
  };
</script>

<style lang="less" scoped>
  .steps-steps {
    width: 100%;
    margin-bottom: 17px;
    padding-bottom: 17px;
    border-bottom: 1px solid #f0f0f0;
  }

  .steps-content {
    width: 100%;
  }
</style>
