// pages/userManage/index.js
import ActionSheet, {
  ActionSheetTheme
} from 'tdesign-miniprogram/action-sheet/index';
import Dialog from "tdesign-miniprogram/dialog/index"
import {
  request
} from "../../utils/request.js"
let tempitem;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    users: [],
    enable: false
  },

  onShow() {
    this.onRefresh()
  },
  onRefresh() {
    this.setData({
      enable: true
    });
    request("getUser", {}, {
      loadingMask: false
    }).then(res => {
      this.setData({
        users: res.data.filter(v => v.username !== getApp().globalData.userInfo.username).map(v => ({
          id: v._id,
          label: v.username,
          isAdmin: v.isAdmin,
          value: v.username,
          remark: v.remark
        }))
      });
    }).finally(() => {
      this.setData({
        enable: false
      })
    })
  },
  openAction(e) {
    tempitem = e.target.dataset.item;
    ActionSheet.show({
      theme: ActionSheetTheme.List,
      selector: '#t-action-sheet',
      items: [{
          label: '编辑用户',
          color: '#0052D9',
        },
        {
          label: '删除用户',
          color: '#e34d59',
        },
      ],
    })
  },
  handleAdd() {
    wx.navigateTo({
      url: '/pages/modifyUser/index',
    })
  },
  handleSelected(e) {
    const {
      index
    } = e.detail
    if (index === 0) {
      wx.navigateTo({
        url: '/pages/modifyUser/index?item=' + JSON.stringify(tempitem),
      })
      //编辑
    } else {
      //删除
      const dialogConfig = {
        context: this,
        closeOnOverlayClick: true,
        content: '确定要删除' + tempitem.label + '吗？',
        confirmBtn: '确定',
        cancelBtn: '取消',
      };

      Dialog.confirm(dialogConfig)
        .then(() => {
          request("deleteUser", {
            id: tempitem.id
          }).then(() => {
            this.onRefresh()
          })
        })
        .catch(() => {});
    }
  },
})