// packageE/appointment/manager/add_technician.js
var app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    text_id: "",
    appointmentLang: {},
    showMember: false,
    show: false,
    applyModel: {
      description: "",
      member_u_id: "",
      name: "",
      project_ids: [],
      thumb: "",
      worker_content: [],
      worker_id: "",
    },
    uploadUrl: "upload.uploadPic",
    usetName: "",
    // appointmentLang: "",
    swlist: [],
    // store_id:'40',
    // worker_id: 9
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.worker_id) {
      this.setData({
        worker_id: options.worker_id,
      });
    }
    if (options.store_id) {
      this.setData({
        store_id: options.store_id,
      });
    }
    if (this.data.worker_id) {
      this.GeteditTechnician();
    }
    try {
      let info = wx.getStorageSync("yz_basic_info");
      if (info) {
        this.setData({
          appointmentLang: info.lang.appointment,
        });
        if (options.worker_id) {
          wx.setNavigationBarTitle({
            title: `编辑${info.lang.appointment.worker}`,
          });
        } else {
          wx.setNavigationBarTitle({
            title: `添加${info.lang.appointment.worker}`,
          });
        }
      }
    } catch (err) {
      console.log(err);
    }

    console.log(info);
  },
  // 删除图片
  removeImg(e) {
    console.log(this.data.applyModel, e);
    let info = this.data.applyModel.worker_content;
    let ind = e.currentTarget.dataset.ind;
    info.splice(ind, 1);
    console.log(info);
    this.setData({
      "applyModel.worker_content": info,
    });
  },
  description_inp(e) {
    console.log(e);
    this.setData({
      "applyModel.description": e.detail.value,
    });
  },
  chooseMember(e) {
    let tapSelect = e.currentTarget.dataset.up;
    if (tapSelect == "up") {
      this.setData({
        leader_uid: `${e.currentTarget.dataset.item.nickname}(id:${e.currentTarget.dataset.item.uid})`,
        "applyModel.leader_uid": e.currentTarget.dataset.item.uid,
        showUPMember: false,
      });
    } else {
      this.setData({
        text_id: `${e.currentTarget.dataset.item.nickname}(id:${e.currentTarget.dataset.item.uid})`,
        "applyModel.member_u_id": e.currentTarget.dataset.item.uid,
        showMember: false,
      });
    }
  },
  getMember(e) {
    let str = e.currentTarget.dataset.up;
    let json = {};
    if (str === "money") {
      this.setData({
        "applyModel.leader_commission": e.detail.value,
      });
      return;
    }
    var that = this;
    let urlStr = app.getNetAddresss(
      "plugin.appointment.frontend.member.query-list"
    );
    app._getNetWork({
      url: urlStr,
      data: {
        keyword: e.detail.value,
      },
      success: (resdata) => {
        var res = resdata.data;
        console.log(res.data);
        if (res.result == 1) {
          let member = res.data;
          that.setData({
            member: res.data,
          });
          if (member.length > 0) {
            if (str === "up") {
              that.setData({
                showUPMember: true,
              });
            } else {
              that.setData({
                showMember: true,
              });
            }
          }
        } else {
          if (str === "up") {
            that.setData({
              showUPMember: true,
            });
          } else {
            that.setData({
              showMember: true,
            });
          }
          that.setData({
            member: [],
          });
        }
      },
    });
    console.log(json);
  },
  getMember_name(e) {
    let name = e.detail.value;
    this.setData({
      "applyModel.name": name,
    });
  },
  showUPMemberTap(e) {
    console.log(e);
  },
  showUPMemberTap_name(e) {
    // console.log(e)
  },
  //选择图片
  onRead() {
    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;
        let photourl = tempFilePaths[0];
        wx.uploadFile({
          url: urlStr,
          filePath: photourl,
          name: "file",
          success(resdata) {
            var res = JSON.parse(resdata.data);
            if (res.result == 1) {
              console.log(res.data);
              that.setData({
                "applyModel.thumb": res.data.img_url,
              });
            } else {
              wx.showToast({
                icon: "none",
                title: res.msg,
                duration: 1500,
              });
            }
          },
        });
      },
    });
  },
  // 多图上传方法
  onRead_2() {
    let that = this;
    // let urlStr = app.getNetAddresss(this.data.uploadUrl);
    let ig = "1";
    wx.chooseImage({
      count: 9,
      sizeType: ["original", "compressed"],
      sourceType: ["album", "camera"],
      success(res) {
        // var tempFilePaths = res.tempFilePaths
        console.log(res.tempFilePaths);
        that.unload(
          {
            tempFilePaths: res.tempFilePaths,
          },
          ig
        );
      },
    });
  },
  //多张上传方法
  unload(data, ig) {
    console.log(ig);
    let urlStr = app.getNetAddresss(this.data.uploadUrl);
    var that = this,
      i = data.i ? data.i : 0,
      success = data.success ? data.success : 0,
      fail = data.fail ? data.fail : 0;
    wx.uploadFile({
      url: urlStr,
      filePath: data.tempFilePaths[i],
      name: "file",
      formData: null,
      success(resdata) {
        var res = JSON.parse(resdata.data);
        console.log(res.data.img_url);
        if (ig == "1") {
          that.data.swlist.push(res.data.img_url);
          that.setData({
            // showpaths: that.data.swlist,
            "applyModel.worker_content": that.data.swlist,
          });
        } else if (ig == 2) {
          that.data.swlis.push(res.data.img_url);
          that.setData({
            // showpaths_two: that.data.swlis,
            "applyModel.worker_content": that.data.swlis,
          });
        }

        console.log(that.data.applyModel);
      },
      fail(e) {
        fail++;
      },
      complete(e) {
        i++;
        if (i == data.tempFilePaths.length) {
          //当图片传完时，停止调用
          console.log("执行完毕");
          console.log("成功：" + success + " 失败：" + fail);
        } else {
          //若图片还没有传完，则继续调用函数
          data.i = i;
          data.success = success;
          data.fail = fail;
          that.unload(data, ig); //递归，回调自己
        }
      },
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

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

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

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

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

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

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
  // 添加
  addTechnician(e) {
    console.log(this.data.applyModel);
    let applyModel = this.data.applyModel;
    if (
      app._isTextEmpty(applyModel.member_u_id) &&
      app._isTextEmpty(applyModel.leader_uid)
    ) {
      wx.showToast({
        title: `${this.data.appointmentLang.worker}会员ID/昵称不能为空`,
        duration: 1000,
        icon: "none",
      });
      return;
    }
    if (app._isTextEmpty(applyModel.name)) {
      wx.showToast({
        title: `${this.data.appointmentLang.worker}姓名不能为空`,
        duration: 1000,
        icon: "none",
      });
      return;
    }
    if (applyModel.project_ids.length <= 0) {
      wx.showToast({
        title: `关联${this.data.appointmentLang.project}不能为空`,
        duration: 1000,
        icon: "none",
      });
      return;
    }
    if (applyModel.worker_content.length <= 0) {
      wx.showToast({
        title: `${this.data.appointmentLang.worker}介绍不能为空`,
        duration: 1000,
        icon: "none",
      });
      return;
    }
    if (app._isTextEmpty(applyModel.thumb)) {
      wx.showToast({
        title: `${this.data.appointmentLang.worker}头像不能为空`,
        duration: 1000,
        icon: "none",
      });
      return;
    }
    // 复选框转成字符串
    if (Array.isArray(this.data.applyModel.project_ids)) {
      this.setData({
        "applyModel.project_ids": String(this.data.applyModel.project_ids),
      });
    }
    this.setData({
      "applyModel.store_id": this.data.store_id,
    });
    let urlStr = app.getNetAddresss(
      "plugin.appointment.frontend.worker.add-worker"
    );
    app._postNetWork({
      url: urlStr,
      data: this.data.applyModel,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          console.log(res);
          wx.showToast({
            title: res.msg,
            icon: "none",
            duration: 1500,
            success: function () {
              setTimeout(() => {
                wx.navigateBack({
                  delta: 1,
                });
              }, 1500);
            },
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
          });
          console.log(res.msg);
        }
      },
    });
  },
  popupComfirm(e) {
    console.log(this.data.applyModel.project_ids);
    this.setData({
      show: false,
      "applyModel.project_ids": this.data.applyModel.project_ids,
    });
  },
  allSelectHandle(e) {
    let val = e.detail;
    val = val.filter(function (el) {
      return el !== "";
    });
    this.setData({
      "applyModel.project_ids": val,
    });
  },
  showCloseBtn(e) {
    this.setData({
      show: false,
    });
  },
  // 编辑提交
  editTechnician() {
    if (this.data.showMember || this.data.showUPMember) {
      wx.showToast({
        title: "请选择用户",
        duration: 1000,
        icon: "none",
      });
      return;
    }
    if (app._isTextEmpty(this.data.applyModel.project_ids)) {
      wx.showToast({
        title: `请选择关联${this.data.appointmentLang.project}`,
        duration: 1000,
        icon: "none",
      });
      return;
    }

    if (!this.data.applyModel.name) {
      wx.showToast({
        title: `${this.data.appointmentLang.worker}姓名不能为空`,
        duration: 1000,
        icon: "none",
      });
      return;
    }
    this.setData({
      "applyModel.worker_id": this.data.worker_id,
    });
    // 复选框转成字符串
    if (Array.isArray(this.data.applyModel.project_ids)) {
      this.setData({
        "applyModel.project_ids": String(this.data.applyModel.project_ids),
      });
    }
    let urlStr = app.getNetAddresss(
      "plugin.appointment.frontend.worker.edit-worker"
    );
    app._postNetWork({
      url: urlStr,
      data: this.data.applyModel,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          console.log(res);
          wx.showToast({
            title: res.msg,
            icon: "none",
            duration: 1000,
            success: function (e) {
              setTimeout(() => {
                wx.navigateBack({
                  delta: 1,
                });
              }, 1000);
            },
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
          });
          console.log(res.msg);
        }
      },
    });
  },
  // 获取关联项目
  getProject() {
    if (typeof this.data.applyModel.project_ids == "string") {
      this.setData({
        "applyModel.project_ids": this.data.applyModel.project_ids.split(","),
      });
    }
    var that = this;
    let urlStr = app.getNetAddresss(
      "plugin.appointment.frontend.project.get-list-by-store-id"
    );
    app._postNetWork({
      url: urlStr,
      data: {
        store_id: "40",
      },
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            projects: res.data,
            show: true,
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
          });
          console.log(res.msg);
        }
      },
    });
  },
  // 获取编辑的数据
  GeteditTechnician() {
    var that = this;
    let urlStr = app.getNetAddresss(
      "plugin.appointment.frontend.worker.edit-show-info"
    );
    app._postNetWork({
      url: urlStr,
      data: {
        worker_id: this.data.worker_id,
      },
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          console.log(res);
          let Data = res.data;
          if (!Data.project_ids && applyModel.project_ids.length <= 0) {
            that.setData({
              "applyModel.project_ids": that.applyModel.project_ids.push(
                Data.project_ids
              ),
            });
          }
          that.setData({
            Data: res.data,
            text_id: Data.member_nickname + "  (id:" + Data.member_u_id + ")",
            leader_uid: Data.leader_nickname + "  (id:" + Data.leader_uid + ")",
            "applyModel.leader_commission": Data.leader_commission,
            "applyModel.name": Data.name,
            "applyModel.thumb": Data.thumb,
            "applyModel.description": Data.description,
            "applyModel.project_ids": Data.project_ids.split(","),
            "applyModel.member_u_id": Data.member_u_id,
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
          });
          console.log(res.msg);
        }
      },
    });
  },
});
