// packageE/appointment/client/make_appointment/make_appointment.js
var app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    showProjects: false,
    show1: false,
    id: 0,
    project_id: 0,
    project: {},
    store: [],
    chooseTechnician: {
      name: "",
    },
    result: "",
    activeNames: ["1"],
    times: [],
    calendarEvents: [],
    isRest: false,
    AStore: {},
    applyModel: {
      order_id: "",
      store_id: "",
      worker_id: "",
      customer_name: "",
      customer_tel: "",
      begin_time: "",
    },
    work_date: "",
    start_time: "",
    point: {},
    appointmentLang: {},
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.data.id = options.id;
    this.data.project_id = options.project_id;
    this.getData();
    this.getLocation();
    this.data.today =
      new Date().getFullYear() +
      "-" +
      (new Date().getMonth() + 1 >= 10
        ? new Date().getMonth() + 1
        : "0" + (new Date().getMonth() + 1)) +
      "-" +
      (new Date().getDate() >= 10
        ? new Date().getDate()
        : "0" + new Date().getDate());
    this.data.work_date = this.data.today;

    let yz_basic_info = wx.getStorageSync("yz_basic_info");
    this.setData({ appointmentLang: yz_basic_info.lang.appointment });
    console.log(yz_basic_info.lang);
    this.setAppointment(options);
  },

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

  setAppointment(options) {
    if (options.has_one_store) {
      this.setData({
        AStore: JSON.parse(options.has_one_store),
      });
    }
    if (options.store_id) {
      this.setData({
        "applyModel.store_id": options.store_id,
      });
    }
    if (options.has_one_worker) {
      this.setData({
        chooseTechnician: JSON.parse(options.has_one_worker),
      });
    }
  },

  closeProjects(evt) {
    this.setData({
      showProjects: !this.data.showProjects,
    });
  },

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

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},
  closeStore() {
    this.setData({
      show1: false,
    });
  },
  changeCollapse(event) {
    this.setData({
      activeNames: event.detail,
    });
  },

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

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},
  inputCustomerName(event) {
    console.log(event.detail.value);
    this.data.applyModel.customer_name = event.detail.value;
  },
  inputCustomerTel(event) {
    this.data.applyModel.customer_tel = event.detail.value;
  },
  inputRemark(event) {
    this.data.applyModel.remark = event.detail.value;
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},
  chooseStore(evt) {
    let item = evt.currentTarget.dataset.item;
    this.setData({
      AStore: item,
      "applyModel.store_id": item.id,
      show1: false,
      start_time: "",
      "chooseTechnician.name": "",
    });
  },

  toTime() {
    if (!this.data.applyModel.store_id) return this.tips("请先选择门店");
    this.setData({
      activeNames: ["1"],
    });
    this.getDate();
    this.getTime();
  },

  onchangeRadio(event) {
    console.log(event);
    this.setData({
      result: event.detail,
    });
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
  getDate() {
    let urlStr = app.getNetAddresss(
      "plugin.appointment.frontend.work-time.get-work-dates"
    );
    app._getNetWork({
      url: urlStr,
      data: {
        store_id: this.data.applyModel.store_id,
      },
      success: (resdata) => {
        let res = resdata.data;
        if (res.result !== 1) return this.tips(res.msg);

        let calendarEvents = res.data.map((item) => {
          if (item.work_date_format == this.data.today) {
            item.work_sattus == 1
              ? (this.data.isRest = true)
              : (this.data.isRest = false);
          }
          if (item.work_status == 1) {
            return item.work_date_format + "-休";
          } else {
            return item.work_date_format;
          }
        });
        this.setData({
          showProjects: true,
          calendarEvents,
        });
      },
    });
  },
  getTime() {
    let urlStr = app.getNetAddresss(
      "plugin.appointment.frontend.work-time.get-start-times"
    );
    app._getNetWork({
      url: urlStr,
      data: {
        store_id: this.data.applyModel.store_id,
      },
      success: (resdata) => {
        let res = resdata.data;
        if (res.result !== 1) return this.tips(res.msg);
        this.setData({
          times: res.data,
        });
      },
    });
  },
  getData() {
    let urlStr = app.getNetAddresss(
      "plugin.appointment.frontend.appointment-order.detail"
    );
    app._getNetWork({
      url: urlStr,
      data: {
        project_id: this.data.id,
      },
      success: (resdata) => {
        let res = resdata.data;
        if (res.result !== 1) return this.tips(res.msg);

        if (res.data.default_customer) {
          this.setData({
            "applyModel.customer_tel": res.data.default_customer.tel,
            "applyModel.customer_name": res.data.default_customer.name,
          });
        }
        this.setData({
          project: res.data.project,
        });
      },
    });
  },
  handSelect(e) {
    //if(this.data.work_date == e.detail.work_date) return;
    console.log(e);
    this.setData({
      work_date: e.detail.work_date,
      start_time: "",
      isRest: !e.detail.disabled,
    });
  },
  selectedTime(e) {
    this.setData({
      activeNames: false,
      start_time: e.currentTarget.dataset.time,
    });
    this.getTechnician();
  },
  clickTechnician(e) {
    this.setData({
      chooseTechnician: e.currentTarget.dataset.item,
    });
    console.log(e.currentTarget.dataset.item);
  },
  makeAppointment() {
    if (!this.data.start_time) return this.tips("请选择时间");
    if (!this.data.chooseTechnician.name)
      return this.tips("请选择" + this.data.appointmentLang.worker);
    if (!this.data.applyModel.customer_name) return this.tips("请填写姓名");
    if (!this.data.applyModel.customer_tel) return this.tips("请填写电话");

    this.data.applyModel.order_id = this.data.id;
    this.data.applyModel.worker_id = this.data.chooseTechnician.id;
    this.data.applyModel.begin_time =
      this.data.work_date + " " + this.data.start_time;
    let urlStr = app.getNetAddresss(
      "plugin.appointment.frontend.appointment-service.create-service"
    );
    app._postNetWork({
      url: urlStr,
      data: this.data.applyModel,
      success: (resdata) => {
        let res = resdata.data;
        if (res.result !== 1) return this.tips(res.msg);

        app.confirm('预约成功',()=>{
          wx.navigateBack();
        },false);
      },
    });
  },
  getTechnician() {
    let urlStr = app.getNetAddresss(
      "plugin.appointment.frontend.worker.get-appointment-workers"
    );
    app._getNetWork({
      url: urlStr,
      data: {
        store_id: this.data.applyModel.store_id,
        project_id: this.data.project_id,
        work_date: this.data.work_date,
        start_time: this.data.start_time,
      },
      success: (resdata) => {
        let res = resdata.data;
        if (res.result !== 1) return this.tips(res.msg);
        this.setData({
          technician: res.data,
        });
      },
    });
  },
  getStore() {
    if (!this.data.point.lng) {
      this.getLocation();
      return;
    }
    let urlStr = app.getNetAddresss(
      "plugin.appointment.frontend.store.get-list-by-project-id"
    );
    app._getNetWork({
      url: urlStr,
      data: {
        lng: this.data.point.lng,
        lat: this.data.point.lat,
        project_id: this.data.project_id,
      },
      success: (resdata) => {
        let res = resdata.data;
        if (res.result !== 1) return this.tips(res.msg);
        this.setData({
          store: res.data,
          show1: true,
        });
      },
    });
  },
  async getLocation() {
    // let userLocationFlag = await this.checkAlbum("scope.userLocation");
    wx.getLocation({
      type: "wgs84",
      success: (res) => {
        this.setData({
          "point.lat": res.latitude,
          "point.lng": res.longitude,
        });
      },
    });
  },
  checkAlbum(scopeName) {
    return new Promise(async (resolve, reject) => { // eslint-disable-line
      let writePhotosAlbum = await this.getAuthSetting(scopeName);
      if (!writePhotosAlbum) {
        wx.showModal({
          title: "请开启授权",
          content: "是否跳转设置页开启授权",
          success(res) {
            if (res.confirm) {
              wx.openSetting({
                success(settingdata) {
                  if (settingdata.authSetting[scopeName]) {
                    resolve(true);
                  } else {
                    resolve(false);
                  }
                },
              });
            } else if (res.cancel) {
              resolve(false);
            }
          },
          fail: () => {
            resolve(false);
          },
        });
      } else resolve(true);
    });
  },
  getAuthSetting(authName) {
    return new Promise((resolve, reject) => {
      wx.getSetting({
        success(res) {
          if (!res.authSetting[authName]) {
            wx.authorize({
              scope: authName,
              success() {
                resolve(true);
              },
              fail() {
                resolve(false);
              },
            });
          } else resolve(true);
        },
        fail() {
          resolve(false);
        },
      });
    });
  },

  tips(msg) {
    wx.showToast({
      title: msg,
      icon: "none",
      duration: 2000,
    });
    return false;
  },
});
