// packageH/installationSever/installationSeverHome/installationSeverHome.js
var app = getApp();
var location = require("../../../mybehaviors/location/location");

Page({
  behaviors: [location],
  /**
   * 页面的初始数据
   */
  data: {
    active: 0,
    codeShow: false,
    codeText: "",
    pictureShow: false,
    pictureList: [],

    titleArr: [{
      code: "waitWorker",
      name: "抢单大厅",
    },
    {
      code: "all",
      name: "全部订单",
    },
    {
      code: "waitTake",
      name: "待取货订单",
    },
    {
      code: "waitDeliveryPay",
      name: "待到付订单",
    },
    {
      code: "waitInstall",
      name: "待安装订单",
    },
    {
      code: "refund",
      name: "售后订单",
    },
    {
      code: "isFinish",
      name: "已完成订单",
    },
    ],

    location: {},

    page: 1, //分页数，当前页数
    isLoadMore: true, //判断是否要加载更多的标志
    total_page: 0, //总页数
    listData: [],
    networkLoading: false,

    _order_id: 0,
    takeCodeImageUrl: "",
  },

  setCodeShow() {
    this.setData({
      codeShow: !this.data.codeShow,
    });
  },

  setPictureShow() {
    this.setData({
      pictureShow: !this.data.pictureShow,
    });
  },

  makePhoneCall(evt) {
    let mobile = evt.currentTarget.dataset.mobile;
    wx.makePhoneCall({
      phoneNumber: mobile,
    });
  },
  openLocation(evt) {
    let item = evt.currentTarget.dataset.item;
    wx.openLocation({
      latitude: Number(item.latitude),
      longitude: Number(item.longitude),
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // this.setData({
    // 	location:{longitude: '110.02', latitude: '110.2',address:'模拟地址'}
    // })
    // this.getListData();
    // return false;

    if (options.status) {
      this.setData({
        active: Number(options.status)
      });
    }
    this._getLocation((mapdata, e) => {
      this.setData({
        "location.latitude": e.lat,
        "location.longitude": e.lng,
        "location.address": mapdata.address,
      });
      this.getListData();
    });
  },

  initData() {
    this.setData({
      page: 1,
      total_page: 0,
      isLoadMore: true,
      networkLoading: false,
    });
  },

  getListData() {
    this.initData();
    let {
      titleArr,
      active,
      page,
      location
    } = this.data;
    let json = {
      code: titleArr[active].code,
      page,
      longitude: location.longitude,
      latitude: location.latitude
    };
    let urlStr = app.getNetAddresss("plugin.live-install.frontend.worker-order.orderList");
    app._postNetWork({
      url: urlStr,
      data: json,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result != 1) return app.tips(res.msg);
        this.data.total_page = res.data.last_page;
        if (!this.data.total_page) {
          this.data.total_page = 0;
        }
        if (res.data.another_name && res.data.another_name.worker_name) {
          wx.setNavigationBarTitle({
            title: res.data.another_name.worker_name
          });
        }

        this.setData({
          listData: res.data.data,
          networkLoading: true,
        });
        console.log(res);
      },
    });
  },
  //加载更多数据
  _getMoreData() {
    this.data.isLoadMore = false; // 防止多次请求分页数据
    if (this.data.page >= this.data.total_page) {
      // that.loading = true;
      return;
    } else {
      this.data.page += 1;
      let {
        titleArr,
        active,
        page,
        location
      } = this.data;
      let json = {
        code: titleArr[active].code,
        page,
        longitude: location.longitude,
        latitude: location.latitude
      };
      let urlStr = app.getNetAddresss("plugin.live-install.frontend.worker-order.orderList");
      app._postNetWork({
        url: urlStr,
        data: json,
        success: (resdata) => {
          let res = resdata.data;
          this.data.isLoadMore = true;
          if (res.result === 1) {
            let listData = this.data.listData.concat(res.data.data);
            this.setData({
              listData
            });
          } else {
            this.data.page = this.data.page - 1;
            this.data.isLoadMore = false;
          }
        },
      });
    }
  },

  async bindBtnClick(evt) {
    console.log(evt);
    let {
      index,
      btn,
      order_id
    } = evt.currentTarget.dataset;
    this.data._order_id = order_id;
    console.log(btn);
    //有些按钮需要弹窗二次确认
    if (btn.code == "installStart" || btn.code == "finishRefund" || btn.code == 'installStart') {
      let confirmFlag = await app.confirm(`确定${btn.name}?`);
      if (confirmFlag == false) return;
    } else if (btn.code == "workerChoose") {
      let confirmFlag = await app.confirm(`确定抢单吗？`);
      if (confirmFlag == false) return;
    }

    if (btn.code == "stateRefunding" || btn.code == "stateRefunded") return;
    if (btn.code == "installFinish") {
      this.setPictureShow();
      return;
    }
    let urlStr = app.getNetAddresss(btn.api);
    app._postNetWork({
      url: urlStr,
      data: {
        order_id,
        source: 2
      },
      success: (resdata) => {
        let res = resdata.data;
        if (res.result !== 1) return app.tips(res.msg);
        if (btn.code == "workerChoose") {
          //抢单的
          app.tips(res.msg);
          let listData = this.data.listData;
          listData.splice(index, 1);
          this.setData({
            listData
          });
        } else if (btn.code == "takeCode" || btn.code == "payCode") {
          let codeText = btn.code == "takeCode" ? "取货码" : "收款码";
          this.setData({
            takeCodeImageUrl: res.data,
            codeShow: true,
            codeText
          });
        } else if (btn.code == "installStart") {
          this.getListData();
        }
      },
    });
  },

  sendImageBtn() {
    let {
      pictureList,
      _order_id
    } = this.data;
    if (pictureList.length == 0) return app.tips("请上传安装图片");
    let urlStr = app.getNetAddresss("plugin.live-install.frontend.worker-order.finishInstall");
    app._postNetWork({
      url: urlStr,
      data: {
        order_id: _order_id,
        image: pictureList
      },
      success: (resdata) => {
        let res = resdata.data;
        if (res.result !== 1) return app.tips(res.msg);
        this.setPictureShow();
        this.setData({
          active: 5,
        });
        this.getListData();
      },
    });
  },

  gotoDetails(evt) {
    let {
      order_id
    } = evt.currentTarget.dataset;
    wx.navigateTo({
      url: "/packageH/installationSever/installationSeverDetail/installationSeverDetail?order_id=" + order_id,
    });
  },

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

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

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

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

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

  bindChangeActive(evt) {
    this.setData({
      active: evt.detail.index,
    });
    this.getListData();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.isLoadMore) {
      this._getMoreData();
    } else {
      console.log("没有更多数据");
    }
  },
  onRead_2() {
    wx.chooseImage({
      count: 9,
      sizeType: ["original", "compressed"],
      sourceType: ["album", "camera"],
      success: (res) => {
        // var tempFilePaths = res.tempFilePaths
        console.log(res.tempFilePaths);
        this.unload({
          tempFilePaths: res.tempFilePaths,
        });
      },
    });
  },
  //多张上传方法
  unload(data) {
    if (data.tempFilePaths.length == 0) return;
    wx.showLoading({
      title: "上传中",
    });
    let urlStr = app.getNetAddresss("upload.uploadPic");

    wx.uploadFile({
      url: urlStr,
      filePath: data.tempFilePaths[0],
      name: "file",
      formData: null,
      success: (resdata) => {
        var res = JSON.parse(resdata.data);
        let pictureList = this.data.pictureList;
        pictureList.push(res.data.img_url);
        this.setData({
          pictureList
        });
      },

      complete: (e) => {
        wx.hideLoading();
        data.tempFilePaths.shift();
        this.unload(data);
      },
    });
  },

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