// pages/user/artUpload/artUpload.js
import WxValidate from "../../../utils/WxValidate";
import {pointNum} from "../../../utils/util"
const app = getApp();
const api = app.api;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    id:null,
    userInfo:null,
    avatarImgFile:null,
    //作品分类
    categoryList:[],
    categoryIdPicker:[],
    categoryIdPickerValue:[0,0],
    categoryName:"",
    // 数字艺术品选项
    digitalArtworkOptions: {
      index: 0,
      options: [
        {label: '否', value: 0},
        {label: '是', value: 2}
      ]
    },

    //作品文件
    opusPicFile:[],
    maxTime:'', //时间限制
    formData:{
      avatarId:"", //艺术家头像id
      artistName:'', //艺名
      author:"", //作者
      name:"", //作品名称
      categoryId: "", //作品分类ID
      material:"", //材质

      fixedHeight:"", //固定高
      fixedLength:"", //固定长
      fixedWidth:"", //固定宽
      sizeMark:"", //无尺寸备注

      frameLength:"", //画框长
      frameWidth:"", //画框宽
      heartLength:"", //画芯长
      heartWidth:"", //画芯宽

      opusPicInfoList:[
      ],

      sourceType:0, //作品来源 0艺术家平台作品登记,1活动报名

      time:"", //作品年份
      price:"", //作品价格单位分
      version:"", //作品版本
      desp:"", //作品描述

      types: 0 // 不是数字艺术品
    },
    rules: {
      avatarId:{
        required: true,
      }, //艺术家头像id
      artistName:{
        required: true,
      }, //艺名
      opusPicInfoList:{
        required: true,
      },
      // author:{
      //   required: true,
      // }, //作者
      categoryId: {
        required: true,
      }, //作品分类ID
      material:{
        required: true,
      }, //材质
      name:{
        required: true,
      }, //作品名称

      price:{
        required: true,
      }, //作品价格单位分
      sourceType:{
        required: true,
      }, //作品来源 0艺术家平台作品登记,1活动报名
      time:{
        required: true,
      }, //作品年份
      desp:{
        required: true,
      }, //作品描述
      /*
      version:{
        required: true,
      } */
      //作品版本
    },
    messages: {
      avatarId:{
        required: '请上传艺术家头像',
      },
      artistName:{
        required: '请输入艺术家姓名',
      },
      opusPicInfoList:{
        required: '请上传作品',
      },
      // author:{
      //   required: '请填写作者姓名',
      // }, //作者
      categoryId:{
        required: '请选择作品类型',
      },
      material:{
        required: '请输入作品材质',
      },
      time:{
        required: '请选择作品日期',
      },
      version:{
        required: '请输入作品版本',
      },
      price:{
        required: '请输入作品价格',
      },
      desp:{
        required: '请输入作品阐述',
      }
    },
    rulesPM:{
      frameLength:{
        required: true,
      }, //画框长
      frameWidth:{
        required: true,
        number: true
      }, //画框宽

      heartLength:{
        required: true,
        number: true
      }, //画芯长
      heartWidth:{
        required: true,
        number: true
      }, //画芯宽
    },
    messagesPM:{
      frameLength:{
        required: '请输入画框长度',
        number: '请输入正确的画框长度'
      }, //画框长
      frameWidth:{
        required: '请输入画框宽度',
        number: '请输入正确的画框宽度'
      }, //画框宽

      heartLength:{
        required: '请输入画芯长度',
        number: '请输入正确的画芯长度'
      }, //画芯长
      heartWidth:{
        required: '请输入画芯宽度',
        number: '请输入正确的画芯宽度'
      }, //画芯宽
    },
    rulesLT:{
      fixedHeight:{
        required: true,
        number: true
      }, //固定高
      fixedLength:{
        required: true,
        number: true
      }, //固定长
      fixedWidth:{
        required: true,
        number: true
      }, //固定宽
    },
    messagesLT:{
      fixedHeight:{
        required: '请输入作品高',
        number: '请输入正确的作品高'
      }, //固定高
      fixedLength:{
        required: '请输入作品长',
        number: '请输入正确的作品长'
      }, //固定长
      fixedWidth:{
        required: '请输入作品宽',
        number: '请输入正确的作品宽'
      }, //固定宽
    },
    isSubmit:false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      id:options.id||null
    })
    const {
      rules,
      messages,
      rulesPM,
      messagesPM,
      rulesLT,
      messagesLT
    }
        = this.data;
    this.WxValidate    = new WxValidate(rules, messages);
    this.WxValidatePM   = new WxValidate(rulesPM, messagesPM);
    this.WxValidateLT   = new WxValidate(rulesLT, messagesLT);
    this.getArtCode().then(res=>{
      console.log('getData=======>')
      const {id}=this.data;
      if(id){
        this.getData();
      }
    });
    this.getUserData();
    wx.hideShareMenu();
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getMaxTime()
  },
  /**当前日期**/
  getMaxTime(){
    const date=new Date()
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    this.setData({
      maxTime:`${year}-${month}-${day}`
    })
  },
  getArtCode(){
    return app.post(api.findTreeByType,{
        "categoryType": 5
    }).then(res=>{
      const data=res.data[0];
      this.setData({
        categoryList:data.children,
        categoryIdPicker:[data.children,data.children[0].children]
      })
      return Promise.resolve(true)
    })
  },
  /**编辑作品信息获取数据**/
  getData(){
    const {opusPicFile,categoryList,categoryIdPickerValue,categoryIdPicker}=this.data;
    const {opusPicInfoList}=this.data.formData;
    app.post(api.artFindById,{
      id:this.data.id
    }).then(res=>{
      res.data.price = res.data.price/100
      if(res.data.opusPicInfoList&&res.data.opusPicInfoList.length!=0){
        res.data.opusPicInfoList=[{
          fileId:res.data.opusPicInfoList[0].id,
          type:'img', // img||video
          url:res.data.opusPicInfoList[0].url
        }];
        opusPicFile.push(res.data.opusPicInfoList[0]);
      }
      console.info(res.data)
      console.info(opusPicFile);
      const categoryId=res.data.categoryId;
      const categoryName=res.data.categoryName;
      categoryList.forEach((category,categoryIndex)=>{
        category.children.forEach((item,index)=>{
          if(categoryId==item.id){
            categoryIdPickerValue[0]=categoryIndex;
            categoryIdPickerValue[1]=index;
            categoryIdPicker[1]=categoryList[categoryIndex].children;
          }
        });
      });

      this.setData({
        opusPicFile:opusPicFile,
        formData:res.data,
        categoryIdPicker,
        categoryIdPickerValue,
        categoryName
      })
    })
  },

  /*获取个人信息*/
  getUserData(){
    let {
      rules,
      messages,
    }
        = this.data;
    app.post(api.getBaseInfo).then(res=>{
      if(res.data.type == 0 ){
        console.log('delete=====================');
        delete rules.avatarId
        delete rules.artistName
      }
      this.setData({
        userInfo:res.data,
        rules:rules
      },()=>{
         this.WxValidate=null;
          this.WxValidate    = new WxValidate(rules, messages);
      });
    });
  },

  upArtImg(){
    app.uploadFile().then(res=>{
      console.log(res);
      const fileInfo=JSON.parse(res.data);
      this.setData({
        avatarImgFile:fileInfo,
        'formData.avatarId':fileInfo.id
      })
    });
  },

  removeUpArtImg(){
    this.setData({
      avatarImgFile:null,
      'formData.avatarId':""
    })
  },
  upArtFile(){
    const {opusPicFile}=this.data;
    const {opusPicInfoList}=this.data.formData;

    app.uploadFile().then(res=>{
      console.log(res);
      const fileInfo=JSON.parse(res.data);
      opusPicInfoList.push({
        fileId:fileInfo.id,
        type:'img' // img||video
      });
      opusPicFile.push(fileInfo);
      this.setData({
        opusPicFile:opusPicFile,
        'fromData.opusPicInfoList':opusPicInfoList
      })
    });
  },
  removeUpArtFile(e){
    const {index}=e.currentTarget.dataset;
    const {opusPicFile}=this.data;
    const {opusPicInfoList}=this.data.formData;
    opusPicFile.splice(index,1);
    opusPicInfoList.splice(index,1);
    this.setData({
      opusPicFile:opusPicFile,
      'fromData.opusPicInfoList':opusPicInfoList
    })
  },
  /** input change value**/
  changeInput(e){
    console.log(e);
    const id = e.currentTarget.id;
    const number = e.currentTarget.dataset.number;
    let value = e.detail.value;
    if(number=='pointNum'){
      value=pointNum(value)
    }
    this.setData({
      [id]: value
    });
  },
  changeTime(e){
    console.log('作品时间',e);
    this.setData({
      'formData.time':e.detail.value
    });
  },

  bindMultiPickerChange: function (e) {
    //console.log('picker发送选择改变,携带值为', e.detail.value)
    const {value}=e.detail;
    //console.log(value);
    const {categoryIdPicker}=this.data;
    this.setData({
      categoryIdPickerValue: value,
      'formData.categoryId':categoryIdPicker[1][value[1]].id,
      categoryName:categoryIdPicker[1][value[1]].name
    });
  },
  bindMultiPickerColumnChange: function (e) {
    //console.log(e);
    const {column,value}=e.detail;
    const {categoryIdPicker,categoryList,categoryIdPickerValue}=this.data;

    if(column==0){
      categoryIdPicker[1]=categoryList[value].children;
      //categoryIdPickerValue[1]=0;
      this.setData({
        //categoryIdPickerValue:categoryIdPickerValue,
        categoryIdPicker:categoryIdPicker
      });
    };
  },



  /***
   * 保存数据
   * */
  saveData(e){
    const {status}=e.currentTarget.dataset;
    const {formData,categoryIdPickerValue,isSubmit}=this.data;
    //重复提交
    if(isSubmit){
      return
    }
    console.info(status)
    //状态暂存或者提交
    formData.isTemp=(status == 1?true:false);

    if (!this.WxValidate.checkForm(formData)) {
      const error = this.WxValidate.errorList[0];
      wx.showToast({
        title: error.msg,
        icon: 'none',
        duration: 2000
      })
      return false
    }
    //平面作品验证
    if(categoryIdPickerValue[0]==0){
      if (!this.WxValidatePM.checkForm(formData)) {
        const error = this.WxValidatePM.errorList[0];
        wx.showToast({
          title: error.msg,
          icon: 'none',
          duration: 2000
        })
        return false
      }
    }else{//立体作品
      if (formData.sizeMark!==""){

      }else if(!this.WxValidateLT.checkForm(formData)) {
        const error = this.WxValidateLT.errorList[0];
        wx.showToast({
          title: error.msg,
          icon: 'none',
          duration: 2000
        })
        return false
      }
    }
    formData.price = parseInt(formData.price * 100);
    this.setData({
      isSubmit:true,
    });
    if(formData.id){
      app.post(api.artUpdate,formData).then(res=>{
        this.setData({
          isSubmit:false,
        });
        wx.redirectTo({
          url:"/pages/user/myArtist/myArtist"
        });
      }).catch(()=>{
        this.setData({
          isSubmit:false,
        });
      })
    }else{
      app.post(api.artAdd,formData).then(res=>{
        this.setData({
          isSubmit:false,
        });
        wx.redirectTo({
          url:"/pages/user/myArtist/myArtist"
        });
      }).catch(()=>{
        this.setData({
          isSubmit:false,
        });
      })
    }
  },

  /**
   *预览图片
   ***/
  prevFile() {
    const {opusPicFile}=this.data;
    app.previewImg(opusPicFile.map(item=>{
      return item.url
    }));
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

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

  },

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

  },

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

  },

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

  },

  /**
   * 数字艺术品选中
   */
  digitalArtworkChange: function(event) {
    const index = parseInt(event.detail.value);
    const self = this;
    const value = self.data.digitalArtworkOptions.options[index].value;
    self.setData({
      ['formData.types']: value,
      ['digitalArtworkOptions.index']: index
    });
  }
})