import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Router, ActivatedRoute } from '@angular/router';
import { IonicModule } from '@ionic/angular';
import { FormsModule } from '@angular/forms';
import { WxworkAuth } from 'fmode-ng/core';
import { FmodeParse, FmodeObject } from 'fmode-ng/parse';

const Parse = FmodeParse.with('nova');

type SurveyState = 'welcome' | 'questionnaire' | 'result';

interface Question {
  id: string;
  section: string;
  title: string;
  type: 'single' | 'multiple' | 'text' | 'number';
  options?: string[];
  hasOther?: boolean;
  required?: boolean;
  placeholder?: string;
  skipCondition?: (contact: any) => boolean;
}

/**
 * 项目问卷组件
 *
 * 功能:
 * 1. 外部联系人填写项目需求问卷
 * 2. 三种状态: 欢迎页、答题页、结果页
 * 3. 自动保存进度,支持中途退出恢复
 * 4. 联系人信息自动补全到ContactInfo
 *
 * 路由: /wxwork/:cid/survey/project/:projectId
 */
@Component({
  selector: 'app-project-survey',
  standalone: true,
  imports: [CommonModule, IonicModule, FormsModule],
  templateUrl: './project-survey.component.html',
  styleUrls: ['./project-survey.component.scss']
})
export class ProjectSurveyComponent implements OnInit {
  // 路由参数
  cid: string = '';
  projectId: string = '';

  // 企微授权
  wxAuth: WxworkAuth | null = null;

  // 当前状态
  currentState: SurveyState = 'welcome';

  // 加载状态
  loading: boolean = true;
  error: string | null = null;
  isCustomerOnly: boolean = false; // 是否仅限客户填写

  // 数据对象
  project: FmodeObject | null = null;
  currentContact: FmodeObject | null = null;
  surveyLog: FmodeObject | null = null;

  // 答题数据
  answers: any = {};
  currentQuestionIndex: number = 0;
  questions: Question[] = [];
  effectiveQuestions: Question[] = []; // 过滤掉跳过题目后的有效题目
  otherInput: string = ''; // "其他"选项的输入内容
  showOtherInput: boolean = false;

  constructor(
    private router: Router,
    private route: ActivatedRoute
  ) {}

  async ngOnInit() {
    // 获取路由参数
    this.cid = this.route.snapshot.paramMap.get('cid') || '';
    this.projectId = this.route.snapshot.paramMap.get('projectId') || '';

    // 初始化题目列表
    this.initQuestions();

    // 初始化企微授权
    await this.initWxworkAuth();

    // 加载数据
    await this.loadData();
  }

  /**
   * 初始化题目列表
   */
  initQuestions() {
    this.questions = [
      // 一、基础需求
      {
        id: 'q1',
        section: '基础需求',
        title: '本次您需要的核心服务是?',
        type: 'single',
        options: ['纯效果图渲染', '效果图+技术配合'],
        hasOther: true,
        required: true
      },
      {
        id: 'q2',
        section: '基础需求',
        title: '需覆盖的关键空间数量及类型?',
        type: 'text',
        placeholder: '例: 3个,客厅/主卧/儿童房',
        required: true
      },

      // 二、核心侧重
      {
        id: 'q3',
        section: '核心侧重',
        title: '您更希望本次效果图突出哪些价值?(可多选2-3项)',
        type: 'multiple',
        options: ['细节写实度', '视觉吸引力', '风格适配性'],
        hasOther: true,
        required: true
      },
      {
        id: 'q4',
        section: '核心侧重',
        title: '关于方案建议,是否需要我们技术团队配合?',
        type: 'single',
        options: ['需要', '暂不需要'],
        required: true
      },

      // 三、协作节奏
      {
        id: 'q5',
        section: '协作节奏',
        title: '您偏好的服务协作方式是?',
        type: 'single',
        options: ['前期多沟通', '先出初版再修改', '灵活协调'],
        required: true
      },

      // 四、特殊提醒
      {
        id: 'q6',
        section: '特殊提醒',
        title: '过往合作中,是否有需要特别注意的点?(可多选)',
        type: 'multiple',
        options: ['软装色调易偏差', '建模细节需盯控'],
        hasOther: true
      },
      {
        id: 'q7',
        section: '特殊提醒',
        title: '本次项目是否有特殊要求?(如业主禁忌、重点展示点)',
        type: 'text',
        placeholder: '请输入特殊要求...'
      },
      {
        id: 'q8',
        section: '特殊提醒',
        title: '是否有参考素材?(如风格图、实景图)',
        type: 'single',
        options: ['有(后续群内发送)', '无(需求已清晰)']
      },

      // 联系信息(自动跳过)
      {
        id: 'contact_name',
        section: '联系信息',
        title: '对接人姓名',
        type: 'text',
        required: true,
        skipCondition: (contact) => !!contact?.get('realname')
      },
      {
        id: 'contact_phone',
        section: '联系信息',
        title: '对接人电话',
        type: 'text',
        required: true,
        skipCondition: (contact) => !!contact?.get('mobile')
      }
    ];
  }

