// send-message-modal.component.ts
import { Component, EventEmitter, Input, Output } from '@angular/core';
import { CommonModule } from '@angular/common';
import {
  FormsModule,
  ReactiveFormsModule,
  FormBuilder,
  FormGroup,
  Validators,
  FormControl,
  AbstractControl,
  ValidationErrors,
} from '@angular/forms';

// NG-ZORRO 组件
import { NzFormModule } from 'ng-zorro-antd/form';
import { NzInputModule } from 'ng-zorro-antd/input';
import { NzButtonModule } from 'ng-zorro-antd/button';
import { NzSelectModule } from 'ng-zorro-antd/select';
import { NzSwitchModule } from 'ng-zorro-antd/switch';
import { NzModalRef } from 'ng-zorro-antd/modal';

@Component({
  selector: 'app-send-message-modal',
  standalone: true,
  imports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule,
    NzFormModule,
    NzInputModule,
    NzButtonModule,
    NzSelectModule,
    NzSwitchModule,
  ],
  template: `
    <form nz-form [formGroup]="form" class="message-form">
      <nz-form-item>
        <nz-form-label nzRequired>标题</nz-form-label>
        <nz-form-control [nzErrorTip]="titleErrorTpl">
          <input nz-input formControlName="title" placeholder="输入消息标题" />
          <ng-template #titleErrorTpl let-control>
            <ng-container *ngIf="control.hasError('required')">
              请输入标题
            </ng-container>
          </ng-template>
        </nz-form-control>
      </nz-form-item>

      <nz-form-item>
        <nz-form-label nzRequired>内容</nz-form-label>
        <nz-form-control [nzErrorTip]="contentErrorTpl">
          <textarea
            nz-input
            rows="4"
            formControlName="content"
            placeholder="输入消息内容"
          ></textarea>
          <ng-template #contentErrorTpl let-control>
            <ng-container *ngIf="control.hasError('required')">
              请输入内容
            </ng-container>
          </ng-template>
        </nz-form-control>
      </nz-form-item>

      <nz-form-item>
        <nz-form-label>图片链接</nz-form-label>
        <nz-form-control>
          <input
            nz-input
            formControlName="image"
            placeholder="输入图片URL（可选）"
          />
        </nz-form-control>
      </nz-form-item>

      <nz-form-item>
        <nz-form-label>大图模式</nz-form-label>
        <nz-form-control>
          <nz-switch formControlName="bigger"></nz-switch>
          <span nz-typography nzType="secondary">（有图片时有效）</span>
        </nz-form-control>
      </nz-form-item>

      <nz-form-item>
        <nz-form-label>客户端行为</nz-form-label>
        <nz-form-control>
          <nz-select formControlName="action" nzPlaceHolder="选择行为（可选）">
            <nz-option nzValue="go/app" nzLabel="打开应用"></nz-option>
            <nz-option nzValue="go/art" nzLabel="打开填色作品"></nz-option>
            <nz-option nzValue="go/album" nzLabel="打开专辑"></nz-option>
            <nz-option nzValue="gain/hint" nzLabel="获取提示奖励"></nz-option>
            <nz-option nzValue="keepgoing" nzLabel="继续完成作品"></nz-option>
          </nz-select>
        </nz-form-control>
      </nz-form-item>

      <nz-form-item>
        <nz-form-label>行为参数</nz-form-label>
        <nz-form-control>
          <input
            nz-input
            formControlName="param"
            [placeholder]="getParamPlaceholder()"
          />
        </nz-form-control>
      </nz-form-item>

      <nz-form-item>
        <nz-form-label>扩展参数</nz-form-label>
        <nz-form-control [nzErrorTip]="extendErrorTpl">
          <textarea
            nz-input
            rows="2"
            formControlName="extend"
            placeholder="输入JSON格式扩展参数（可选）"
          ></textarea>
          <ng-template #extendErrorTpl let-control>
            <ng-container *ngIf="control.hasError('invalidJson')">
              请输入有效的JSON格式
            </ng-container>
          </ng-template>
        </nz-form-control>
      </nz-form-item>
    </form>
  `,
  styles: [
    `
      .message-form {
        padding: 16px;
      }

      nz-form-item {
        margin-bottom: 16px;
      }

      textarea.ant-input {
        resize: vertical;
        min-height: 80px;
      }
    `,
  ],
})
export class SendMessageModalComponent {
  form: FormGroup;

  constructor(private fb: FormBuilder, private modalRef: NzModalRef) {
    this.form = this.fb.group({
      title: ['', Validators.required],
      content: ['', Validators.required],
      image: [''],
      bigger: [false],
      action: [''],
      param: [''],
      extend: ['', [this.jsonValidator]],
    });
  }

  // JSON格式验证器
  private jsonValidator(control: AbstractControl): ValidationErrors | null {
    if (!control.value) return null;
    try {
      JSON.parse(control.value);
      return null;
    } catch (e) {
      return { invalidJson: true };
    }
  }

  // 根据行为类型获取参数占位符
  getParamPlaceholder(): string {
    const action = this.form.get('action')?.value;
    switch (action) {
      case 'go/app':
        return '';
      case 'go/art':
        return '输入作品ID';
      case 'go/album':
        return '输入专辑ID';
      case 'gain/hint':
        return '输入提示数量';
      case 'keepgoing':
        return '输入作品ID';
      default:
        return '输入参数';
    }
  }

  // 获取表单值（已解析JSON）
  getFormValue(): any {
    const value = { ...this.form.value };
    if (value.extend) {
      value.extend = JSON.parse(value.extend);
    }
    return value;
  }
}
