// pages/createGoods/index.js
const app = getApp();
Page({

  data: {
    userInfo: wx.getStorageSync('userInfo'),
    mainImg: {
      filePath: "../../images/icons/add_img.png",
      isUpload: 0,
      uploadPath: "",
      type: "main",
      size: 0
    },
    cateTitle: "请选择商品分类",
    detailImg: [],
    detailImgCount: 0,
    cateList: [],
    cateValue: [],
    goodsInfo: {},
    radioList:[
      {
        "name":"营业额分成",
        "value":1,
        "checked":true
      },
      {
        "name":"利润分成",
        "value":2,
        "checked":false
      }
    ]
  },
  onLoad: function (options) {
    var id = options.id;
    var PageThis = this;
    PageThis.setData({
      userInfo:wx.getStorageSync('userInfo')
    })
    this.getGoodsInfo(id);
    this.getGoodsCate();
  },
  getGoodsInfo:function(id){
    var PageThis = this;
    wx.request({
      url: app.globalData.serverInfo.gateWayUrl,
      header: {
        'content-type': 'application/json'
      },
      method: 'POST',
      data: {
        api_name: "goods_detail",
        goods_id: id,
        login_manager_id: PageThis.data.userInfo.manager_id
      },
      success:function(ret){
        var data = ret.data.data;
        var imgList = data['g_pic']?JSON.parse(data['g_pic']):[];
        var radioList = PageThis.data.radioList;
        var detailImg = [];
        for(var i in imgList){
          var obj = {
            filePath:imgList[i],
            isUpload: 1,
            uploadPath: imgList[i],
            type: "detail",
          }
          detailImg.push(obj);
        }
        if(Number(data['g_money_type']) != 1){
          radioList[1].checked = true;
          radioList[0].checked = "";
        }
        PageThis.setData({
          goodsInfo:data,
          mainImg:{
            filePath: data['g_cover'],
            isUpload: 1,
            uploadPath: data['g_cover'],
            type: "main",
          },
          detailImg: detailImg,
          detailImgCount: detailImg.length,
          cateTitle: data['c_title'],
          radioList:radioList
        })
      }
    })
  },
  getGoodsCate: function () {
    var PageThis = this;
    wx.request({
      url: app.globalData.serverInfo.gateWayUrl,
      header: {
        'content-type': 'application/json'
      },
      method: 'POST',
      data: {
        api_name: "goods_cate",
        login_manager_id: PageThis.data.userInfo.manager_id
      },
      success: function (res) {
        var data = res.data.data;
        var cateList = [];
        for (var i in data) {
          cateList.push(data[i].c_title);
        }
        PageThis.setData({
          "cateValue": data,
          "cateList": cateList
        })
      }
    })
  },
  chooseImage: function (e) {
    var PageThis = this;
    var count = 1;
    var type = e.currentTarget.dataset.type;
    if (type == "detail") {
      count = 10 - PageThis.data.detailImg.length;
    }
    wx.chooseImage({
      count: count,
      sizeType: ['original'],
      sourceType: ['album'],
      success: function (res) {
        if (type == "main") {
          PageThis.setData({
            "mainImg": {
              "filePath": res.tempFiles[0].path,
              "isUpload": 0,
              "uploadPath": "",
              "type": "main",
              "size": res.tempFiles[0].size
            }
          })
        } else {
          var imgs = PageThis.data.detailImg;
          for (var i in res.tempFilePaths) {
            var obj = {
              "filePath": res.tempFiles[i].path,
              "isUpload": 0,
              "uploadPath": "",
              "type": "detail",
              "size": res.tempFiles[i].size,
            };
            imgs.push(obj);
          }
          PageThis.setData({
            "detailImg": imgs,
            "detailImgCount": PageThis.data.detailImgCount + res.tempFilePaths.length
          })
        }
      },
    })
  },
  delImage: function (e) {
    var PageThis = this;
    var name = e.currentTarget.dataset.name;
    var data = PageThis.data.detailImg;
    var new_data = [];
    var new_num = 0;
    for (var i in data) {
      if (data[i]['filePath'] != name) {
        new_data.push(data[i])
        new_num++;
      }
    }
    PageThis.setData({
      detailImg: new_data,
      detailImgCount: new_num
    })
  },
  inputChange: function (e) {
    var PageThis = this;
    var name = e.currentTarget.dataset.name;
    var data = PageThis.data.goodsInfo;
    data[name] = e.detail.value;
    PageThis.setData({
      "goodsInfo": data
    })
  },
  radioChange(e){
    var PageThis = this;
    var goodsInfo = PageThis.data.goodsInfo;
    goodsInfo['g_money_type'] = e.detail.value;
    PageThis.setData({
      "goodsInfo":goodsInfo
    })
  },
  cateChange: function (e) {
    var PageThis = this;
    var id = e.detail.value;
    var cateList = PageThis.data.cateList;
    var cateValue = PageThis.data.cateValue;
    var goodsInfo = PageThis.data.goodsInfo;
    for (var i in cateValue) {
      if (cateValue[i]['c_title'] == cateList[id]) {
        goodsInfo['g_cate_id'] = cateValue[i]['c_id']
      }
    }
    PageThis.setData({
      "cateTitle": cateList[id],
      "goodsInfo": goodsInfo
    })
  },
  uploadImgs: function () {
    var PageThis = this;
    var data = [PageThis.data.mainImg];
    var detailImg = PageThis.data.detailImg;
    for (var i in detailImg) {
      data.push(detailImg[i]);
    }
    wx.showToast({
      title: '图片上传中',
      icon: 'loading',
      duration: 99999
    })
    var img_interval = setInterval(function () {//轮询图片是否上传完成
      var flag = true;
      for (var i in data) {
        if (data[i].isUpload != 1) {
          flag = false;
        }
      }
      console.log(data);
      if (flag) {//没有未上传的，直接处理数据
        clearInterval(img_interval);
        var detailImgs = [];
        for (var i in data) {
          if (data[i]['type'] == "main") {
            PageThis.setData({
              "mainImg": data[i]
            })
          } else {
            detailImgs.push(data[i])
          }
        }
        PageThis.setData({
          "detailImg": detailImgs
        })
        console.log(detailImgs);
        wx.hideLoading();
        PageThis.createGood();
      }
    }, 500);
    for (var i in data) {
      if (data[i].isUpload != 1) {
        wx.uploadFile({
          url: app.globalData.serverInfo.uploadFileUrl,
          filePath: data[i].filePath,
          name: 'file',
          success: function (res) {
            res = JSON.parse(res.data);
            if (res.state == 1) {
              for (var j in data) {
                if (data[j].size == res.data.file_size) {
                  data[j]['isUpload'] = 1;
                  data[j]['uploadPath'] = res.data.file_url;
                }
              }
            } else {
              clearInterval(img_interval);
              wx.hideLoading();
              wx.showToast({
                title: '图片上传失败',
                icon: 'none',
                duration: 2000
              })
            }
          }
        })
      }
    }
  },
  createGood: function () {
    var PageThis = this;
    var goodsInfo = PageThis.data.goodsInfo;
    goodsInfo['g_cover'] = PageThis.data.mainImg.uploadPath;
    goodsInfo['g_pic'] = PageThis.data.detailImg;
    goodsInfo['api_name'] = "update_goods";
    goodsInfo['login_manager_id'] = PageThis.data.userInfo.manager_id
    wx.hideLoading()
    wx.request({
      url: app.globalData.serverInfo.gateWayUrl,
      header: {
        'content-type': 'application/json'
      },
      method: 'POST',
      data: goodsInfo,
      success: function (res) {
        res = res.data;
        if (Number(res.state) == 1) {
          wx.showToast({
            title: '保存成功',
            icon: 'success',
            duration: 2000,
            success: function () {
              wx.navigateBack({})
            }
          })
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  }
})