// index.js
// 获取应用实例
const app = getApp()

import { debug, info, error } from '../../log.js'

import {
  get_camera_rule,
  goto_camera,
  get_phone_model,
  extract_code_from_url,
} from '../../utils.js'

Page({
  data: {
    loading_data: true,
    userInfo: {},
    content: {},
    background_style: '',
    scan_button_text: '开启AI验证',
    scan_button_style: '',
  },
  goto_link(e) {
    var link = e.currentTarget.dataset.link;
    if (link) {
      wx.navigateTo({
        url: '/pages/article/article?article_id=' + link,
      });
    }
  },
  patch_url(items) {
    var server_url = app.globalData.server_url;
    for (var x of items) {
      if (x.url && x.url.startsWith('/')) {
        x.url = server_url + x.url;
      }
      if (x.img && x.img.startsWith('/')) {
        x.img = server_url + x.img;
      }
    }
  },
  process_content(c) {
    this.patch_url(c.carousel);
    this.patch_url([c.video]);
    this.patch_url(c.icons);
    this.patch_url(c.static);
    this.gen_scan_button_props(c);
    return c;
  },
  load_content(tenant_id, code) {
    console.log("load_content", tenant_id, code);
    var url = app.globalData.server_url + '/api/v1/mini-program-content/?';
    if (tenant_id) {
      url += "tenant=" + tenant_id;
    }
    if (code) {
      url += "&code=" + code;
    }
    console.log(url);
    var r = wx.request({
      url,
      complete: (res) => {
        console.log(res);
        if (res.statusCode == 200) {
          var content = this.process_content(res.data.content);
          console.log(content);
          this.setData({
            content: content,
            background_style: this.gen_background_style(content),
          });
        }
        this.setData({
          loading_data: false,
        });
      }
    })
  },
  onLoad(options) {
    var gd = app.globalData;
    // preload camera rules from server
    get_camera_rule(null, () => {});
    let phone_model = get_phone_model();
    info("phone model", phone_model);
    console.log(options);
    if (options.env == 'dev') {
      console.log("Using dev env settings.");
      gd.server_url = 'https://dev.themblem.com';
    }
    if (options.debug || options.scene == 'debug') {
      gd.debug = true;
    }
    gd.tenant = options.tenant;
    if (options.redirect && options.redirect.length > 0) {
      console.log("Redirecting to", options.redirect);
      wx.redirectTo({
        url: options.redirect,
      });
      return;
    }
    var code = null;
    if (options.q) {
      console.log("options.q", options.q);
      code = extract_code_from_url(decodeURIComponent(options.q));
      console.log("code", code);
    }
    this.load_content(options.tenant, code);
  },

  doGetUserProfile() {
    return wx.getUserProfile({
      desc: '展示用户信息',
    })
  },

  async getUserProfile(done_cb) {
    var ui = wx.getStorageSync('userinfo');
    if (!ui || !ui.emblem_id) {
      var res = await this.doGetUserProfile();
      ui = res.userInfo;
      ui.emblem_id = Math.random().toString().substr(2);
      wx.setStorageSync('userinfo', ui);
    }
    this.setData({
      userInfo: ui,
    });
    done_cb(ui);
  },

  goto_camera: function () {
    this.getUserProfile(() => {
      wx.navigateTo({
        url: '/pages/emblemscanner/emblemscanner?return_page=/pages/result_page/result_page'
      });
    });
  },

  gen_scan_button_props: function(content) {
    var scan_button = content.scan_button;
    var text = '开启AI验证';
    var style = '';
    
    if (scan_button) {
      if (scan_button.text) {
        text = scan_button.text;
      }
      
      var styles = [];
      if (scan_button.color) {
        styles.push('background-color: ' + scan_button.color);
      }
      if (scan_button.text_color) {
        styles.push('color: ' + scan_button.text_color);
      }
      style = styles.join('; ');
    }
    
    this.setData({
      scan_button_text: text,
      scan_button_style: style,
    });
  },

  gen_background_style: function(content) {
    var bg = content.background;
    var ret = '';
    if (!bg) return ret;
    if (bg.type == 'color') {
      ret = 'background-image: none; background-color: ' + bg.color;
    }
    if (bg.type == 'gradient') {
      ret =  'background-image: linear-gradient(' + bg.gradiant_begin + ',' + bg.gradiant_end + ');';
    }
    if (bg.type == 'image') {
      var base_url = getApp().globalData.server_url;
      ret =  'background-image: url("' + base_url + bg.image + '");';
    }
    console.log(ret);
    return ret;
  }
})
