const app = require('../../utils/util.js');
const tools = require('../../utils/tools.js');
Page({
  data: {
    nameIsTrue: false, //名字是否填写
    cultureIsTrue: false, //文化是否填写
    graduationIsTrue: false, //毕业学校
    majorIsTrue: false, //所有专业
    postIsTrue: false, //现任职务
    renzhishijianIsTrue: false,
    phoneIsTrue: false, //电话
    peixunshijianTrue: false, // 培训时间
    nameMessage: '',
    zaizhiTime: [], //在线时间
    peixunTime: '', //培训时间
    headmasterText: [], // 
    names: [],
    timeIndex: '',
    chooseValue: [], // 选择的答案序列
    radio: '1',
    renzhiDate: '',
    postshow: [],
    postshow1: false,
    errorIsTrue: false,
    currentDate: new Date().getTime(),
    currentDate1: new Date().getTime(),
    minDate: new Date().getTime,
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      } else if (type === 'month') {
        return `${value}月`;
      }
      return value;
    },
    questionList: [],
    answersId: '', // 提交答案用到
    sessionKey: '',
    paperId: '',
    answersId: '',
    id: '',
    status: ''
  },
  onChange(event) {
    this.setData({
      radio: event.detail,
    });
  },
  radioChange(e) {
    const items = this.data.questionList[e.currentTarget.dataset.index].QuestChoice
    for (let i = 0, len = items.length; i < len; ++i) {
      items[i].checked = items[i].value === e.detail.value
    }
    let json = {};
    json.currentAnswer = e.detail.value;
    json.id = e.currentTarget.dataset.idx;
    json.questType = e.currentTarget.dataset.questtypes;
    this.data.chooseValue[e.currentTarget.dataset.index] = json;
    this.setData({
      questionList: this.data.questionList
    })
    wx.setStorageSync('questionList' + wx.getStorageSync('answersId'), this.data.questionList);
    wx.setStorageSync('chooseValue' + wx.getStorageSync('answersId'), this.data.chooseValue);
  },
  checkboxChange(e) {
    const items = this.data.questionList[e.currentTarget.dataset.index].QuestChoice
    const values = e.detail.value
    for (let i = 0, lenI = items.length; i < lenI; ++i) {
      items[i].checked = false
      for (let j = 0, lenJ = values.length; j < lenJ; ++j) {
        if (items[i].value === values[j]) {
          items[i].checked = true
          break
        }
      }
    }
    let json = {};
    let aa = e.detail.value.join("||")
    json.currentAnswer = aa;
    json.id = e.currentTarget.dataset.idx;
    json.questType = e.currentTarget.dataset.questtypes;
    this.data.chooseValue[e.currentTarget.dataset.index] = json;
    this.setData({
      questionList: this.data.questionList
    })
    wx.setStorageSync('questionList' + wx.getStorageSync('answersId'), this.data.questionList);
    wx.setStorageSync('chooseValue' + wx.getStorageSync('answersId'), this.data.chooseValue);
  },
  bindTextAreaBlur(e) {
    let json = {};
    json.currentAnswer = e.detail.value;
    json.id = e.currentTarget.dataset.idx;
    json.questType = e.currentTarget.dataset.questtypes;
    this.data.chooseValue[e.currentTarget.dataset.index] = json;
    this.data.questionList[e.currentTarget.dataset.index].QuestAnswer = e.detail.value;
    this.setData({
      questionList: this.data.questionList
    })
    wx.setStorageSync('questionList' + wx.getStorageSync('answersId'), this.data.questionList);
    wx.setStorageSync('chooseValue' + wx.getStorageSync('answersId'), this.data.chooseValue);
  },
  share() {
    this.setData({
      show: true
    });
  },
  onClose() {
    this.setData({
      ['postshow[' + this.data.timeIndex + ']']: false,
    });
  },
  onClose1() {
    this.setData({
      postshow1: false
    });
  },
  onInput(event) {
    this.setData({
      currentDate: event.detail,
    });
  },
  onInput1(event) {
    this.setData({
      currentDate1: event.detail,
    });
  },

  formatDate(date) {
    date = new Date(date);
    return `${date.getFullYear()-1}/${date.getMonth() + 1}/${date.getDate()}`;
  },

  share1(e) {
    this.data.postshow[e.currentTarget.dataset.index] = true;
    this.data.names[e.currentTarget.dataset.index] = e.currentTarget.dataset.names;
    this.setData({
      postshow: this.data.postshow,
      timeIndex: e.currentTarget.dataset.index
    })
  },
  share() {
    this.setData({
      postshow1: true
    });
  },
  formatDate(date) {
    date = new Date(date);
    return `${date.getFullYear()-1}/${date.getMonth() + 1}/${date.getDate()}`;
  },
  onConfirm(event) {
    let timeValue = this.timeFormat(new Date(event.detail), "yyyy-MM-dd");
    let json = {};
    json.currentAnswer = timeValue;
    json.id = event.currentTarget.dataset.idx;
    json.questType = event.currentTarget.dataset.questtypes;
    let aa = this.data.chooseValue[event.currentTarget.dataset.index] = json;
    this.data.questionList[event.currentTarget.dataset.index].QuestAnswer = timeValue;
    this.setData({
      questionList: this.data.questionList,
      ['chooseValue[' + event.currentTarget.dataset.index + ']']: aa,
      ['postshow[' + this.data.timeIndex + ']']: false,
      ['headmasterText[' + this.data.timeIndex + ']']: '',
    });
    wx.setStorageSync('questionList' + wx.getStorageSync('answersId'), this.data.questionList);
    wx.setStorageSync('chooseValue' + wx.getStorageSync('answersId'), this.data.chooseValue);
  },
  onConfirm1(event) {
    let timeValue = this.timeFormat(new Date(event.detail), "yyyy-MM-dd");
    this.setData({
      peixunTime: timeValue,
      postshow1: false,
      peixunText: ''
    });
  },
  parameterTap: function (e) { //e是获取e.currentTarget.dataset.id所以是必备的，跟前端的data-id获取的方式差不多
    let that = this
    let this_checked = e.currentTarget.dataset.id
    let parameterList = this.data.parameter //获取Json数组
    for (let i = 0; i < parameterList.length; i++) {
      if (parameterList[i].id == this_checked) {
        parameterList[i].checked = true; //当前点击的位置为true即选中
      } else {
        parameterList[i].checked = false; //其他的位置为false
      }
    }
    that.setData({
      parameter: parameterList
    })
  },
  submitForm() {
    let obj = this.data.chooseValue.find(item => !item.currentAnswer)
    if (!obj) {
      wx.request({
        url: app.globalData.publicUrl + '/wx/paper/commit',
        method: "post",
        data: {
          sessionKey: this.data.sessionKey,
          currentAnswerTemp: this.data.chooseValue,
          answersId: wx.getStorageSync('answersId')
        },
        success: (res) => {
          if (res.data.code == 0) {
            wx.showModal({
              showCancel: false,
              content: '提交成功',
              success() {
                wx.navigateBack({
                  delta: 1
                })
              }
            })
          } else {
            wx.showModal({
              showCancel: false,
              content: res.data.msg
            })
          }
        }
      })
    } else {
      wx.showModal({
        showCancel: false,
        content: '请补全提交信息哦',
        success() {}
      })
    }

  },
  formSubmit(e) {
    let arr1 = this.data.zaizhiTime.filter(d => d);
    let arr = this.data.names.filter(d => d);
    var activeSubjectsArr = [];
    for (var i = 0; i < arr.length; i++) {
      var activeSubjectsObject = {};
      for (var j = 0; j < arr1.length; j++) {
        if (i == j) {
          activeSubjectsObject[arr[i]] = arr1[j];
          activeSubjectsArr.push(activeSubjectsObject);
        }
      }
    }
    let count = 0;
    let data = {};
    for (let a in e.detail.value) {
      count += 1;
      if (count = 1) {
        data[a] = e.detail.value[a]
      }
    }
    activeSubjectsArr.forEach(item => {
      Object.assign(data, item)
    })
  },
  timeFormat(date, fmt) {
    let o = {
      "M+": date.getMonth() + 1, //月份   
      "d+": date.getDate(), //日
      "h+": date.getHours(), //小时   
      "m+": date.getMinutes(), //分   
      "s+": date.getSeconds(), //秒   
      "q+": Math.floor((date.getMonth() + 3) / 3), //季度   
      "S": date.getMilliseconds() //毫秒   
    };
    if (/(y+)/.test(fmt))
      fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (let k in o)
      if (new RegExp("(" + k + ")").test(fmt))
        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;

  },
  async onLoad(options) {
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    const sessionKey = await tools.checkSessionAndLogin();
    wx.setStorageSync('answersId', options.answersId);
    this.setData({
      sessionKey: sessionKey,
      paperId: options.paperId,
      answersId: options.answersId,
      id: options.id,
    })
    if (wx.getStorageSync('questionList' + wx.getStorageSync('answersId'))) {
      const questionList = wx.getStorageSync('questionList' + wx.getStorageSync('answersId'));
      this.setData({
        questionList: questionList,
        answersId: wx.getStorageSync('answersId' + wx.getStorageSync('answersId')),
        chooseValue: wx.getStorageSync('chooseValue' + wx.getStorageSync('answersId')),
      })
      wx.hideLoading();
    } else {
      this.allShi(this.data.id, this.data.paperId, this.data.sessionKey);
    }
  },
  allShi(id, paperId, sessionKey) {
    wx.request({
      url: app.globalData.publicUrl + '/wx/paper/detail',
      method: "post",
      data: {
        sessionKey: sessionKey,
        id: id,
        paperId: paperId
      },
      success: (res) => {
        let jsonArr = JSON.parse(res.data.paperContent).map(item => {
          let json = {};
          json.QuestType = item.QuestType;
          json.Id = item.Id;
          json.QuestAnswer = item.QuestAnswer;
          json.QuestStem = item.QuestStem;
          if (item.QuestType == '1' || item.QuestType == '0') {
            let arr = item.QuestChoice.split('||');
            let arrJson = arr.map(item => {
              let json1 = {};
              json1.name = item;
              json1.value = item;
              json1.checked = false;
              return json1
            });
            json.QuestChoice = arrJson;
          }
          return json;
        })
        let chooceArr = jsonArr.map(item => {
          let json = {};
          json.currentAnswer = '';
          json.questType = '';
          json.id = item.Id;
          json.QuestStem = item.QuestStem;
          return json
        })
        this.setData({
          questionList: jsonArr,
          chooseValue: chooceArr
        })
        wx.hideLoading();
        wx.setStorageSync('questionList' + wx.getStorageSync('answersId'), this.data.questionList);
        wx.setStorageSync('chooseValue' + wx.getStorageSync('answersId'), this.data.chooseValue);
      }
    })
  },
})