// packageD/auction/auctioneer-publish/publish_first/publish_first.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    form: {
      title: '',
      sku: '',
      // 拍品图片
      thumb: '',
      // 其他图片
      thumb_url: [],
      // 拍品详情图片
      content: '',
      // 备注
      describe: '',
      // 属性名
      // param_title:'',
      //属性值
      // param_value:''
    },
    // 属性弹窗
    showphone: false,
    // 服务协议
    checkXy: true,
    checkXy_show: false,
    protocol: '',
    // 属性数组
    paramArr: [],
    param_title: [],
    param_value: [],
    uploadUrl: 'upload.uploadPic',
    // 分类数组
    sectionOptions: [],
    newoptions: [],
    // 显示分类
    addressShow: false,
    one: 0,
    two: 0,
    pickerValue: [0, 0, 0],
    selectedOptions3: []
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.good) {
      this.setData({
        "form.goods_id": options.good
      });
      this.getInfo();
    }
    this.getAgreement();
    this.getJson();
    
  },
  onClicksQ() {
    this.setData({
      checkXy_show: false
    });
  },
  onClicks() {
    this.setData({
      checkXy_show: true
    });
  },
  // 删除拍品图片
  delThumb(e) {
    let del = e.currentTarget.id;
    if (del == 0) {
      this.setData({
        "form.thumb": ''
      });
    }
  },
  delcontent(e) {
    let del = e.currentTarget.id;
    if (del == 0) {
      this.setData({
        "form.content": ''
      });
    }
  },
  delthumb_url(e) {
    let del = e.currentTarget.id;
    if (del == 0) {
      this.setData({
        "form.thumb_url": ''
      });
    }
  },
  Chooseinp() {
    this.setData({
      checkXy: !this.data.checkXy
    });
  },
  calshow() {
    this.setData({
      showphone: false
    });
  },
  //删除已添加的属性 
  delShuxing(e) {
    console.log(e.currentTarget.dataset.ind);
    let ind = e.currentTarget.dataset.ind;
    if (ind == 0) {
      this.setData({
        paramArr: []
      });
      return;
    }
    this.data.paramArr.splice(ind, 1);
  },
  pushAttr() {
    if (app._isTextEmpty(this.data.param_title)) {
      wx.showToast({
        title: '请填写属性名',
        icon: 'none',
        duration: 1000
      });
      return;
    }
    if (app._isTextEmpty(this.data.param_value)) {
      wx.showToast({
        title: '请填写属性值',
        icon: 'none',
        duration: 1000
      });
      return;
    }
    let json = {
      attrname: this.data.param_value,
      attrvalue: this.data.param_title
    };
    let sarr = this.data.paramArr;
    sarr.push(json);
    this.setData({
      paramArr: sarr,
      showphone: false
    });
  },
  // 属性值
  attrvalue(e) {
    this.setData({
      param_value: e.detail.value
    });
  },
  // 属性名
  attrname(e) {
    this.setData({
      param_title: e.detail.value
    });
  },
  isCoverLayer(e) {
    this.setData({
      showphone: false
    });
  },
  tapSx(e) {
    this.setData({
      showphone: true,
      param_title: '',
      param_value: ''
    });
  },
  title(e) {
    this.setData({
      "form.title": e.detail.value
    });
  },
  sku(e) {
    this.setData({
      "form.sku": e.detail.value
    });
  },
  stock(e){
    this.setData({
      "form.stock":e.detail.value
    });
  },
  remarkinp(e) {
    this.setData({
      "form.describe": e.detail.value
    });
  },
  upLoad_1() {
    let that = this;
    let urlStr = app.getNetAddresss(that.data.uploadUrl);
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        const tempFilePaths = res.tempFilePaths;
        console.log(tempFilePaths);
        let photourl = tempFilePaths[0];
        wx.uploadFile({
          url: urlStr,
          filePath: photourl,
          name: 'file',
          success(resdata) {
            var res = JSON.parse(resdata.data);
            if (res.result == 1) {
              that.setData({
                "form.thumb": res.data.img_url,
              });
            } else {
              wx.showToast({
                icon: 'none',
                title: res.msg,
                duration: 1500
              });
            }
          }
        });
      }
    });
  },
  upLoad_2() {
    let that = this;
    let ig = '1';
    wx.chooseImage({
      count: 9,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        console.log(res.tempFilePaths);
        that.unload({
          tempFilePaths: res.tempFilePaths
        }, ig);
      }
    });
  },
  upLoad_3() {
    let that = this;
    let urlStr = app.getNetAddresss(that.data.uploadUrl);
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        const tempFilePaths = res.tempFilePaths;
        console.log(tempFilePaths);
        let photourl = tempFilePaths[0];
        wx.uploadFile({
          url: urlStr,
          filePath: photourl,
          name: 'file',
          success(resdata) {
            var res = JSON.parse(resdata.data);
            if (res.result == 1) {
              that.setData({
                "form.content": res.data.img_url,
              });
            } else {
              wx.showToast({
                icon: 'none',
                title: res.msg,
                duration: 1500
              });
            }
          }
        });
      }
    });
  },
  //多张上传方法  1
  unload(data, ig) {
    let urlStr = app.getNetAddresss(this.data.uploadUrl);
    var that = this,
      i = data.i ? data.i : 0,
      success = data.success ? data.success : 0,
      fail = data.fail ? data.fail : 0;
    wx.uploadFile({
      url: urlStr,
      filePath: data.tempFilePaths[i],
      name: 'file',
      formData: null,
      success(resdata) {
        var res = JSON.parse(resdata.data);
        that.setData({
          "form.thumb_url": that.data.form.thumb_url.concat(res.data.img_url)
        });
        console.log(that.data.form.thumb_url);
      },
      fail(e) {
        fail++;
      },
      complete(e) {
        i++;
        if (i == data.tempFilePaths.length) { //当图片传完时，停止调用     
          console.log('执行完毕');
          console.log('成功：' + success + " 失败：" + fail);
        } else { //若图片还没有传完，则继续调用函数
          data.i = i;
          data.success = success;
          data.fail = fail;
          that.unload(data, ig); //递归，回调自己
        }
      }
    });
  },

  // 获取分类信息
  getJson() {
    let that = this;
    let json = {
      art: 'getGoodsCategory'
    };
    let urlStr = app.getNetAddresss('plugin.auction.api.index.getAuctionData');
    app._getNetWork({
      url: urlStr,
      data: json,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          for (let i = 0; i < res.data.getGoodsCategory.length; i++) {
            that.data.sectionOptions.push({
              id: res.data.getGoodsCategory[i].id,
              value: res.data.getGoodsCategory[i].id,
              label: res.data.getGoodsCategory[i].name,
              children: []
            });
            for (let k = 0; k < res.data.getGoodsCategory[i].childrens.length; k++) {
              that.data.sectionOptions[i].children.push({
                id: res.data.getGoodsCategory[i].childrens[k].id,
                value: res.data.getGoodsCategory[i].childrens[k].id,
                label: res.data.getGoodsCategory[i].childrens[k].name,
                childrens: []
              });
              if(that.data.cat_level == 3){
                for (let a = 0; a < res.data.getGoodsCategory[i].childrens[k].childrens.length; a++) {
                  that.data.sectionOptions[i].children[k].childrens.push({
                    id: res.data.getGoodsCategory[i].childrens[k].childrens[a].id,
                    value: res.data.getGoodsCategory[i].childrens[k].childrens[a].id,
                    label: res.data.getGoodsCategory[i].childrens[k].childrens[a].name,
                  });
                }
              }
            }
          }
          that.setData({
            sectionOptions: that.data.sectionOptions
          });
          console.log(that.data.sectionOptions);
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
            duration: 1000
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  // 选择方法
  bindChange(e) {
    var val = e.detail.value;
    this.setData({
      one: val[0],
      two: val[1],
      "pickerValue[0]": val[0],
      "pickerValue[1]": val[1],
      "pickerValue[2]": val[2]
    });
  },
  // 选择取消
  _closeDateLw() {
    this.setData({
      addressShow: false
    });
  },
  resultAdd() {
    // selectedOptions3
    this.data.selectedOptions3.push(this.data.sectionOptions[this.data.pickerValue[0]].id);
    if (this.data.sectionOptions[this.data.pickerValue[0]].children[this.data.pickerValue[1]]) {
      this.data.selectedOptions3.push(this.data.sectionOptions[this.data.pickerValue[0]].children[this.data.pickerValue[1]].id);
      if(this.data.sectionOptions[this.data.pickerValue[0]].children[this.data.pickerValue[1]].childrens[this.data.pickerValue[2]]){
        this.data.selectedOptions3.push(this.data.sectionOptions[this.data.pickerValue[0]].children[this.data.pickerValue[1]].childrens[this.data.pickerValue[2]].id);
      }
      console.log(this.data.selectedOptions3);
      this.setData({
        selectedOptions3: this.data.selectedOptions3,
        addressShow: false
      });
    } else {
      wx.showToast({
        title: '至少要选择二级分类',
        icon: 'none',
        duration: 1000
      });
      this.setData({
        addressShow: false
      });
    }

    // this.data.selectedOptions3.push(this.data.sectionOptions[this.data.pickerValue[0]].children[this.data.pickerValue[1]].id)
    // this.data.selectedOptions3.push(this.data.sectionOptions[this.data.pickerValue[0]].children[this.data.pickerValue[1]].childrens[this.data.pickerValue[2]].id)

  },
  xuanzefenl() {
    this.setData({
      addressShow: true,
      selectedOptions3: []
    });
  },
  nextbox() {
    if (app._isTextEmpty(this.data.form.title)) {
      wx.showToast({
        title: '请输入拍品单位',
        icon: 'none',
        duration: 1000
      });
      return;
    }
    if (app._isTextEmpty(this.data.form.sku)) {
      wx.showToast({
        title: '请输入拍品单位',
        icon: 'none',
        duration: 1000
      });
      return;
    }
    if (this.data.selectedOptions3.length <= 0) {
      wx.showToast({
        title: '请选择商品分类',
        icon: 'none',
        duration: 1000
      });
      return;
    }
    if (app._isTextEmpty(this.data.form.thumb)) {
      wx.showToast({
        title: '请上传拍品图片',
        icon: 'none',
        duration: 1000
      });
      return;
    }
    if (!this.data.checkXy) {
      wx.showToast({
        title: '请同意竞拍服务协议',
        icon: 'none',
        duration: 1000
      });
      return;
    } else {
      console.log(this.data.paramArr);
      let json = {
        from: this.data.form,
        param_title: this.data.paramArr.length > 0 ? JSON.stringify(this.data.paramArr.map((item) => {
          return item.attrvalue;
        })) : JSON.stringify([]),
        param_value: this.data.paramArr.length > 0 ? JSON.stringify(this.data.paramArr.map((item) => {
          return item.attrname;
        })) : JSON.stringify([]),
        category: JSON.stringify([this.data.selectedOptions3])
      };
      console.log(JSON.stringify(json));
      let sjson = JSON.stringify(json);
      if (this.data.form.goods_id) {
        // 是编辑
        console.log('是编辑');
        wx.navigateTo({
          url: '/packageD/auction/auctioneer-publish/publish_second/publish_second?json=' + sjson + "&&goods_id=" + this.data.form.goods_id,
        });
      } else {
        console.log('是发布');
        wx.navigateTo({
          url: '/packageD/auction/auctioneer-publish/publish_second/publish_second?json=' + sjson,
        });
      }
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

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

  },

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

  },

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

  },

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

  },

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

  },

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

  },
  // 获取协议
  getAgreement() {
    var that = this;
    let urlStr = app.getNetAddresss('plugin.auction.api.index.getAuctionData');
    app._postNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          console.log(res);
          that.setData({
            protocol: res.data.getAgreement.protocol,
            cat_level:res.data.getAgreement.cat_level
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
            duration: 1000
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  // 编辑
  getInfo() {
    var that = this;
    let urlStr = app.getNetAddresss('plugin.auction.api.index.getAuctionData');
    let json = {
      art: 'editGoods',
      goods_id: this.data.form.goods_id
    };
    app._getNetWork({
      url: urlStr,
      data: json,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          let ars = that.data.paramArr;
          res.data.editGoods.has_many_params.forEach((item, index, key) => {
            let obj = {};
            obj.attrvalue = item.value;
            obj.attrname = item.title;
            ars.push(obj);
          });
          that.setData({
            "form.title": res.data.editGoods.title,
            "form.sku": res.data.editGoods.sku,
            "form.thumb": res.data.editGoods.thumb,
            "form.describe": res.data.editGoods.has_one_auction_goods.describe,
            "form.content": res.data.editGoods.content,
            "form.thumb_url": res.data.editGoods.thumb_url,
            "form.stock": res.data.editGoods.stock,
            paramArr: ars,
            selectedOptions3: res.data.editGoods.has_many_goods_category[0].category_ids.split(','),

          });
          console.log(that.data);

        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
            duration: 1000
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  }
});