  /**
   * 初始化企微授权
   */
  async initWxworkAuth() {
    try {
      if (!this.cid) {
        throw new Error('未找到company ID (cid)');
      }

      this.wxAuth = new WxworkAuth({ cid: this.cid, appId: 'crm' });
      console.log('✅ 企微授权初始化成功');
    } catch (error) {
      console.error('❌ 企微授权初始化失败:', error);
      this.error = '初始化失败,请稍后重试';
    }
  }

  /**
   * 加载数据
   */
  async loadData() {
    try {
      this.loading = true;

      // 1. 获取当前外部联系人
      if (!this.wxAuth) {
        this.isCustomerOnly = true;
        this.error = '该问卷仅供客户填写,请通过企微群聊进入';
        // return;
      }

      try {
        this.currentContact = await this.wxAuth.currentContact();
        console.log('✅ 当前联系人:', this.currentContact?.get('name'));

        // 验证是否为外部联系人
        if (!this.currentContact || !this.currentContact.id) {
          console.warn('⚠️ 未找到外部联系人信息');
          this.isCustomerOnly = true;
          this.error = '该问卷仅供客户填写';
          // return;
        }
      } catch (error) {
        console.error('❌ 获取联系人失败:', error);
        this.isCustomerOnly = true;
        this.error = '该问卷仅供客户填写,请通过企微群聊进入';
        // return;
      }

      // 2. 加载项目
      if (this.projectId) {
        const query = new Parse.Query('Project');
        query.include('contact');
        this.project = await query.get(this.projectId);
        console.log('✅ 项目加载成功:', this.project.get('title'));
      }

      // 3. 过滤有效题目(根据skipCondition)
      this.effectiveQuestions = this.questions.filter(q => {
        if (q.skipCondition) {
          return !q.skipCondition(this.currentContact);
        }
        return true;
      });

      // 4. 检查是否已填写问卷
      await this.checkExistingSurvey();

    } catch (err: any) {
      console.error('❌ 加载失败:', err);
      this.error = err.message || '加载失败';
    } finally {
      this.loading = false;
    }
  }

  /**
   * 检查现有问卷
   */
  async checkExistingSurvey() {
    if (!this.project) return;

    try {
      const query = new Parse.Query('SurveyLog');
      query.equalTo('project', this.project.toPointer());
      query.equalTo('type', 'survey-project');

      this.surveyLog = await query.first();

      if (this.surveyLog?.get('isCompleted')) {
        // 已完成,直接显示结果
        this.currentState = 'result';
        this.answers = this.surveyLog.get('data') || {};
        console.log('✅ 问卷已完成,显示结果');
      } else if (this.surveyLog) {
        // 未完成,恢复进度
        this.answers = this.surveyLog.get('data') || {};
        console.log('✅ 恢复问卷进度,已填写', Object.keys(this.answers).length, '题');
      }
    } catch (err) {
      console.error('❌ 查询问卷失败:', err);
    }
  }

  /**
   * 开始填写问卷
   */
  startSurvey() {
    this.currentState = 'questionnaire';
    this.currentQuestionIndex = 0;
  }

  /**
   * 获取当前题目
   */
  getCurrentQuestion(): Question | null {
    if (this.currentQuestionIndex < 0 || this.currentQuestionIndex >= this.effectiveQuestions.length) {
      return null;
    }
    return this.effectiveQuestions[this.currentQuestionIndex];
  }

  /**
   * 上一题
   */
  previousQuestion() {
    if (this.currentQuestionIndex > 0) {
      this.currentQuestionIndex--;
      this.showOtherInput = false;
      this.otherInput = '';
    }
  }

  /**
   * 下一题
   */
  async nextQuestion() {
    const question = this.getCurrentQuestion();
    if (!question) return;

    // 验证必填
    if (question.required && !this.answers[question.id]) {
      alert('请完成当前题目');
      return;
    }

    // 处理"其他"选项
    if (this.showOtherInput && this.otherInput.trim()) {
      this.answers[question.id] = '其他:' + this.otherInput.trim();
    }

    // 保存当前答案
    await this.saveAnswer(question.id, this.answers[question.id]);

    // 重置"其他"输入
    this.showOtherInput = false;
    this.otherInput = '';

    // 检查是否最后一题
    if (this.currentQuestionIndex >= this.effectiveQuestions.length - 1) {
      // 最后一题,提交问卷
      await this.completeSurvey();
    } else {
      // 下一题
      this.currentQuestionIndex++;
    }
  }

