module.exports = class extends think.Controller {
  /**
   * 根据 content_key 获取内容
   * GET /api/content?key=xxx
   */
  async contentAction() {
    const key = this.get('key');
    if (!key) return this.json({ code: 1, msg: '参数错误' });

    try {
      const item = await this.model('content').getByKey(key);
      if (think.isEmpty(item)) {
        return this.json({ code: 1, msg: '内容不存在' });
      }
      return this.json({ code: 0, data: item });
    } catch (error) {
      think.logger.error('获取内容失败:', error);
      return this.json({ code: 1, msg: '获取内容失败' });
    }
  }

  /**
   * 身份证OCR识别
   * POST /common/ocr/idcard
   */
  async ocrIdcardAction() {
    const { imageUrl, cardSide = 'FRONT' } = this.post();
    if (!imageUrl) {
      return this.json({ code: 1, msg: '请上传证件图片' });
    }

    const ocrConfig = require('../config/ocr.js');

    if (!ocrConfig.enabled || !ocrConfig.secretId) {
      return this.json({ code: 0, data: this._getMockIdCardData(cardSide), msg: 'OCR识别成功（模拟数据）' });
    }

    try {
      const tencentcloud = require('tencentcloud-sdk-nodejs');
      const OcrClient = tencentcloud.ocr.v20181119.Client;

      const client = new OcrClient({
        credential: { secretId: ocrConfig.secretId, secretKey: ocrConfig.secretKey },
        region: ocrConfig.region,
        profile: { httpProfile: { endpoint: 'ocr.tencentcloudapi.com' } }
      });

      const result = await client.IDCardOCR({ ImageUrl: imageUrl, CardSide: cardSide });

      const data = cardSide === 'FRONT' ? {
        name: result.Name || '',
        sex: result.Sex || '',
        nation: result.Nation || '',
        birth: result.Birth || '',
        address: result.Address || '',
        idNum: result.IdNum || ''
      } : {
        authority: result.Authority || '',
        validDate: result.ValidDate || ''
      };

      return this.json({ code: 0, data, msg: 'OCR识别成功' });
    } catch (error) {
      think.logger.error('[OCR] 身份证识别失败:', error);
      return this.json({ code: 1, msg: error.message || 'OCR识别失败' });
    }
  }

  /**
   * 港澳台通行证OCR识别
   * POST /common/ocr/hmt
   */
  async ocrHmtAction() {
    const { imageUrl } = this.post();
    if (!imageUrl) {
      return this.json({ code: 1, msg: '请上传证件图片' });
    }

    const ocrConfig = require('../config/ocr.js');

    if (!ocrConfig.enabled || !ocrConfig.secretId) {
      return this.json({ code: 0, data: this._getMockHmtData(), msg: 'OCR识别成功（模拟数据）' });
    }

    try {
      const tencentcloud = require('tencentcloud-sdk-nodejs');
      const OcrClient = tencentcloud.ocr.v20181119.Client;

      const client = new OcrClient({
        credential: { secretId: ocrConfig.secretId, secretKey: ocrConfig.secretKey },
        region: ocrConfig.region,
        profile: { httpProfile: { endpoint: 'ocr.tencentcloudapi.com' } }
      });

      const result = await client.MainlandPermitOCR({ ImageUrl: imageUrl });

      return this.json({
        code: 0,
        data: {
          name: result.Name || '',
          englishName: result.EnglishName || '',
          sex: result.Sex || '',
          birth: result.Birthday || '',
          idNum: result.Number || '',
          issueAuthority: result.IssueAuthority || '',
          validDate: result.ValidDate || '',
          issueAddress: result.IssueAddress || '',
          type: result.Type || ''
        },
        msg: 'OCR识别成功'
      });
    } catch (error) {
      think.logger.error('[OCR] 港澳台通行证识别失败:', error);
      return this.json({ code: 1, msg: error.message || 'OCR识别失败' });
    }
  }

  _getMockIdCardData(cardSide) {
    if (cardSide === 'FRONT') {
      return {
        name: '张三', sex: '男', nation: '汉',
        birth: '1990/01/01', address: '北京市朝阳区xxx街道xxx号',
        idNum: '110101199001011234'
      };
    }
    return { authority: '北京市公安局朝阳分局', validDate: '2020.01.01-2040.01.01' };
  }

  _getMockHmtData() {
    return {
      name: '李小红', englishName: 'LI XIAOHONG', sex: '女',
      birth: '1992.08.20', idNum: 'H12345678',
      issueAuthority: '公安部出入境管理局', validDate: '2020.01.01-2030.01.01',
      issueAddress: '广东', type: '港澳居民来往内地通行证'
    };
  }

  /**
   * 获取瘤种选项列表
   * GET /common/tagOptions
   */
  async tagOptionsAction() {
    try {
      const tags = await this.model('sys_config').getByKey('tag_options');
      return this.json({ code: 0, data: tags || [] });
    } catch (error) {
      think.logger.error('获取瘤种选项失败:', error);
      return this.json({ code: 0, data: [] });
    }
  }

  /**
   * 获取省市区树形数据（一次返回）
   * GET /common/regions
   */
  async regionsAction() {
    try {
      const regionModel = this.model('sys_region');
      const regions = await regionModel
        .where({ status: 1 })
        .order('code ASC')
        .select();

      // 分离省、市、区
      const provinces = [];
      const cityMap = {};
      const districtMap = {};

      regions.forEach(r => {
        const code = r.code;
        if (code.endsWith('0000')) {
          provinces.push({ code, name: r.name, children: [] });
        } else if (code.endsWith('00')) {
          const parentCode = code.substring(0, 2) + '0000';
          if (!cityMap[parentCode]) cityMap[parentCode] = [];
          cityMap[parentCode].push({ code, name: r.name, children: [] });
        } else {
          const parentCode = code.substring(0, 4) + '00';
          if (!districtMap[parentCode]) districtMap[parentCode] = [];
          districtMap[parentCode].push({ code, name: r.name });
        }
      });

      // 组装树
      provinces.forEach(p => {
        p.children = cityMap[p.code] || [];
        p.children.forEach(c => {
          c.children = districtMap[c.code] || [];
        });
      });

      return this.json({ code: 0, data: provinces });
    } catch (error) {
      think.logger.error('获取省市区数据失败:', error);
      return this.json({ code: 1, msg: '获取省市区数据失败' });
    }
  }
};
