// pages/user/personalInfo/personalInfo.js
const app = getApp();
const api = app.api;
import WxValidate from '../../../utils/WxValidate'
Page({

  /**
   * 页面的初始数据
   */
  data: {

    // 性别 0 - 未知的性别,1 - 男性,2 - 女性,5 - 女性改(变)为男性,6 - 男性改(变)为女性,9 - 未说明的性别

    // 最高学历 0初中,1高中/中专,2大专,3本科,4硕士,5博士
    //性别字典
    sexPickList:[
        {
          name:"男",
          value:1,
        },
        {
          name:"女",
          value:2,
        }
    ],
    sexPickListValue:'',
    //学历
    EducationPickList:[],
    EducationPickValue:null,

    //学历状态
    EducationStatePickList:[],
    EducationStatePickValue:null,

    upFileInfo:null,
    referrerFileInfo:null,

    //展览记录
    showHistory:{
      id:"",
      name:"",
      organ:"",
      time:"",
    },
    //获奖记录
    awardHistory:{
      id:"",
      organ:"",
      prize:"",
      time:"",
    },

    //缺少艺名
    formData:{
      type:0,
      photoId:"",
      name:"",
      artistName:"",
      sex:"",
      birthday:"",
      nationality:"",

      referrerName:"",
      referrerPosition:"",
      referrerFileId:"",

      mobile:"",
      email:"",
      address:"",
      weixinNo:"",

      highestDegreeOrg:"",
      highestDegreeStartTime:"",
      highestDegreeEndTime:"",
      highestDegree:"",
      highestDegreeStatus:"",
      awardHistoryList:[],
      showHistoryList:[],
    },
    rules: {
      photoId:{
        required: true,
      },
      name:{
        required: true,
        cnAndEg: true
      },
      artistName:{
        required: true,
        cnAndEg: true
      },
      sex:{
        required: true,
      },
      birthday:{
        required: true,
      },
      // nationality:{
      //   required: true,
      // },
      // referrerName:{
      //   required: true,
      // },
      // referrerPosition:{
      //   required: true,
      // },
      // referrerFileId:{
      //   required: true,
      // },

      mobile: {
        required: true,
        tel:true,
      },
      email: {
        required: true,
        email:true,
      },
/*      address:{
        required: true,
      },
      weixinNo:{
        required: true,
      },*/

      highestDegreeOrg:{
        required: true
      },
      highestDegreeStartTime:{
        required: true
      },
      highestDegreeEndTime:{
        required: true
      },
      highestDegree:{
        required: true
      },
      highestDegreeStatus:{
        required: true
      }
    },
    awardRules:{
      organ:{
        required: true,
      },
      prize:{
        required: true,
      },
      time:{
        required: true,
      },
    },
    awardMessages:{
      organ:{
        required:'请输入奖项名称'
      },
      prize:{
        required:'请输入奖项机构'
      },
      time:{
        required:'请输入获奖时间'
      }
    },
    showRules:{
      name:{
        required: true,
      },
      organ:{
        required: true,
      },
      time:{
        required: true,
      },
    },
    showMessages:{
      name:{
        required: '请输入展展览名称',
      },
      organ:{
        required: '请输入展展览机构',
      },
      time:{
        required: '请输入展览时间',
      },
    },
    messages: {
      photoId:{
        required: '请上传个人形象照',
      },
      name:{
        required: '请输入姓名',
        cnAndEg: '只能输入英文和中文'
      },
      artistName:{
        required: '请输入艺名',
        cnAndEg: '只能输入英文和中文'
      },
      sex:{
        required: '请选择性别',
      },
      birthday:{
        required: '请选择出生日期',
      },
      nationality:{
        required: '请选择国籍',
      },
      // referrerName:{
      //   required: '请输入推荐人姓名',
      // },
      // referrerPosition:{
      //   required: '请输入推荐人职业',
      // },
      // referrerFileId:{
      //   required: '请上传推荐信',
      // },
      mobile: {
        required: '请输入手机号',
        tel:"请输入正确的手机号"
      },
      email: {
        required: '请输入邮箱地址',
        tel:"请输入正确的邮箱"
      },
      address:{
        required: '请输入地址',
      },
      weixinNo:{
        required: '请输入微信号',
      },
      highestDegreeOrg:{
        required: '请输入最高学历机构'
      },
      highestDegreeStartTime:{
        required: '请输入最高学历开始时间'
      },
      highestDegreeEndTime:{
        required: '请输入最高学历结束时间'
      },
      highestDegree:{
        required: '请选择最高学历',
      },
      highestDegreeStatus:{
        required: '请选择最高学历状态'
      }
    },
    isValidate:false,
    isSubmit:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const type=options.type||0
    const {
      formData,
      rules,
      messages,
      showHistory,
      awardHistory,
      awardRules,
      awardMessages,
      showRules,
      showMessages
    }
    = this.data;
    this.WxValidate    = new WxValidate(rules, messages);
    this.awardValidate = new WxValidate(awardRules, awardMessages);
    this.showValidate  = new WxValidate(showRules, showMessages);

    if(formData.awardHistoryList.length==0){
      this.setData({
        'formData.awardHistoryList':[{...awardHistory}]
      })
    }
    if(formData.showHistoryList.length==0){
      this.setData({
        'formData.showHistoryList':[{...showHistory}]
      })
    }
    //类型 0 个人 2策展
    formData.type=type
    Promise.all([
        this.findByCode('education'),
        this.findByCode('education_status')
    ]).then((res)=>{
     const EducationPickList=res[0].data.dicInfoList;
     const EducationStatePickList=res[1].data.dicInfoList;
     this.setData({
       EducationPickList:EducationPickList,
       EducationStatePickList:EducationStatePickList
     },()=>{
       //加载保存数据
       /** todo  更新数据 **/
       //this.getData();
     });
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
  getData(){
    const {formData}=this.data;
    app.post(api.getPersonalSettledInfo).then(res=>{
      console.log(res);
      const saveData=res.data;
      Object.keys(saveData).forEach(key=>{
        if(saveData[key]==null){
          delete  saveData[key]
        }
      })
      const formDataNew=Object.assign(formData,res.data);
      formDataNew.photoId=formDataNew.photoInfo?formDataNew.photoInfo.id:"";
      formDataNew.referrerFileId=formDataNew.referrerFile?formDataNew.referrerFile.id:"";
      this.setData({
        formData:formDataNew,
        upFileInfo:formDataNew.photoInfo,
        referrerFileInfo:formDataNew.referrerFile,
        sexPickListValue:formDataNew.sex==1?0:1,
        EducationPickValue:formDataNew.highestDegree,
        EducationStatePickValue:formDataNew.highestDegreeStatus
      },()=>{
        this.validateForm()
      });
    });

  },
  validateForm(showInfo=false){
    // 传入表单数据
    const {formData} = this.data;
    let flag=true;
    // let flagAward=false;
    // let flagShow=false;
    if (!this.WxValidate.checkForm(formData)) {
      flag=false
      if(showInfo===true) {
        const error = this.WxValidate.errorList[0];
        wx.showToast({
          title: error.msg,
          icon: 'none',
          duration: 2000
        })
      }
    }
    this.setData({
      isValidate:flag
    });
    return flag
    /*//验证获奖经历表单
    formData.awardHistoryList.forEach(item=>{
      if(flagAward){
        return
      }
      if (!this.awardValidate.checkForm(item)) {
        const error = this.awardValidate.errorList[0];
        wx.showToast({
          title: error.msg,
          icon: 'none',
          duration: 2000
        });
        flagAward=true;
        return false

      }
    });
    if(flagAward){
      return
    }
    //验证展览经历表单
    formData.showHistoryList.forEach(item=>{
      if(flagShow){
        return
      }
      if (!this.showValidate.checkForm(item)) {
        const error = this.showValidate.errorList[0];
        wx.showToast({
          title: error.msg,
          icon: 'none',
          duration: 2000
        });
        flagShow=true;
        return false

      }
    });
    if(flagShow){
      return
    }*/
  },
  saveData() {
    const {formData,isSubmit} = this.data;
    if(isSubmit){
      return
    }
    let flag=this.validateForm(true);
    if(!flag){
      return;
    }
    const submit=function(){
      this.setData({
        isSubmit:true
      })
      app.post(api.addPersonalDetails, formData).then(res => {
        console.log(res);
        this.setData({
          isSubmit:false,
        });
        wx.navigateTo({
          url:`/pages/user/success/success?type=${formData.type}`,
        })
      }).catch(()=>{
        this.setData({
          isSubmit:false
        })
      })
    }.bind(this);
    //策展入驻增加消息订阅
    if(formData.type==2){
      wx.requestSubscribeMessage({
        tmplIds: [
          'EnF59db6rv1QhwUc67GuKNQBw-R-VZNAB5xVXyP40A4',
        ],
        success: (res)=> {
          submit()
        }
      });
    }else{
      submit()
    }
  },
  changeInput(e){
    console.log(e);
    const id = e.currentTarget.id;
    const value = e.detail.value;
    this.setData({
      [id]: value
    });
  },
  changePicker(e){
    console.log(e);
    const id = e.currentTarget.id;
    const value = e.detail.value;
    this.setData({
      [id]: value
    });
  },
  /**上传形象**/
  chooseFile(){
    app.uploadFile({
      extension:['jpg','png','jpeg'],
      validate:(imgInfo)=>{
        console.log('validate',imgInfo)
        return true;
        // if(imgInfo.width&&imgInfo.height){
        //   const ratio=imgInfo.width/imgInfo.height;
        //   if(ratio>0.99&ratio<1.1){
        //     return true
        //   }else{
        //     wx.showToast({
        //       title:"请上传长宽比为1:1的图片",
        //       icon:"none",
        //       duration:2000,
        //     })
        //     return false
        //   }
        // }else{
        //   wx.showToast({
        //     title:"图片信息错误",
        //     icon:"none",
        //     duration:2000,
        //   })
        //   return false
        // }
      }
    }).then(res=>{
      console.log(res)
      const data=JSON.parse(res.data);
      this.setData({
        upFileInfo:data,
        'formData.photoId':data.id,
      })
    }).catch(error=>{
      console.log(error)
    });
  },
  /**删除形象**/
  removeChooseFile(){
    this.setData({
      upFileInfo:null,
      'formData.photoId':''
    })
  },
  /** 上传推荐信 **/
  chooseReferrerFile(){
    app.uploadFile({
      extension:['jpg','png','jpeg']
    }).then(res=>{
      console.log(res)
      const data=JSON.parse(res.data);
      this.setData({
        referrerFileInfo:data,
        'formData.referrerFileId':data.id
      })
    }).catch(error=>{
      console.log(error)
    });
  },
  /**删除推荐信**/
  removeReferrerFile(){
    this.setData({
      referrerFileInfo:null,
      'formData.referrerFileId':''
    })
  },

  findByCode(code){
    return app.post(api.findByCode,{
      "code": code
    })
  },

  /**
   * 添加奖励
   * */
  addAward() {
    const awardHistoryList=this.data.formData.awardHistoryList;
    awardHistoryList.push(this.data.awardHistory)
    this.setData({
      'formData.awardHistoryList':awardHistoryList
    })
  },
  /**
   * 删除奖励
   * */
  removeAward(e) {
    const {index}=e.currentTarget.dataset;
    const awardHistoryList=this.data.formData.awardHistoryList;
    awardHistoryList.splice(index,1);
    this.setData({
      'formData.awardHistoryList':awardHistoryList
    })
  },

  /**
   * 添加展览记录
   * */
  addShow() {
    const showHistoryList=this.data.formData.showHistoryList;
    showHistoryList.push(this.data.showHistory);
    this.setData({
      'formData.showHistoryList':showHistoryList
    })
  },

  /**
   * 删除展览记录
   * */
  removeShow(e) {
    const {index}=e.currentTarget.dataset;
    const showHistoryList=this.data.formData.showHistoryList;
    showHistoryList.splice(index,1);
    this.setData({
      'formData.showHistoryList':showHistoryList
    })
  },
  /**
   *
   * */
  sexPickHandler(e){
    const {value}=e.detail;
    const {sexPickList}=this.data;
    this.setData({
      sexPickListValue:value,
      'formData.sex':sexPickList[value].value
    },()=>{
      this.validateForm()
    });
  },

  /**
  * 学历picker 选择
  * **/
  educationPickHandler(e){
    const {value}=e.detail;
    const {EducationPickList}=this.data;
    this.setData({
      EducationPickValue:value,
      'formData.highestDegree':EducationPickList[value].code
    },()=>{
      this.validateForm()
    })
  },
  /**
   * 学历状态picker 选择
   * **/
  educationStatePickHandler(e){
    const {value}=e.detail;
    const {EducationStatePickList}=this.data;
    this.setData({
      EducationStatePickValue:value,
      'formData.highestDegreeStatus':EducationStatePickList[value].code,
    },()=>{
      this.validateForm()
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})