<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import type { FormInstance } from 'ant-design-vue';
import { VxeUI } from 'vxe-pc-ui';
import { ArrowLeftOutlined, SaveOutlined } from '@ant-design/icons-vue';
import { setSatisfactionTriggerMethod } from '@/request/api/satisfaction.api';
import { useRequest } from 'alova/client';
import { notification } from 'ant-design-vue';

const props = defineProps<{
  data?: any;
}>();
const { loading: setting, send: onSetting } = useRequest(setSatisfactionTriggerMethod, { immediate: false });
const emits = defineEmits<{
  submit: [data?: any];
  back: [];
}>();

const formRef = ref<FormInstance>();

// 条件类型选项
const conditionTypeOptions = [
  { label: '就诊后', value: '0' },
  { label: '调养付款后', value: '1' },
  { label: '调养结束后', value: '2' },
];

// 表单数据
const form = reactive({
  name: '', // 问卷名称
  enabled: false, // 启用状态
  pushType: ['0'], // 通知渠道：站内等，默认选中站内
  status: '0', // 启用状态：0-启用，1-禁用
  satisfiesyPmr: {
    triggerType: '0', // 触发方式：0-就诊后，1-调养付款后，2-调养结束后
    triggerIntervalHours: null as any, // 触发间隔小时数
  },
});

// 表单验证规则
const rules: any = {
  pushType: [{ required: true, message: '请选择通知渠道', trigger: 'change', type: 'array', min: 1 }],
};

// 初始化数据
onMounted(() => {
  if (props.data) {
    Object.assign(form, props.data);
    form.enabled = props.data.status === '0' ? true : false;
    // 确保 pushType 是数组格式
    if (typeof form.pushType === 'string') {
      form.pushType = [form.pushType];
    } else if (!Array.isArray(form.pushType)) {
      form.pushType = ['0'];
    }
  } else {
    // 默认选中站内
    form.pushType = ['0'];
  }
  // 确保 satisfiesyPmr 始终存在
  if (!form.satisfiesyPmr) {
    form.satisfiesyPmr = {
      triggerType: '0',
      triggerIntervalHours: null as any,
    };
  }
});

// 保存
const handleSave = async () => {
  try {
    await formRef.value?.validate();
    setting.value = true;
    const status = form.enabled ? '0' : '1';
    const submitData = {
      ...form,
      status,
      pushType: Array.isArray(form.pushType) ? form.pushType[0] || '0' : form.pushType || '0',
      satisfiesyPmr: {
        ...form.satisfiesyPmr,
        triggerIntervalHours: form.satisfiesyPmr.triggerIntervalHours,
      },
    };
    onSetting(submitData).then(() => {
      notification.success({
        message: '保存成功',
      });
      emits('submit', submitData);
    });
  } catch (error) {
    notification.error({ message: '表单验证失败', description: (error as Error).message });
  } finally {
    setting.value = false;
  }
};

// 返回
const handleBack = () => {
  VxeUI.modal.close(`set-satisfaction-modal`);
};
</script>

<template>
  <div class="satisfaction-form-container">
    <!-- 表单内容 -->
    <div class="form-content">
      <a-form ref="formRef" :model="form" :rules="rules" layout="horizontal">
        <!-- 问卷名称和启用 - 同一行 -->
        <div class="form-row">
          <a-form-item label="问卷名称" name="name" class="form-row-item form-row-item-name">
            {{ form.name }}
          </a-form-item>

          <a-form-item label="启用:" name="enabled" class="form-row-item form-row-item-enabled">
            <a-switch v-model:checked="form.enabled" />
          </a-form-item>
        </div>

        <!-- 触发条件 -->
        <div class="trigger-conditions-section">
          <div class="flex items-center">
            <div class="section-label">触发条件：</div>
          </div>

          <!-- 条件列表 -->
          <div class="condition-row">
            <!-- 就诊后条件 -->
            <a-select v-model:value="form.satisfiesyPmr.triggerType" :options="conditionTypeOptions" style="width: 200px" class="condition-select" />
            <a-input 
              placeholder="请输入" 
              style="width: 160px" 
              class="condition-input"
              type="number"
              :value="form.satisfiesyPmr.triggerIntervalHours === null ? undefined : form.satisfiesyPmr.triggerIntervalHours"
              @input="(e: any) => { 
                const value = e.target.value;
                if (value === '' || value === null || value === undefined) {
                  form.satisfiesyPmr.triggerIntervalHours = null;
                } else {
                  const num = Number(value);
                  form.satisfiesyPmr.triggerIntervalHours = isNaN(num) ? null : num;
                }
              }"
            />
            <span class="condition-unit">小时</span>
          </div>
        </div>

        <!-- 通知渠道 -->
        <a-form-item label="通知渠道:" name="pushType" class="form-row-item" required>
          <a-checkbox-group v-model:value="form.pushType">
            <a-checkbox value="0">站内</a-checkbox>
          </a-checkbox-group>
        </a-form-item>
      </a-form>
    </div>

    <!-- 底部按钮 -->
    <div class="footer-actions">
      <vxe-button type="primary" status="primary" @click="handleBack">
        <template #icon>
          <ArrowLeftOutlined />
        </template>
        取消
      </vxe-button>
      <vxe-button type="submit" status="warning" @click="handleSave" :loading="setting">
        <template #icon>
          <SaveOutlined />
        </template>
        保存
      </vxe-button>
    </div>
  </div>
