import common from '../../utils/util';
import server from '../../utils/main';

const app = getApp();
Page({
  data: {

  },
  onLoad: function (options) {
    var unitid = options.id;
    this.setData({
      Height: common.getSystemHeight(),
      UnitID: unitid,
    });
    this.init();
  },
  init: function () {
    var that = this;
    server.getData('GetHanziWordListByUnitID?UnitID=' + this.data.UnitID + "&UserID=" + app.globalData.userInfo.UserID, function (data) {
      if (data) {
        that.setData({
          List: data,
        })
      }
    });
  },
  changeSelected: function (e) {
    var id = e.currentTarget.dataset.id;
    var name = e.currentTarget.dataset.name;
    for (var i = 0; i < this.data.List.length; i++) {
      if (this.data.List[i].ID == id) {
        for (var j = 0; j < this.data.List[i].CombineWords.length; j++) {
          var item = this.data.List[i].CombineWords[j];
          if (item.name == name) {
            if (item.css == "")
              item.css = "selected";
            else
              item.css = "";
            break;
          }
        }
      }
    }
    this.setData({
      List: this.data.List,
    })
  },
  save: function () {
    var result=[];
    for (var i = 0; i < this.data.List.length; i++) {
      var word=[];
      for (var j = 0; j < this.data.List[i].CombineWords.length; j++) {
        var item = this.data.List[i].CombineWords[j];
        if (item.css == "selected"){
          word.push(item.name);
        }
      }
      this.data.List[i].CombineWords=word.join(",");
      result.push(this.data.List[i]);
    }

    var UnitCustom = wx.getStorageSync("UnitCustom");
    if (UnitCustom){
      var b=false;
      for(var i=0;i<UnitCustom.length;i++){
        if (UnitCustom[i].ID==this.data.UnitID){
          UnitCustom[i].List=result;
          b=true;
          break;
        }
      }

      if (!b){
        UnitCustom.push({
          ID:this.data.UnitID,
          List:result,
        })
      }
    }
    else{
      UnitCustom=[];
      UnitCustom.push({
        ID: this.data.UnitID,
        List: result,
      })
    }

    wx.setStorageSync("UnitCustom", UnitCustom);
    
    
    server.postData('AddHanziCustom',{
      UserID: app.globalData.userInfo.UserID,
      UnitID: this.data.UnitID,
      UnitCustom: JSON.stringify(result),
    }, function (data) {});

    app.globalData.IsSaveCustom=true;
    
    wx.navigateBack({
      delta: 1
    });
  },
})