// pages/member/supplier/supplier.js
var app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    explainFlag: false,
    agreement: false,
    agreementText: '',
    startDate: new Date('1900-01-01'),
    msgText: 0,
    pass_safe: 0,
    showtips: true,
    supplier_status: -2,
    showAddress: false,
    supplier_info: "",
    isDiyForm: 0,
    form_id: '',
    types: {
      "88": 'diyusername',
      "99": 'diypassword',
      "0": 'diyinput',
      "1": 'diytextarea',
      "3": 'diycheckbox',
      "4": 'diyradio',
      "2": 'diyselect',
      "7": 'diydate',
      "9": 'diycity',
      "5": 'diyimage',
    },
    diydata: [],
    applyModel: {
      username: "",
      password: "",
      realname: "",
      mobile: "",
      product: "",
      remark: "",
      //省市区
      province_name: "",
      city_name: "",
      district_name: "",
      street_name: "",
      group_id:'',
      category_id:'',
      aptitude:[],
      identity: [],
    },
    setname: '',
    uploadUrl: 'upload.uploadPic',
    //地区
    provinceData: [],
    cityData: [],
    districtData: [],
    pickerValue: [0, 0, 0],
    selectAddressData: [],
    currentDate: new Date().getTime(),
    showCity1: false,
    isValidation: true,
    select:false,
    grouping_name:'请选择分组',
    grouping: [],
    up_aptitude:'',
    is_identity: '', // 是否验证身份证
    group_list:[],
    select_ind:false,
    industry_name:'请选择行业',
    industry: [],
    // imagesList: [],
    is_open_category:'',
    is_open_group:'',

    isShowStreet: false,
    districtVal: [],
    streetShow: false,

    // 身份证
    imagefile1: "",
    imagefile2: "",

    //自定义图片
    apply_page_banner:"",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //加载地址数据初始化
    this._initAddressInfo();
    this._getData();
    this.getApply();
  },
  bindGrouping() {
    this.setData({
      select: !this.data.select
    });
  },
  /**
 * 已选下拉框
 */
  selectGrouping(e) {
    console.log(e); 
    var name = e.currentTarget.dataset.datalist.title;
    this.data.applyModel.group_id =  e.currentTarget.dataset.datalist.id;
    this.setData({
      group_list:e.currentTarget.dataset.datalist,
      grouping_name: name,
      select: false,
      'applyModel.aptitude':[],
      up_aptitude: e.currentTarget.dataset.datalist.up_aptitude,
      is_identity: e.currentTarget.dataset.datalist.is_identity
    });
  },
  bindIndustry() {
    this.setData({
      select_ind: !this.data.select_ind
    });
  },
  /**
 * 已选下拉框
 */
  selectIndustry(e) {
    console.log(e);
    var name = e.currentTarget.dataset.datalist.title;
    this.data.applyModel.category_id =  e.currentTarget.dataset.datalist.id;
    this.setData({
      industry_name: name,
      select_ind: false
    });
  },
  del(e){
    var index = parseInt(e.target.dataset.index);
    let imagesList = this.data.applyModel.aptitude;
    imagesList.splice(index, 1);
    this.setData({
      'applyModel.aptitude':imagesList
    });
   
  },
  async bindUpImage() {
    let fileArray = await this.selectImage();
    console.log(fileArray,'sssss');
    let imagesList = this.data.applyModel.aptitude;
    for (let i = 0; i < fileArray.length; i++) {
      let data = await this.uploadImage(fileArray[i]);
      console.log(data,'data');
      imagesList.push(data.img_url);
      this.setData({
        'applyModel.aptitude':imagesList,
      });
    }
  },
  selectImage() {
    return new Promise((resolve, reject) => {
      wx.chooseImage({
        sizeType: ["original", "compressed"],
        sourceType: ["album", "camera"],
        success(res) {
          resolve(res.tempFilePaths);
        },
      });
    });
  },
  uploadImage(tempFile) {
    return new Promise((resolve, reject) => {
      wx.showLoading({
        title: "上传图片中",
      });
      let urlStr = app.getNetAddresss("upload.uploadPic");
      wx.uploadFile({
        url: urlStr,
        filePath: tempFile,
        name: "file",
        success(resdata) {
          var res = JSON.parse(resdata.data);
          if (res.result == 1) {
            resolve(res.data);
          } else {
            wx.showToast({
              icon: "none",
              title: res.msg,
              duration: 1500,
            });
          }
        },
        complete: () => {
          wx.hideLoading();
        },
      });
    });
  },

  // 获取申请数据
  getApply(){
    let that = this;
    let urlStr = app.getNetAddresss("plugin.supplier.supplier.controllers.apply.supplier-apply.index");
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            grouping: res.data.groups,
            industry:res.data.categorys,
            is_open_category:res.data.is_open_category,
            is_open_group:res.data.is_open_group
          });
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  changeAgreement(e) {
    this.setData({ agreement: e.detail });
  },
  setExplainFlag() {
    this.setData({
      explainFlag: !this.data.explainFlag
    });
  },

  //日期转化
  timestampToTime(timestamp) {

    var date = new Date(timestamp);
    let Y = date.getFullYear() + '-';
    let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    let D = this.change(date.getDate()) + ' ';
    return Y + M + D;
  },
  change(t) {
    if (t < 10) {
      return "0" + t;
    } else {
      return t;
    }
  },
  birthdayconfirm(e, time) {
    let that = this;
    let index = e.currentTarget.dataset.idex;
    let val = e.detail;
    that.setData({
      ["diydata[" + index + "].value"]: String(val).substring(0, 10),
      shoTime: that.timestampToTime(val),
      ["diydata[" + index + "].timeShow"]: false
    });
  },
  dateClose(e) {
    let index = e.currentTarget.dataset.idex;
    this.setData({
      ["diydata[" + index + "].timeShow"]: false
    });
  },
  //获取数据
  _getData() {
    let that = this;
    let urlStr = app.getNetAddresss("plugin.supplier.supplier.controllers.apply.supplier-apply");
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            supplier_status: res.data.status,
            pass_safe: res.data.safe,
            agreementText: res.data.agreement,
            apply_page_banner: res.data.apply_page_banner
          });
          if (that.data.supplier_status == 1) {
            if (res.data.is_open_region == "1") {
              that.setData({
                showAddress: true
              });
            }
            that.checkEnableDiyForm();
            that.setData({
              supplier_info: res.data.signature
            });
            return;
          }
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  //验证开启表单
  checkEnableDiyForm() {
    let that = this;
    let urlStr = app.getNetAddresss("plugin.supplier.supplier.controllers.apply.supplier-apply.is-enable-diyform");
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            supplier_status: 2,
            isDiyForm: 1,
            form_id: res.data.form_id,
          });
          that.getForm();
        } else {
          // wx.showToast({
          // 	icon: 'none',
          // 	title: res.msg,
          // 	duration: 1500
          // })
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  //获取表单信息
  getForm() {
    let that = this;
    let urlStr = app.getNetAddresss("plugin.diyform.api.diy-form.get-diy-form-by-id");
    urlStr += '&form_id=' + this.data.form_id;
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            diyform: res.data
          });
          let fields = that.data.diyform.fields;
          let diydata = that.data.diydata;
          let f = {};
          for (var field in fields) {
            console.log(fields[field].data_type);
            if (that.data.types[fields[field].data_type] == 'diycheckbox') {
              f = {
                name: field,
                data: fields[field],
                value: [],
                type: that.data.types[fields[field].data_type],
              };
            } else if (fields[field].data_type == '7') {
              var timestamp = Date.parse(new Date());
              var date = new Date(timestamp);
              var Y = date.getFullYear();
              var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
              var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();//获取当日日期
              console.log(Y + '-' + M + '-' + D);
              var isdatae = Y + '-' + M + '-' + D;
              f = {
                name: field,
                data: fields[field],
                value: '',
                type: that.data.types[fields[field].data_type],
                shoTime: app._isTextEmpty(fields[field].default_time) ? isdatae : fields[field].default_time
              };

            } else if (that.data.types[fields[field].data_type] == 'diyselect') {
              let tp_textArr = [];
              for (let i = 0; i < fields[field].tp_text.length; i++) {
                tp_textArr.push({
                  name: fields[field].tp_text[i]
                });
              }
              f = {
                name: field,
                data: fields[field],
                value: '',
                type: that.data.types[fields[field].data_type],
                diysishow: false,
                sitem: tp_textArr
              };
            } else if (that.data.types[fields[field].data_type] == 'diycity') {
              f = {
                name: field,
                data: fields[field],
                value: '',
                type: that.data.types[fields[field].data_type],
                showAdd: false
              };

            } else if (that.data.types[fields[field].data_type] == 'diydate') {
              f = {
                name: field,
                data: fields[field],
                value: '',
                type: that.data.types[fields[field].data_type],
                timeShow: false,
                currentDate: new Date().getTime()
              };
            } else if (that.data.types[fields[field].data_type] == 'diyimage') {
              f = {
                name: field,
                data: fields[field],
                imgUrls: [],
                isPhoto: false,
                type: that.data.types[fields[field].data_type],
              };

            } else {
              f = {
                name: field,
                data: fields[field],
                value: '',
                type: that.data.types[fields[field].data_type],
              };
            }
            diydata.push(f);
            that.setData({
              diydata: diydata
            });
          }

        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  //设置账号的值
  usernameinp(e) {
    let val = e.detail.value;
    this.setData({
      "applyModel.username": val
    });
  },
  //设置密码的值
  passwordinp(e) {
    let val = e.detail;
    this.setData({
      "applyModel.password": val
    });

    this.msgText = this.checkStrong(val);
    if (this.msgText == 3) {
      this.setData({
        'showtips': false
      });
    } else {
      this.setData({
        'showtips': true
      });
    }
  },
  checkStrong(sValue) {
    var modes = 0;
    //正则表达式验证符合要求的
    if (sValue.length < 1) return modes;
    if (/\d/.test(sValue)) modes++; //数字
    if (/[a-z]/.test(sValue)) modes++; //小写
    if (/[A-Z]/.test(sValue)) modes++; //大写
    // if (/\W/.test(sValue)) modes++; //特殊字符

    //逻辑处理
    // switch (modes) {
    //   case 1:
    //     return 1;
    //     break;
    //   case 2:
    //     return 2;
    //     break;
    //   case 3:
    //     return sValue.length < 8 ? 2 : 3;
    //     break;
    // }
    // return modes;
    if (modes == 1) {
      return 1;
    } else if (modes == 2) {
      return 2;
    } else {
      return sValue.length < 8 ? 2 : 3;
    }
  },
  //真实姓名的值
  realnameinp(e) {
    let val = e.detail.value;
    this.setData({
      "applyModel.realname": val
    });
  },
  //手机号码的值
  mobileinp(e) {
    let val = e.detail.value;
    this.setData({
      "applyModel.mobile": val
    });
  },
  //产品类型的值
  productinp(e) {
    let val = e.detail.value;
    this.setData({
      "applyModel.product": val
    });
  },
  //备注的值
  remarkinp(e) {
    let val = e.detail.value;
    this.setData({
      "applyModel.remark": val
    });
  },
  //自定义表单值绑定
  tpnameinp(e) {
    let val = e.detail.value;
    let idx = e.currentTarget.dataset.idex;
    this.setData({
      ["diydata[" + idx + "].value"]: val
    });
  },
  onRead_1(e) {
    let name = e.currentTarget.dataset.name;
    this.setData({
      setname: name
    });
    let that = this;
    let urlStr = app.getNetAddresss(this.data.uploadUrl);
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        const tempFilePaths = res.tempFilePaths;
        console.log(tempFilePaths[0]);
        wx.compressImage({
          src: tempFilePaths[0], // 图片路径
          quality: 60, // 压缩质量
          success(e) {
            let photourl = e.tempFilePath;
            wx.uploadFile({
              url: urlStr,
              filePath: photourl,
              name: 'file',
              formData: {
                attach: that.data.setname
              },
              success(resdata) {
                var res = JSON.parse(resdata.data);
                if (res.result == 1) {
                  let diydata = that.data.diydata;
                  for (var i = 0; i < diydata.length; i++) {
                    if (diydata[i].name == res.data.attach) {
                      diydata[i].imgUrls.push(res.data.img_url);
                    }
                  }
                  that.setData({
                    diydata: diydata
                  });
                } else {
                  wx.showToast({
                    icon: 'none',
                    title: res.msg,
                    duration: 1500
                  });
                }
              }
            });
          },
          fail(e) {

          },
          complete(e) {

          }
        });
      }
    });
  },
  upIdCard(evt) {
    let index = evt.currentTarget.dataset.index;
    let that = this;
    let urlStr = app.getNetAddresss("upload.uploadPic");
    wx.chooseImage({
      count: 1,
      sizeType: ["original", "compressed"],
      sourceType: ["album", "camera"],
      success(res) {
        const tempFilePaths = res.tempFilePaths;
        let photourl = tempFilePaths[0];
        wx.showLoading({
          title: "上传图片中",
        });
        wx.uploadFile({
          url: urlStr,
          filePath: photourl,
          name: "file",
          success(resdata) {
            wx.hideLoading();
            var res = JSON.parse(resdata.data);
            if (res.result != 1) {
              wx.showToast({
                icon: "none",
                title: res.msg,
                duration: 1500,
              });
              return false;
            }
            let target = "imagefile" + index;
            that.setData({
              [target]: res.data.img_url,
            });
          },
          fail () {
            wx.hideLoading();
          }
        });
      },
    });
  },
  removeImg: function(e) {
    let delIndex = e.currentTarget.dataset.indexc;
    let index_1 = e.currentTarget.dataset.index;
    let diydata = this.data.diydata;
    diydata[index_1].imgUrls.splice(delIndex, 1);
    this.setData({
      diydata: diydata
    });
  },
  diytextareainp(e) {
    let val = e.detail.value;
    let idx = e.currentTarget.dataset.idex;
    this.setData({
      ["diydata[" + idx + "].value"]: val
    });
  },
  checkboxinp(e) {
    let val = e.detail;
    let idx = e.currentTarget.dataset.idex;
    this.setData({
      ["diydata[" + idx + "].value"]: val
    });
  },
  diyselectBtn(e) {
    let idx = e.currentTarget.dataset.idex;
    this.setData({
      ["diydata[" + idx + "].diysishow"]: true
    });
  },
  sitemClose(e){
    let idx = e.currentTarget.dataset.idex;
    this.setData({
      ["diydata[" + idx + "].diysishow"]: false
    });
  },
  sitemSelectBtn(event){
    let idx = event.currentTarget.dataset.idex;
    this.setData({
      ["diydata[" + idx + "].value"]: event.detail.name,
      ["diydata[" + idx + "].diysishow"]: false
    });
  },
  raidinp(e) {
    let val = e.detail;
    let idx = e.currentTarget.dataset.idex;
    this.setData({
      ["diydata[" + idx + "].value"]: val
    });
  },
  //所在地选择显示
  showAddBtn(e) {
    let idx = e.currentTarget.dataset.idex;
    this.setData({
      ["diydata[" + idx + "].showAdd"]: true
    });
  },
  // 关闭选择收货地址
  _closeDateLw: function(e) {
    let idx = e.currentTarget.dataset.idex;
    this.setData({
      ["diydata[" + idx + "].showAdd"]: false
    });
  },
  //地址选择器数据初始化
  _initAddressInfo: function() {
    var that = this;
    var _keyName = 'provinceData';
    wx.getStorage({
      key: _keyName,
      success: function(res) {
        console.log("地址信息准备就绪");
        that._getProvinceData();
      },
      fail: function(res) {
        console.log("省fail");
        app._getNetWork({
          url: app.getNetAddresss("member.member-address.address"),
          success: function(res) {
            var response = res.data;
            var province = response.data.province;
            var city = response.data.city;
            var district = response.data.district;
            wx.setStorage({
              key: 'provinceData',
              data: province
            });
            wx.setStorage({
              key: 'cityData',
              data: city
            });
            wx.setStorage({
              key: 'districtData',
              data: district
            });
            that._initAddressInfo();
          },
          fail: function(res) {},
          state: true
        });
      }
    });
  },
  // 读取省key
  _getProvinceData: function() {
    var that = this;
    var _keyName = 'provinceData';
    wx.getStorage({
      key: _keyName,
      success: function(res) {
        console.log("省读取成功", res.data);
        that.setData({
          provinceData: res.data
        });
        that.setData({
          "selectAddressData[0].name": res.data[that.data.pickerValue[0]].areaname,
          "selectAddressData[0].id": res.data[that.data.pickerValue[0]].id,
          "selectAddressData[0].index": that.data.pickerValue[0]
        });
        that._getCityData();
      }
    });
  },
  // 读取城市key，筛选城市data
  _getCityData: function() {
    var _data = this.data.selectAddressData[0];
    console.log("城市", "_data", _data);
    var that = this;
    var _keyName = 'cityData';
    wx.getStorage({
      key: _keyName,
      success: function(res) {
        console.log("城市读取成功", res);

        var _json = [];
        for (var i = 0; i < res.data.length; i++) {
          if (res.data[i].parentid == _data.id) {
            _json.push(res.data[i]);
          }
        }
        console.log("城市数据筛选", _json);
        that.setData({
          cityData: _json
        });
        that.setData({
          "selectAddressData[1].name": _json[that.data.pickerValue[1]].areaname,
          "selectAddressData[1].id": _json[that.data.pickerValue[1]].id,
          "selectAddressData[1].index": that.data.pickerValue[1]
        });
        that._getDistrictData();
      }
    });
  },
  // 读取地区key，筛选地区data
  _getDistrictData: function () {
    var _data = this.data.selectAddressData[1];
    console.log("地区", "_data", _data);
    console.log(_data);
    var that = this;
    var _keyName = 'districtData';
    wx.getStorage({
      key: _keyName,
      success: function (res) {
        console.log("地区读取成功");
        var _json = [];
        for (var i = 0; i < res.data.length; i++) {
          if (res.data[i].parentid == _data.id) {
            _json.push(res.data[i]);
          }
        }
        console.log("地区数据筛选", _json);
        that.setData({
          districtData: _json
        });
        console.log("districtData", _json);
        that.setData({
          "selectAddressData[2].name": _json[that.data.pickerValue[2]].areaname,
          "selectAddressData[2].id": _json[that.data.pickerValue[2]].id,
          "selectAddressData[2].index": that.data.pickerValue[2]
        });
        console.log("over", that.data.selectAddressData);
      }
    });
  },
  // 收货地址滚动事件
  bindChange: function (e) {
    var val = e.detail.value;
    if (this.data.pickerValue[0] != val[0]) {
      val[1] = 0;
      val[2] = 0;
    }
    if (this.data.pickerValue[1] != val[1]) {
      val[2] = 0;
    }
    this.setData({
      "pickerValue[0]": val[0],
      "pickerValue[1]": val[1],
      "pickerValue[2]": val[2]
    });
    this._initAddressInfo();
  },
  //城市结果
  resultAdd: function (e) {
    let idx = e.currentTarget.dataset.idex;
    let seleData = this.data.selectAddressData;
    let retCity = seleData[0].name + ' ' + seleData[1].name + ' ' + seleData[2].name;
    this.setData({
      ["diydata[" + idx + "].value"]: retCity,
      ["diydata[" + idx + "].showAdd"]: false
    });
  },
  //自定义日期选择
  openPicker(e) {
    let idx = e.currentTarget.dataset.idex;
    this.setData({
      ["diydata[" + idx + "].timeShow"]: true
    });
  },
  _closeDateLw_1() {
    this.setData({
      'showCity1': false
    });
  },
  resultAdd_1() {
    let seleData = this.data.selectAddressData;
    this.setData({
      'applyModel.province_name': seleData[0].name,
      'applyModel.city_name': seleData[1].name,
      'applyModel.district_name': seleData[2].name,
      fullAddress: seleData[0].name + ' ' + seleData[1].name + ' ' + seleData[2].name,
      'showCity1': false,
      'applyModel.street_name': '',
      districtVal: [],
    });
    this._getStreet(seleData[2].id);
  },
  //获取街道
  _getStreet(param) {
    var that = this;
    let urlStr = app.getNetAddresss("member.memberAddress.street");
    urlStr += "&district_id=" + param;
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1 && !app._isTextEmpty(res.data)) {
          if (!app._isTextEmpty(res.data) && res.data.length > 0) {
            that.setData({
              districtVal: res.data,
              isShowStreet: true,
            });
          } else {
            that.setData({
              isShowStreet: false,
            });
          }
        } else {
          that.setData({
            isShowStreet: false,
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  // 显示街道选择框
  streetChoose() {
    if (app._isTextEmpty(this.data.fullAddress)) {
      wx.showToast({
        icon: "none",
        title: "请先选择所在地区",
        duration: 1500,
      });
    } else {
      this.setData({
        streetShow: true,
        opren: false,
      });
    }
  },

  //选择街道
  streetConfirm(e) {
    let strname = e.target.dataset.strname;
    this.setData({
      "applyModel.street_name": strname,
      streetShow: false,
    });
  },
  //关闭街道选择
  streetClose(e) {
    this.setData({
      streetShow: false,
      opren: true,
    });
  },
  //提交数据
  setApplyData() {
    if (app._isTextEmpty(this.data.applyModel.username)) {
      wx.showToast({
        icon: 'none',
        title: '请填写账号',
        duration: 1500
      });
      return;
    }

    if (app._isTextEmpty(this.data.applyModel.password)) {
      wx.showToast({
        icon: 'none',
        title: '请填写密码',
        duration: 1500
      });
      return;
    }

    if (this.data.msgText != 3 && this.data.pass_safe == 1) {
      wx.showToast({
        icon: 'none',
        title: '请正确填写密码',
        duration: 1500
      });
      return;
    }

    if (app._isTextEmpty(this.data.applyModel.realname)) {
      wx.showToast({
        icon: 'none',
        title: '请填写真实姓名',
        duration: 1500
      });
      return;
    }

    if (app._isTextEmpty(this.data.applyModel.mobile)) {
      wx.showToast({
        icon: 'none',
        title: '请填写手机号码',
        duration: 1500
      });
      return;
    }

    if (app._isMoblie(this.data.applyModel.mobile)) {
      wx.showToast({
        icon: 'none',
        title: '请输入正确的手机号',
        duration: 1500
      });
      return;
    }

    if (app._isTextEmpty(this.data.applyModel.product)) {
      wx.showToast({
        icon: 'none',
        title: '请填写产品类型',
        duration: 1500
      });
      return;
    }
    if (app._isTextEmpty(this.data.applyModel.group_id) && this.data.is_open_group === "1") {
      wx.showToast({
        icon: 'none',
        title: '请选择分组',
        duration: 1500
      });
      return;
    }
    if (app._isTextEmpty(this.data.applyModel.category_id) && this.data.is_open_category === "1") {
      wx.showToast({
        icon: 'none',
        title: '请选择行业',
        duration: 1500
      });
      return;
    }
    if (app._isTextEmpty(this.data.applyModel.aptitude ) && this.data.up_aptitude === 1) {
      wx.showToast({
        icon: 'none',
        title: '上传营业执照',
        duration: 1500
      });
      return;
    }
    if (this.data.is_identity === 1 && app._isTextEmpty(this.data.imagefile1) && app._isTextEmpty(this.data.imagefile2)) {
      wx.showToast({
        icon: 'none',
        title: '上传身份证',
        duration: 1500
      });
      return;
    }
    if (!this.data.agreement) {
      wx.showToast({
        icon: 'none',
        title: '请先阅读协议',
        duration: 1500
      });
      return;
    }
    this.data.applyModel.identity[0] = this.data.imagefile1;
    this.data.applyModel.identity[1] = this.data.imagefile2;
    let that = this;
    let urlStr = app.getNetAddresss("plugin.supplier.supplier.controllers.apply.supplier-apply.apply");
    urlStr += '&apply=' + JSON.stringify(this.data.applyModel);
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            supplier_status: res.data.status
          });
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  submit() {
    this.validation();
    if (!this.data.isValidation) {
      return;
    }
    if (!this.data.agreement) {
      wx.showToast({
        icon: 'none',
        title: '请先阅读协议',
        duration: 1500
      });
      return;
    }
    this.submitForm();
  },
  validation() {
    this.setData({
      isValidation: true
    });
    this.data.diydata.forEach(item => {
      if (item.data.tp_must == 1 && !item.value && item.type != 'diyimage') {
        wx.showToast({
          icon: 'none',
          title: item.data.tp_name + '必须填写哦',
          duration: 1500
        });
        this.setData({
          isValidation: false
        });
      }
      if (item.data.tp_must == 1 && item.type == 'diyimage') {
        if (item.imgUrls.length < item.data.tp_max) {
          wx.showToast({
            icon: 'none',
            title: item.data.tp_name + '必须上传' + item.data.tp_max + "张",
            duration: 1500
          });
          this.setData({
            isValidation: false
          });
        }
      }
      if (item.type == 'diycheckbox' && item.value.length == 0) {
        wx.showToast({
          icon: 'none',
          title: item.data.tp_name + '必须选择哦',
          duration: 1500
        });
        this.setData({
          isValidation: false
        });
      }
    });
  },
  //自定义表单提交
  submitForm() {
    var that = this;
    var formData = [];
    var formObject = {};
    this.data.diydata.forEach(item => {
      //图片类型的直接提交图片base64的数组到后台，其它直接传值
      if (item.type == 'diyimage') {
        formObject[item.name] = item.imgUrls;
      } else {
        formObject[item.name] = item.value;
      }
    });
    formData.push(formObject);
    let json = {
      form_id: this.data.form_id,
      form_data: formData
    };
    let urlStr = app.getNetAddresss("plugin.diyform.api.diy-form.save-diy-form-data");
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: json,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.submitApplyByForm(res.data.form_data_id);
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) { }
    });
  },
  submitApplyByForm(fromId) {
    // let that = this;
    let urlStr = app.getNetAddresss("plugin.supplier.supplier.controllers.apply.supplier-apply.apply");
    urlStr += '&form_data_id=' + fromId;
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 1500,
            success: function () {
              setTimeout(function () {
                //要延时执行的代码
                wx.navigateBack({
                  delta: 1
                });
              }, 1500); //延迟时间
            },
          });
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  showCity1btn() {
    this.setData({
      showCity1: true
    });
  },
  goHome() {
    wx.reLaunch({
      url: '/packageG/index/index'
    });
  },
  // 预览
  previewImage: function (e) {
    // var current = e.target.dataset; // 这里获取到的是一张本地的图片
    wx.previewImage({
      current: e.target.dataset.src, // 需要预览的图片链接列表
      urls: e.target.dataset.srcList // 当前显示图片的链接
    });
  },
});