</template>

<style scoped lang="scss">
.satisfaction-form-container {
  padding: 24px;
  background: #fff;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.form-content {
  flex: 1;
  overflow: auto;
  margin-bottom: 24px;
}

.form-row {
  display: flex;
  gap: 16px;
  align-items: flex-start;
}

.form-row-item {
  flex: 1;
  margin-bottom: 0;
}

.form-row-item-name {
  flex: 0 1 auto;
  min-width: 400px;
  max-width: 600px;
}

.form-row-item-enabled {
  flex: 0 0 auto;
  width: auto;
}

.form-row-item :deep(.ant-form-item) {
  margin-bottom: 0;
  display: flex;
  flex-direction: column;
}

.form-row-item :deep(.ant-form-item-label) {
  flex: 0 0 auto;
  width: auto;
  min-width: 80px;
  text-align: left;
  padding-right: 8px;
  padding-bottom: 0;
}

.form-row-item :deep(.ant-form-item-control) {
  flex: 1;
  width: 100%;
}

// 触发条件部分
.trigger-conditions-section {
  margin-bottom: 24px;
}

.section-label {
  font-size: 14px;
  color: rgba(0, 0, 0, 0.85);
  margin-bottom: 12px;
  font-weight: 500;
}

.logic-buttons {
  display: flex;
  gap: 8px;
  margin-bottom: 16px;
}

.logic-btn {
  padding: 4px 16px;
  border: 1px solid #d9d9d9;
  background: #fff;
  color: rgba(0, 0, 0, 0.65);
  cursor: pointer;
  border-radius: 4px;
  font-size: 14px;
  transition: all 0.3s;

  &:hover {
    border-color: #ff7a45;
    color: #ff7a45;
  }

  &.active {
    background: #ff7a45;
    border-color: #ff7a45;
    color: #fff;
  }
}

.conditions-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.condition-row {
  display: flex;
  align-items: center;
  gap: 8px;
  flex-wrap: wrap;
  margin-bottom: 8px;
  &:first-child {
    margin-left: 35px;
  }
}

.condition-logic-label {
  color: #ff7a45;
  font-size: 14px;
  font-weight: 500;
  min-width: 24px;
  margin-right: 4px;
}

.condition-select,
.condition-input {
  flex-shrink: 0;
}

.condition-unit {
  font-size: 14px;
  color: rgba(0, 0, 0, 0.65);
  margin-left: 4px;
}

.add-condition-btn {
  width: 32px;
  height: 32px;
  border: 1px dashed #d9d9d9;
  background: #fff;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: rgba(0, 0, 0, 0.65);
  transition: all 0.3s;
  flex-shrink: 0;

  &:hover {
    border-color: #ff7a45;
    color: #ff7a45;
  }
}

// 底部按钮
.footer-actions {
  display: flex;
  justify-content: center;
  gap: 12px;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;

  :deep(.ant-btn-primary) {
    background: #ff7a45;
    border-color: #ff7a45;

    &:hover {
      background: #ff9256;
      border-color: #ff9256;
    }
  }

  :deep(.ant-btn-default) {
    color: #1890ff;
    border-color: #1890ff;

    &:hover {
      color: #40a9ff;
      border-color: #40a9ff;
    }
  }
}

:deep(.ant-form-item-label > label.ant-form-item-required:not(.ant-form-item-required-mark-optional)) {
  &::before {
    display: inline-block;
    margin-right: 4px;
    color: #ff4d4f;
    font-size: 14px;
    font-family: SimSun, sans-serif;
    line-height: 1;
    content: '*';
  }
}

:deep(.ant-form-item) {
  margin-bottom: 24px;
}

:deep(.ant-input),
:deep(.ant-select-selector),
:deep(.ant-picker) {
  border-color: #d9d9d9;
}

:deep(.ant-checkbox-group) {
  display: flex;
  gap: 16px;
}
</style>