  /**
   * 选择单选项
   */
  async selectSingleOption(option: string) {
    const question = this.getCurrentQuestion();
    if (!question) return;

    this.answers[question.id] = option;

    // 检查是否是"其他"选项
    if (question.hasOther && option.startsWith('其他')) {
      this.showOtherInput = true;
      this.otherInput = '';
    } else {
      this.showOtherInput = false;
      // 非"其他"选项,自动跳转下一题
      await this.nextQuestion();
    }
  }

  /**
   * 切换多选项
   */
  toggleMultipleOption(option: string) {
    const question = this.getCurrentQuestion();
    if (!question) return;

    let selected = this.answers[question.id] || [];
    if (!Array.isArray(selected)) {
      selected = [];
    }

    const index = selected.indexOf(option);
    if (index > -1) {
      selected.splice(index, 1);
    } else {
      selected.push(option);
    }

    this.answers[question.id] = selected;

    // 检查是否选择了"其他"
    if (question.hasOther && selected.some((s: string) => s.startsWith('其他'))) {
      this.showOtherInput = true;
    } else {
      this.showOtherInput = false;
    }
  }

  /**
   * 检查多选答案是否包含指定选项
   */
  hasMultipleOption(questionId: string, option: string): boolean {
    const answers = this.answers[questionId];
    if (!Array.isArray(answers)) return false;
    return answers.includes(option);
  }

  /**
   * 检查多选答案是否包含以指定文本开头的选项
   */
  hasMultipleOptionStartsWith(questionId: string, prefix: string): boolean {
    const answers = this.answers[questionId];
    if (!Array.isArray(answers)) return false;
    return answers.some(s => s.startsWith(prefix));
  }

  /**
   * 保存答案
   */
  async saveAnswer(questionId: string, answer: any) {
    try {
      if (!this.surveyLog) {
        // 首次保存,创建记录
        const SurveyLog = Parse.Object.extend('SurveyLog');
        this.surveyLog = new SurveyLog();

        const company = new Parse.Object('Company');
        company.id = localStorage.getItem('company') || this.cid;

        this.surveyLog.set('company', company.toPointer());
        this.surveyLog.set('project', this.project!.toPointer());
        this.surveyLog.set('contact', this.currentContact!.toPointer());
        this.surveyLog.set('type', 'survey-project');
      }

      // 更新答案
      const data = this.surveyLog.get('data') || {};
      data[questionId] = answer;
      this.surveyLog.set('data', data);

      await this.surveyLog.save();
      console.log('✅ 答案已保存:', questionId);
    } catch (err) {
      console.error('❌ 保存答案失败:', err);
    }
  }

  /**
   * 完成问卷
   */
  async completeSurvey() {
    if (!this.surveyLog) return;

    try {
      this.surveyLog.set('isCompleted', true);
      this.surveyLog.set('completedAt', new Date());
      await this.surveyLog.save();

      // 同步联系人信息
      await this.updateContactInfo();

      // 切换到结果页
      this.currentState = 'result';
      console.log('✅ 问卷提交成功');
    } catch (err) {
      console.error('❌ 提交问卷失败:', err);
      alert('提交失败,请重试');
    }
  }

  /**
   * 更新联系人信息
   */
  async updateContactInfo() {
    const data = this.surveyLog?.get('data') || {};

    if (!this.currentContact) return;

    try {
      let updated = false;

      if (data.contact_name && !this.currentContact.get('realname')) {
        this.currentContact.set('realname', data.contact_name);
        updated = true;
      }

      if (data.contact_phone && !this.currentContact.get('mobile')) {
        this.currentContact.set('mobile', data.contact_phone);
        updated = true;
      }

      if (updated) {
        await this.currentContact.save();
        console.log('✅ 联系人信息已更新');
      }
    } catch (err) {
      console.error('❌ 更新联系人信息失败:', err);
    }
  }

  /**
   * 获取进度百分比
   */
  getProgress(): number {
    if (this.effectiveQuestions.length === 0) return 0;
    return Math.round((this.currentQuestionIndex / this.effectiveQuestions.length) * 100);
  }

  /**
   * 格式化结果
   */
  getFormattedAnswer(questionId: string): string {
    const answer = this.answers[questionId];
    if (!answer) return '-';

    if (Array.isArray(answer)) {
      return answer.join('、');
    }

    return answer.toString();
  }

  /**
   * 脱敏手机号
   */
  maskPhone(phone: string): string {
    if (!phone || phone.length < 11) return phone;
    return phone.slice(0, 3) + '****' + phone.slice(7);
  }

  /**
   * 返回项目详情
   */
  goBack() {
      this.router.navigate(['/wxwork', this.cid, 'project', this.projectId]);
  }
}
