// pages/addOrEditMember/index.js
let app = getApp();
var commonUtil = require("../../utils/commonUtil");
import { customRequest } from '../../utils/request.js';

Page({
  /**
   * 页面的初始数据
   */
  data: {
    memeber: [
      // {
      // 	id: 1,
      // 	checked: true,
      // 	value: "创建人",
      // },
      {
        id: 2,
        checked: false,
        value: "管理员",
      },
      {
        id: 3,
        checked: false,
        value: "成员",
      },
    ],
    groupList: [
    ],
    memberInfo: {
      tel: "",
      aliasName: "",
    },
    pageType: 1,
    currentGroup: -1,
    joinSta: false,// 参与统计选择
    showOnScreen: false,// 参与统计选择
    agencyTeamId: null,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad (options) {
    console.log(options);
    if (options.info) {
      wx.setNavigationBarTitle({
        title: "成员修改",
      });
      let memberInfo = JSON.parse(options.info);
      // 成员角色赋值
      this.data.memeber.forEach((item) => {
        console.log(item);
        if (memberInfo.agencyRole == item.id) {
          item.checked = true;
          memberInfo.agencyRole = item.id + "";
          memberInfo.agencyRoleText = item.value;
        }
      });
      console.log(memberInfo);
      this.setData({
        memberInfo,
        pageType: 1,
        memeber: this.data.memeber,
        joinSta: memberInfo.inAgencyStatistics == 0 ? true : false,
        showOnScreen: memberInfo.showAgencyScreen == 0 ? true : false
      });

    } else {
      wx.setNavigationBarTitle({
        title: "添加成员",
      });
      // 添加成员的时候在不同部门点击赋不同的值
      if (options.group) {
        this.setData({
          groupId: options.group
        });
      } else {
        this.setData({
          agencyTeamId: -1
        });
      }
      this.data.memberInfo.agencyRole = 3;
      this.data.memberInfo.agencyRoleText = "成员";

      this.setData({
        memberInfo: this.data.memberInfo,
        pageType: 2,
      });
    }
    console.log(app.globalData.loginUserInfo);
    this.setData({
      loginUserInfo: app.globalData.loginUserInfo
    })
  },

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

  /**
   * 生命周期函数--监听页面显示
   */
  onShow () {
    console.log(wx.getStorageSync('MEMBERGROUPLIST'));
    if (wx.getStorageSync('MEMBERGROUPLIST')) {
      this.setData({
        groupList: wx.getStorageSync('MEMBERGROUPLIST')
      })
    }
    // 修改成员
    if (this.data.memberInfo.agencyTeamId) {
      console.log(98);
      this.setGroup(this.data.memberInfo.agencyTeamId)

    } else {
      // 添加成员
      console.log(102);

      this.setGroup(this.data.groupId)

    }
  },
  setGroup (id) {
    console.log(id);
    this.data.groupList.forEach((item, index) => {
      if (item.id == id) {
        this.setData({
          currentGroup: index,
          agencyTeamId: item.id + ''
        })
        console.log(this.data.agencyTeamId);
      }
    });
  },
  radioChange (e) {
    console.log(e);
    this.data.groupList.forEach((item, index) => {
      console.log(item);
      item.checked = false;
      if (item.id == e.detail.value) {
        item.checked = true;
        this.data.currentGroup = index
        this.data.agencyTeamId = item.id
      }
    });
    this.setData({
      groupList: this.data.groupList,
      currentGroup: this.data.currentGroup,
      drawerShow: false
    });
  },
  /**
  * 转让创建人
  */
  transferCreator () {
    let that = this
    customRequest("/yishoudan/agency/getCreatorTel", { header: 'headers', method: 'GET', data: {} })
      .then(({data}) => {
        wx.showModal({
          title: "确认要转让创建人吗？",
          content: "您将放弃创建人身份",
          contentColor: "#ccc",
          confirmColor: "#1890ff",
          confirmText: "确定",
          // showCancel: false,
          success (res) {
            // console.log(res);
            if (res.confirm) {
              wx.navigateTo({
                url: `/pages/sendCreatorCode/index?info=${JSON.stringify(data.data)}`,
              });
            }

          },
        });
      })
    // wx.request({
    //   url: app.globalData.ip + "/yishoudan/agency/getCreatorTel",
    //   method: "get",
    //   header: app.globalData.headers,
    //   success: function ({ data }) {
    //     console.log(data);

    //   }
    // })
  },
  /**
   * 阻止滑动穿透
   *
   *
   */
  modalMove () {
    return false;
  },

  /**
  * 数据相关开关切换
  */
  switchChange (e) {
    console.log(e);
    let type = e.currentTarget.dataset.type
    this.setData({
      [type]: e.detail.value
    })
    console.log(this.data[type]);
  },
  /* 
    表单提交的前置校验
  */
  beforeFormSubmit (e) {
    console.log(e);
    console.log(this.data.memberInfo);

    let myreg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
    // if (app.isEmptyCheck(e.detail.value.userName)) {
    // 	wx.showToast({
    // 		duration: 2000,
    // 		title: "请输入姓名",
    // 		icon: "none",
    // 		mask: true,
    // 	});
    // } else
    if (app.isEmptyCheck(this.data.memberInfo.tel)) {
      wx.showToast({
        duration: 2000,
        title: "请输入手机号",
        icon: "none",
        mask: true,
      });
    } else if (app.isEmptyCheck(this.data.memberInfo.aliasName)) {
      wx.showToast({
        duration: 2000,
        title: "请输入备注名",
        icon: "none",
        mask: true,
      });
    } else if (app.isEmptyCheck(this.data.memberInfo.agencyRole)) {
      wx.showToast({
        duration: 2000,
        title: "请选择角色",
        icon: "none",
        mask: true,
      });
    } else if (!myreg.test(this.data.memberInfo.tel)) {
      wx.showToast({
        duration: 2000,
        title: "请输入正确的手机号",
        icon: "none",
        mask: true,
      });
    } else {
      if (this.data.pageType == 1) {
        this.formSubmit(this.data.memberInfo);
      } else {
        this.addMember(this.data.memberInfo);
      }
    }
  },
  /* 
    表单提交
  */
  formSubmit (data) {
    let that = this;
    let role = commonUtil.getAgencyPermissionsByRole(data.agencyRole);
    console.log(that.data.agencyTeamId);
    let info = { ...that.data.memberInfo, id: that.data.memberInfo.id, agencyPermissions: role, agencyTeamId: that.data.agencyTeamId, inAgencyStatistics: this.data.joinSta ? 0 : 1, showAgencyScreen: this.data.showOnScreen ? 0 : 1 };
    wx.showLoading({
      title: "提交中...",
      mask: true,
    });
    customRequest("/yishoudan/user/updateAgencyCorpUser", { header: 'headers', method: 'POST', data: info })
      .then((res) => {
        wx.hideLoading();
        if (res.data.status == 200) {
          wx.showToast({
            title: "修改成功",
            icon: "success",
            duration: 1000,
            success: () => {
              wx.navigateBack({
                delta: 1
              });
            },
          });
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: "error",
            duration: 1000,
          });
        }
      })
    // wx.request({
    //   url: app.globalData.ip + "/yishoudan/user/updateAgencyCorpUser",
    //   header: app.globalData.headers,
    //   method: "POST",
    //   data: info,
    //   success: function (res) {
    //     console.log(res);

    //   },
    // });
  },
  addMember (data) {
    let that = this;
    wx.showLoading({
      title: "提交中...",
      mask: true,
    });
    // setTimeout(() => {
    // 	var pages = getCurrentPages();
    // 	var prevPage = pages[pages.length - 2]; // 上一个页面
    // 	prevPage.setData({
    // 		toastShow: true,
    // 	});
    // 	wx.navigateBack({
    // 		delta: -1,
    // 	});
    // }, 2000);

    // return;
    let role = commonUtil.getAgencyPermissionsByRole(data.agencyRole);
    let info = { ...that.data.memberInfo, agencyPermissions: role, agencyTeamId: that.data.agencyTeamId, inAgencyStatistics: this.data.joinSta ? 0 : 1, showAgencyScreen: this.data.showOnScreen ? 0 : 1 };
    customRequest("/yishoudan/user/addAgencyUser", { header: 'headers', method: 'post', data: info }).then((res) => {
      wx.hideLoading();
      if (res.data.status == 200) {
        wx.showToast({
          title: "已添加，等待成员同意",
          icon: "success",
          duration: 2000,
          success: () => {
            wx.navigateBack({
              delta: 1
            });
          },
        });
      } else if (res.data.status == 500) {
        wx.showToast({
          title: res.data.msg,
          icon: "none",
          duration: 2000,
        });
      }
    })
    // wx.request({
    //   url: app.globalData.ip + "/yishoudan/user/addAgencyUser",
    //   method: "post",
    //   header: app.globalData.headers,
    //   data: info,
    //   success: function (res) {
    //     console.log(res);

    //   },
    // });
  },
  showDrawer () {
    this.setData({
      drawerShow: true
    })
  },
  hidedrawershow (e) {
    console.log(e);
    this.setData({
      [e.detail.type]: false
    })
    console.log(this.data.drawerShow);
  },
  showDelModal (e) {
    let that = this;
    wx.showModal({
      title: "删除成员",
      content: "确定将该成员删除吗?",
      confirmColor: "#1890ff",
      success (res) {
        if (res.confirm) {
          that.deleteMember(that.data.memberInfo.id);
        } else if (res.cancel) {
        }
      },
    });
  },
  deleteMember (id) {
    let that = this;
    wx.showLoading({
      title: "删除中...",
      mask: true,
    });
    customRequest("/yishoudan/user/delAgencyCorpUser", { header: 'headers', method: 'POST', data: { id, } }).then((res) => {
      wx.hideLoading();
      if (res.data.status == 200) {
        wx.showToast({
          title: "已删除",
          icon: "success",
          duration: 1000,
          success: () => {
            wx.navigateBack({
              detail: 1
            });
          },
        });
      }
    })
    // wx.request({
    //   url: app.globalData.ip + "/yishoudan/user/delAgencyCorpUser",
    //   method: "POST",
    //   header: app.globalData.headers,
    //   data: {
    //     id,
    //   },
    //   success: function (res) {
    //     console.log(res);

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

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

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

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

  /**
   * 用户点击右上角分享
   */
onShareAppMessage() {
  return app.sharePageImage()
},
  /**
   * 角色选择
   *
   *
   */
  changeRole (e) {
    console.log(e);
    console.log(this.data.memberInfo);
    if (e.detail.value == 0) {
      this.data.memberInfo.agencyRole = 2;
      this.data.memberInfo.agencyRoleText = "管理员";
    } else if (e.detail.value == 1) {
      this.data.memberInfo.agencyRole = 3;
      this.data.memberInfo.agencyRoleText = "成员";
    }
    console.log(this.data.memberInfo);
    this.setData({
      memberInfo: this.data.memberInfo,
    });
  },
  /**
   * 勉强实现双向绑定
   *
   *
   */
  setDesp (e) {
    console.log(e);
    if (e.target.dataset.type == "tel") {
      this.data.memberInfo.tel = e.detail.value;
    } else {
      this.data.memberInfo.aliasName = e.detail.value;
    }
    this.setData({
      memberInfo: this.data.memberInfo,
    });
  },
  goSearch () {
    wx.navigateTo({
      url: "/pages/search/index?from=agencyRole",
    });
  },
});
