// pages/mine/wxml/release/release.js
const app = getApp();
var util = require('../../../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    array: [],
    payType: ['线上拍卖', '线下拍卖'],
    payTypeValue:"",
    index: 0,
    indexs: 0,
    pics: [],
    count: [],
    isShow: true,
    date: '',
    time: '',
    dates: '',
    imgData: [],
    display: false,
    close: true,
    delayed: "300",
    delayeddisabled: true,
    textareaVal: '',
    src: '',
    videoData: [],
    indexnew: 0,
    parameter: [{
      name: '',
      cont: ''
    }],
    formIdArray: [],
    onlineFlag:true,
    filename1:'',
    filename2:'',
    bidding_agreement_path:'',
    bidding_rules_path:''

  },
  bindPickerChangePay: function (e) {
    var index=e.detail.value;
    var payType = this.data.payType;
    if(index == 1){
      this.setData({
        payTypeValue: payType[index],
        onlineFlag:false
      })
    }else if(index == 0 ){
      this.setData({
        payTypeValue: payType[index],
        onlineFlag: true
      })
    }else {

    }
    

  },
  bindPickerChange: function(e) {
    let _this = this;
    if (_this.data.array[e.detail.value]) {
      _this.setData({
        arrays: _this.data.array[e.detail.value].value
      })
    }
    this.setData({
      index: e.detail.value
    })
  },
  bindPickerChanges: function(e) {
    this.setData({
      indexs: e.detail.value
    })
  },
  bindPickerChangenew: function(e) {
    this.setData({
      indexs: e.detail.value
    })
  },
  bindPickerChangenew: function(e) {
    this.setData({
      indexnew: e.detail.value
    })
  },
  bindTimeChange: function(e) {
    let _this = this;
    this.setData({
      time: e.detail.value
    }, () => {
      _this.verifyTime()
    })
  },
  bindDateChange: function(e) {
    let _this = this;
    this.setData({
      date: e.detail.value
    }, () => {
      _this.verifyTime()
    })
  },
  bindTimeChanges: function(e) {
    let _this = this;
    this.setData({
      times: e.detail.value
    }, () => {
      _this.verifyTime()
    })
  },
  bindDateChanges: function(e) {
    let _this = this;
    this.setData({
      dates: e.detail.value
    }, () => {
      _this.verifyTime()
    })
  },
  //验证开拍关拍时间
  verifyTime: function() {
    let _this = this;
    let stateDate = (_this.data.date + ' ' + _this.data.time).replace(/-/g, '/');
    let endDate = (_this.data.dates + ' ' + _this.data.times).replace(/-/g, '/');
    let statetimestamp = new Date(stateDate).getTime();
    let endtimestamp = new Date(endDate).getTime();
    if ((endtimestamp - statetimestamp) < 1800000) {
      var t = statetimestamp + 1800000
      _this.setData({
        endDate: util.formatTimeTwo(t, 'Y-M-D'),
        endTime: util.formatTimeTwo(t, 'h:m'),
        dates: util.formatTimeTwo(t, 'Y-M-D'),
        times: util.formatTimeTwo(t, 'h:m')
      });
    }
  },
  //拍卖按钮相应的隐藏与显示
  switchChange: function(e) {
    var _this = this;
    if (e.detail.value) {
      _this.setData({
        display: e.detail.value,
        close: false,
        delayed: "15",
        isLive: e.detail.value
      })
      if (_this.data.news.length > 0) {
        _this.setData({
          liveroom: _this.data.news[0].kid
        })
      } else {
        _this.setData({
          liveroom: ''
        })
      }
    } else {
      _this.setData({
        close: true,
        display: e.detail.value,
        delayed: "300",
        isLive: e.detail.value,
        liveroom: ""
      })
    }
  },

  //创建拍卖会
  establish: function() {
    var _this = this
    wx.request({
      url: app.globalData.prodUrl + 'web-pm/wx/pm/check_live_room',
      data: {
        shop_id: _this.data.shop_id
      },
      header: {
        'ydw-token': wx.getStorageSync('key').ydw_token
      },
      success: function(data) {
        if (data.data.success == true) {
          wx.navigateTo({
            url: '../establish/establish'
          })
        } else {
          wx.showModal({
            title: '提示',
            content: '一个店铺只能有一个拍卖会,您已有拍卖会',
            success: function(res) {
              if (res.confirm) {
                //'用户点击确定'
              } else if (res.cancel) {
                //'用户点击取消'
              }
            }
          })
        }
      },
    });
  },
  //上传图片
  chooseImage: function() {
    var _this = this,
      pics = this.data.pics;
    wx.chooseImage({
      count: 9 - pics.length, // 最多可以选择的图片张数，默认9
      sizeType: ['original', 'compressed'], // original 原图，compressed 压缩图，默认二者都有
      sourceType: ['album', 'camera'], // album 从相册选图，camera 使用相机，默认二者都有
      success: function(res) {
        // success
        for (var i = 0; i < res.tempFilePaths.length; i++) {
          wx.uploadFile({
            url: app.globalData.prodUrl + 'web-cp-all/upload_pm/upload',
            filePath: res.tempFilePaths[i],
            header: {
              'Content-Type': 'multipart/form-data'
            },
            formData: {
              method: 'POST'   //请求方式
            },
            name: 'file',
            success(res) {
              if (res.statusCode==200){
                _this.data.imgData.push(JSON.parse(res.data).file_id);
              }
            }
          })
        }

        var imgSrc = res.tempFilePaths;
        pics = pics.concat(imgSrc);
        // 控制触发添加图片的最多时隐藏
        if (pics.length >= 9) {
          _this.setData({
            isShow: (!_this.data.isShow)
          })
        } else {
          _this.setData({
            isShow: (_this.data.isShow)
          })
        }
        _this.setData({
          pics: pics
        })
      },
      fail: function() {
        // fail
      },
      complete: function() {
        // complete
      }
    })
  },
  // 图片预览
  previewImage: function(e) {
    var current = e.target.dataset.src
    wx.previewImage({
      current: current,
      urls: this.data.pics
    })
  },

  //上传视频

  chooseVideo: function() {
    var _this = this
    wx.chooseVideo({
      sourceType: ['album', 'camera'],
      maxDuration: 60,
      camera: 'back',
      success: function(res) {
        wx.uploadFile({
          url: app.globalData.prodUrl + 'web-cp-all/upload_pm/upload',
          filePath: res.tempFilePath,
          name: 'file',
          success(res) {
            _this.data.videoData.push(JSON.parse(res.data).file_id)
          }
        })
        _this.setData({
          src: res.tempFilePath
        });
      }
    });
  },
  upLoadAction1(e){
    var _this = this
    wx.chooseMessageFile({
      count: 1,
      type:'file',
      extension: ['pdf'],
      success(res){
        var size = res.tempFiles[0].size;
        var filename = res.tempFiles[0].name;
        var newfilename = filename + ""; 
        if (newfilename.indexOf(".pdf")==-1){ 
          wx.showToast({
          title: '请上传pdf文件',
          icon: "none",
          duration: 2000,
          mask: true
          })
         }else{
          _this.setData({
          filename1: filename    
          })

          wx.uploadFile({
            url: app.globalData.prodUrl + 'web-cp-all/upload_pm/upload/file',
            filePath: res.tempFiles[0].path,
            name: 'file',
            success(res) {
        
             _this.setData({
              bidding_agreement_path: JSON.parse(res.data).file_url    
              })
            }
          })
         }


      }
    })
  },
  upLoadAction2(e){
    var _this = this
    wx.chooseMessageFile({
      count: 1,
      type:'file',
      extension: ['pdf'],
      success(res){
        var size = res.tempFiles[0].size;
        var filename = res.tempFiles[0].name;
        var newfilename = filename + ""; 
        if (newfilename.indexOf(".pdf")==-1){ 
          wx.showToast({
          title: '请上传pdf文件',
          icon: "none",
          duration: 2000,
          mask: true
          })
         }else{
          _this.setData({
          filename2: filename    
          })

          wx.uploadFile({
            url: app.globalData.prodUrl + 'web-cp-all/upload_pm/upload/file',
            filePath: res.tempFiles[0].path,
            name: 'file',
            success(res) {
              _this.setData({
                bidding_rules_path: JSON.parse(res.data).file_url    
                })
            }
          })
         }


      }
    })
  },
  //上传
  formSubmit: function(e) {
    let _this = this;
    if (_this.data.formIdArray.length < 3) {
      _this.data.formIdArray.push(e.detail.formId);
    }
    if (_this.data.formIdArray.length === 3) {
      var date = e.detail.value.startdate + ' ' + e.detail.value.starttime;
      var endDate = e.detail.value.closingdate + ' ' + e.detail.value.closingtime;
      date = date.substring(0, 19);
      date = date.replace(/-/g, '/');
      endDate = endDate.substring(0, 19);
      endDate = endDate.replace(/-/g, '/');
      var timestamp = new Date(date).getTime();
      var timesend = new Date(endDate).getTime();
      if (_this.data.display) {
        var startTime = 0;
        var endTime = 0;
      } else {
        var startTime = timestamp;
        var endTime = timesend;
      }
      var auction_way = "";
      if (e.detail.value.payType == 0) {
        var price_start = Number(e.detail.value.start);
        var update_interval = Number(e.detail.value.delayed);
        var priceincrease=e.detail.value.priceincrease;
      } else if (e.detail.value.payType == 1) {
        var price_start = 0;
        var update_interval = 10;
        var priceincrease =0;
      }
      if (e.detail.value.checked == true) {
        auction_way = "拍卖会"
      } else {
        auction_way = "在线拍卖"
      };
      if (e.detail.value.name === undefined || e.detail.value.name === '') {
        wx.showToast({
          title: '未填写标题！',
          icon: 'none',
          duration: 2000
        });
      } else if (_this.data.textareaVal === "") {
        wx.showToast({
          title: '未填写拍品描述！',
          icon: 'none',
          duration: 2000
        });
      } else if (_this.data.isLive && _this.data.liveroom === '') {
        wx.showToast({
          title: '您没有选择拍卖会！',
          icon: 'none',
          duration: 2000
        });
      } else if (_this.data.isLive && !e.detail.value.auctioneer) {
        if (!e.detail.value.auctioneer) {
          wx.showToast({
            title: '未填写拍卖师！',
            icon: 'none',
            duration: 2000
          });
        }
      } else if (!_this.data.pics.length) {
        wx.showToast({
          title: '图片不可少于5张',
          icon: 'none',
          duration: 2000
        });
      } else if (price_start === "" || price_start === undefined) {
        wx.showToast({
          title: '未设置起拍价！',
          icon: 'none',
          duration: 2000
        });
      } else if (e.detail.value.bond === "" || e.detail.value.bond === undefined) {
        wx.showToast({
          title: '未设置保证金！',
          icon: 'none',
          duration: 2000
        });
      } else if (priceincrease === '' || priceincrease === undefined ) {
        wx.showToast({
          title: '未设置加价幅度！',
          icon: 'none',
          duration: 2000
        });
      } else if (update_interval === '' || update_interval === undefined) {
        wx.showToast({
          title: '未设置延时周期！',
          icon: 'none',
          duration: 2000
        });
      } else if (!_this.data.isLive && endTime - startTime < 1000 * 60 * 30) {
        wx.showToast({
          title: '拍卖时间不得小于30分钟',
          icon: 'none',
          duration: 2000
        })
      } else if (!_this.data.isLive && startTime < new Date().getTime()) {
        wx.showToast({
          title: '开拍时间不能晚于当前时间',
          icon: 'none',
          duration: 2000
        })
      } else if (e.detail.value.payType === '' || e.detail.value.payType === undefined) {
        wx.showToast({
          title: '请选择拍卖模式',
          icon: 'none',
          duration: 2000
        });
      } else{
        
        wx.request({
          url: app.globalData.prodUrl + 'web-pm/wx/pm/new_add_item',
          header: {
            'ydw-token': wx.getStorageSync('key').ydw_token
          },
          data: {
            bid_type: e.detail.value.choice,
            bid_from: e.detail.value.smalltaxonomy,
            item_name: e.detail.value.name,
            bid_content: e.detail.value.describe,
            bid_file_id: _this.data.imgData + '',
            price_start: price_start,
            price_guarantee: Number(e.detail.value.bond),
            price_add: Number(priceincrease),
            time_opening: Number(startTime),
            time_end: Number(endTime),
            auction_way: auction_way,
            shop_id: _this.data.shop_id,
            live_room_id: _this.data.liveroom,
            auctioneer: e.detail.value.auctioneer,
            update_interval: update_interval,
            form_id: _this.data.formIdArray[0],
            verify_form_id: _this.data.formIdArray[1],
            seller_bid_success_form_id: _this.data.formIdArray[2],
            video_file_id: _this.data.videoData + '',
            bid_parameter: JSON.stringify(_this.data.parameter),
            // 提交支付方式
            auction_type: e.detail.value.payType,
            bidding_agreement_path: _this.data.bidding_agreement_path,
            bidding_rules_path:_this.data.bidding_rules_path
          },
          success: function(data) {
            if (data.statusCode === 200) {
              wx.showToast({
                title: '发布成功！',
                icon: 'none',
                duration: 3000,
                success: function() {
                  setTimeout(function() {
                    wx.navigateBack({
                      delta: 1,
                      success: function() {

                      }
                    });
                  }, 2000)
                }
              });
            } else {
              wx.showToast({
                title: '网络出错，商品未发布成功！',
                icon: 'none',
                duration: 3000
              });
            };
          }
        })
      }
      _this.setData({
        formIdArray: []
      });

    }

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var _this = this;
    var currentDate = Date.parse(new Date());
    var endDate = currentDate + 1800000;
    var stateDate = util.formatTimeTwo(currentDate, 'Y-M-D');
    var stateTime = util.formatTimeTwo(currentDate, 'h:m:s');
    var defaultDate = util.formatTimeTwo(endDate, 'Y-M-D');
    var defaultTime = util.formatTimeTwo(endDate, 'h:m:s');
    _this.setData({
      currentDate: stateDate,
      currentTime: stateTime,
      endDate: defaultDate,
      endTime: defaultTime.substr(0, 5),
      date: stateDate,
      dates: defaultDate,
      time: stateTime.substr(0, 5),
      times: defaultTime.substr(0, 5),
      shop_id: options.shop_id
    });
    wx.request({
      url: app.globalData.prodUrl + 'web-pm/wx/pm/list_verify_pass',
      header: {
        'ydw-token': wx.getStorageSync('key').ydw_token
      },
      data: {
        shop_id: _this.data.shop_id
      },
      success: function(data) {
        if (data.data.data.length === 0) {
          _this.setData({
            news: []
          })
        } else {
          _this.setData({
            news: data.data.data
          })
        }

      },
    });
    wx.request({
      url: app.globalData.prodUrl + 'web-pm/wx/pm/list_item_classify',
      header: {
        'ydw-token': wx.getStorageSync('key').ydw_token
      },
      data: {
        shop_id: _this.data.shop_id
      },
      success: function(data) {
        _this.setData({
          array: data.data.data,
          arrays: data.data.data[0].value
        })
      },
    });
  },
  // 
  bindTextAreaBlur: function(e) {
    this.setData({
      textareaVal: e.detail.value
    })
  },
  /**添加自定义参数**/
  addParameter: function(e) {
    let _this = this;
    let parameter = _this.data.parameter;
    let obj = {
      name: '',
      cont: ''
    };
    parameter.push(obj);
    _this.setData({
      parameter: parameter
    })
  },
  /*获取参数内容*/
  setParameter: function(e) {
    let _this = this;
    let index = e.currentTarget.dataset.index;
    if (e.target.id === 'name') {
      _this.data.parameter[index].name = e.detail.value
    } else if (e.target.id === 'cont') {
      _this.data.parameter[index].cont = e.detail.value
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

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

  },

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

  },

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

  }
})