// pages/tobeAgency/index.js
var QQMapWX = require("../../utils/qqmap-wx-jssdk.min.js");
const app = getApp();
import { customRequest } from '../../utils/request.js';
import { baseUrl } from '../../utils/request.js';
var qqmapsdk;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    locationObj: {
      provinceName: "",
      cityName: "",
      districtName: "",
    },
    serviceInfo: app.globalData.serviceInfo,
    iosDialogTobe: false, // 成为代理弹窗显示
    recording: false,
    loading: false,
    submitObj: {
      desp: "",
      userName: "",
      tel: "",
      companyName: "",
      companyPic: "",
      businessLicensePic: "",
      lat: "",
      lng: "",
      address: "",
    },
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad (options) {
    console.log(this.data.serviceInfo);
    qqmapsdk = new QQMapWX({
      key: "5PTBZ-YI7C6-MZGS3-ES7QN-4T5O2-EJFVR",
    });
    this.getApplyAgencyRecord();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady () { },

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

  /**
   * 地址选择
   *
   *
   */
  chooseMap: function () {
    var that = this;
    // wx.chooseLocation({
    wx.chooseLocation({
      success: function (res) {
        console.log("res", res);
        that.data.submitObj.lat = res.latitude;
        that.data.submitObj.lng = res.longitude;
        that.data.submitObj.address = res.name;
        qqmapsdk.reverseGeocoder({
          location: `${res.latitude},${res.longitude}`,
          success: function (res) {
            console.log(res.result);
            let address = res.result.address_component;
            that.data.submitObj.address = res.result.address;
            that.data.district = `${address.province} ${address.city} ${address.district}`;
            that.setData({
              submitObj: that.data.submitObj,
              district: that.data.district,
              locationObj: {
                provinceName: res.result.address_component.province,
                cityName: res.result.address_component.city,
                districtName: res.result.address_component.district,
              },
            });
          },
          fail: function (res) {
            console.log(res);
          },
        });
      },
      fail: function (e) {
        console.log(e);
      },
    });
  },
  showTobe () {
    this.setData({
      iosDialogTobe: true,
    });
  },
  closeTobe () {
    this.setData({
      iosDialogTobe: false,
    });
  },
  bothwayBind (e) {
    console.log(e);
    let type = `submitObj.${e.currentTarget.dataset.type}`;
    this.setData({
      [type]: e.detail.value,
    });
  },
  getApplyAgencyRecord () {
    let that = this;
    customRequest("/getApplyAgencyRecord", { header: 'headers', method: 'GET', data: {} }).then((res) => {
      if (res.data.status == 200) {
        if (res.data.data.record) {
          that.data.submitObj = res.data.data.record;
          that.setData({
            submitObj: that.data.submitObj,
            recording: true,
          });
        }
      }
    })
    // wx.request({
    //   url: app.globalData.ip + "/getApplyAgencyRecord",
    //   header: app.globalData.headers,
    //   success: function (res) {
    //     console.log(res);
    //     if (res.data.status == 200) {
    //       if (res.data.data.record) {
    //         that.data.submitObj = res.data.data.record;
    //         that.setData({
    //           submitObj: that.data.submitObj,
    //           recording: true,
    //         });
    //       }
    //     }
    //   },
    // });
  },
  submit (e) {
    console.log(e);
    let that = this

    if (e.detail.value.userName == "") {
      wx.showToast({
        title: "申请人名称不能为空",
        icon: "none",
        duration: 2000,
      });
      return;
    }
    if (e.detail.value.tel == "") {
      wx.showToast({
        title: "联系电话不能为空",
        icon: "none",
        duration: 2000,
      });
      return;
    }
    if (this.data.recording) return;
    if (this.data.loading == true) return
    wx.showLoading({
      title: '提交中',
    })
    this.data.loading = true
    let data = { creator: app.globalData.loginUserInfo.id, district: this.data.district, recordType: 2, ...this.data.submitObj };
    console.log('submit', data);
    wx.request({
      url: "https://admin.ibocai.com.cn/business/coop/add",
      method: "post",
      data,
      header: app.globalData.headers,
      success: function (res) {
        console.log(res);
        if (res.data.status == 200) {
          wx.showToast({
            title: "提交成功",
            icon: "success",
            duration: 2000,
            success () {
              setTimeout(() => {
                wx.navigateBack({
                  delta: 1,
                });
              }, 1000);
            },
          });
        } else if (res.data.status == 2002) {
          app.logout().then(() => {
            wx.reLaunch({
              url: "/pages/login/index",
            });
          });
        } else {
          wx.showToast({
            title: "提交失败,请重试",
            icon: "fail",
            duration: 2000,
          });
        }
        wx.hideLoading();
        that.data.loading = false
      },
    });
  },
  chooseImg (e) {
    console.log(e);
    let that = this;
    if (this.data.recording) return;
    wx.chooseMedia({
      count: 1,
      mediaType: ["image", "video"],
      sizeType: ["original", "compressed"],
      sourceType: ["album", "camera"],
      success (res) {
        // tempFilePath可以作为 img 标签的 src 属性显示图片
        wx.showLoading({
          title: "上传中...",
        });
        console.log(res);
        var currData = {};

        const tempFilePaths = res.tempFiles;
        tempFilePaths.forEach((item, index) => {
          wx.uploadFile({
            url: baseUrl + "/imgs/uploadImage",
            method: "post",
            // data:currData,
            // name: "uploadFile",
            filePath: tempFilePaths[index].tempFilePath,
            name: "uploadFile",
            header: app.globalData.headers,
            success: function (res) {
              if (e.currentTarget.dataset.type == "yyzz") {
                that.data.submitObj.businessLicensePic = JSON.parse(res.data).data;
              } else if (e.currentTarget.dataset.type == "mtzp") {
                that.data.submitObj.companyPic = JSON.parse(res.data).data;
              }
              // that.data.files.push({ url: JSON.parse(res.data).data, id: new Date().getTime() });
              that.setData({
                submitObj: that.data.submitObj,
              });
              // that.pushImg();
              setTimeout(() => {
                wx.hideLoading();
              }, 0);
              // that.updateImgs(currData.type,currData.fkId,currData.data.data);
            },
            fail: function (res) {
              console.log(res);

              setTimeout(() => {
                wx.hideLoading();
              }, 0);
            },
          });
          setTimeout(() => {
            wx.hideLoading();
          }, 0);
        });
      },
      fail (res) {
        if (res["errMsg"]) {
        }
        console.log(res);
      },
    });
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide () { },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload () { },

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

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

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage () {
    return app.sharePageImage()
  },
});
