import { defHttp } from '/@/utils/http/axios';
import {
  LoginParams,
  LoginResultModel,
  GetUserInfoModel,
  UserInfoModel,
  RefreshTokenParams,
  SmsLoginParams,
} from './model/userModel';
import { session } from "/@/utils/Memory.js";
import md5 from 'js-md5';
import type { ErrorMessageMode } from '/#/axios';
import permissions from "/@/mock/role_me_permissions.json";
import tool from "/@/utils/Tool.js";
import { getJwtToken } from '/@/utils/auth';
import moment from 'moment';
import { resolve } from 'path';
import { message } from 'ant-design-vue';

enum Api {
  // Login = '/auth/login',
  Login = '/api-auth/oauth/token',
  SmsCodeLogin = '/auth/code/login',
  Logout = '/auth/logout',
  GetUserInfo = '/user',
  // GetMyInfo = '/user/me/info',
  // GetMyInfo = '/api-auth/oauth/userinfo',
  GetMyInfo = '/callProvider',
  GetPermCode = '/callProvider',
  RefreshToken = '/auth/token',
  SendLoginSmsCode = '/noauth/send_login_code/',
  ResetCode = '/noauth/reset_code/',
  ResetPassword = '/noauth/reset/',
  Appointment = "/user-center/position/GetPostTreeByOrgId",
  AppointPos = "/user-center/post/GetAtpPostTree",
  SelectGroupList = "/user-center/role/selectGroupList",
  AddLoginRecord = "/base-center/syslog/AddLogin",
  SaveRoleMenu = "/base-center/newmenu/saveRoleMenu",
  SaveUserMenu = "/base-center/newmenu/saveUserMenu",
  GetRoleMenus = "/base-center/newmenu/getRoleMenus",
  GetUserMenus = "/base-center/newmenu/getUserMenus",
  allSys = '/datastore/dir/sys/list',
  GetUserDetailInfo = '/user-center/role/selectMHRoleByUserId',
  GetPersonByDepId = '/user-center/user/getPersonByDepId',  ///api-user/user/getPersonByDepId
}

const client = {
  grant_type: "password",
  scope: "all",
  client_id: "space",
  client_secret: 'e10adc3949ba59abbe56e057f20f883e',
}

const interfaceType = { apiUrl2: true };

/**
 * @description: user login api
 */
export function loginApi(params: LoginParams, mode: ErrorMessageMode = 'modal') {
  session.setItem('loginFrom', params)
  const formData = new FormData();
  var a = { ...params, ...client };
  Object.keys(a).forEach((key) => formData.append(key, a[key]))
  return new Promise<void>((resolve, reject) => {
    defHttp.post<LoginResultModel>({ url: Api.Login, params: formData })
      .then((r) => {
        r.refreshToken = r.refresh_token;
        r.token = r.access_token;
        session.setItem('token', r.access_token);
        resolve(r);
        allSys();
        // loginCallProvider();
      }).catch((err) => {
        resolve(err)
      })
  })
}


export function loginCallProvider() {
  var a = {
    interfaceName: "atp-provider.controller.AtpController",
    methodName: "getToken",
    args: ['superAtp', '#super&Atp@123']
  }
  const f = new FormData();
  Object.keys(a).forEach((key) => f.append(key, a[key]))
  return new Promise<void>((resolve, reject) => {
    defHttp.post<LoginResultModel>({ url: Api.GetPermCode, params: f, ...interfaceType, })
      .then((r) => {
        debugger;
      })
  })
}


export function getMyInfo() {
  var a = session.getItem('loginFrom');
  const formData = new URLSearchParams();
  formData.append('interfaceName', 'atp-provider.controller.AtpController');
  formData.append('methodName', 'misLogin');
  formData.append('args[]', 'space');
  formData.append('args[]', a.username);
  formData.append('args[]', md5(a.password));
  formData.append('args[]', '');
  return new Promise<void>((resolve, reject) => {
    defHttp.post<UserInfoModel>({
      url: Api.GetMyInfo,
      params: formData,
      ...interfaceType,
    }, { joinPrefix: false }).then(async (i) => {
      if (i.status == 0) {
        var u = JSON.parse(i.result);
        console.log(u);

        //插入登录日志记录
        let addRecordParam = {
          systemLog: {
            cjrq: moment().format('YYYY-MM-DD HH:mm:ss'),
            czsm: "登录操作",
            opt: "login",
            sfcg: u.hasOwnProperty('tokenV2') ? 1 : 0,
            userid: u.EMPLOYEE_MIS.EMPLOYEE_ID,
            username: u.EMPLOYEE.NAME
          }
        }
        defHttp.post({ url: Api.AddLoginRecord, params: addRecordParam })

        var a = {
          info: u,
          "userId": "80808080-8080-8080-8080-808080808080",
          "realName": u.EMPLOYEE.NAME,
          "username": u.EMPLOYEE.NAME,
          "LOGIN_NAME": u.EMPLOYEE.LOGIN_NAME,
          "phoneNumber": "17313039356",
          "email": "1419750663@qq.com",
          "avatar": "",
          "tenantId": "13814000-1dd2-11b2-8080-808080808080",
          "needSetPwd": false,
          "roles": [
            "SYS_ADMIN"
          ],
          "nameroles": u.ROLES && u.ROLES.map(i => i.NAME).join(","),
          "plainRoles": [
            {
              "roleId": "81818181-8181-8181-8181-818181818181",
              "roleName": "超级管理员"
            }
          ]
        }
        await getUserIdInfo(u.EMPLOYEE_MIS.EMPLOYEE_ID);
        resolve(a);
        session.setItem("userInfo", u);
        session.setItem('tokenV2', u.tokenV2);
        session.setItem('userId', u.EMPLOYEE_MIS.EMPLOYEE_ID);
      } else {
        window.localStorage.clear();
        window.sessionStorage.clear();
        message.error("用户名或密码错误");
        resolve([]);
      }
    })
  })
}

/**
 * @description: 根据用户id获取详细信息
 */
export const getUserIdInfo = (id) => {
  return new Promise((resolve) => {
    defHttp.post<Array<string>>({
      url: Api.GetUserDetailInfo, params: {
        userId: id,
        getRoleIds: true
      }
    }).then(r => {
      if (r.resp_code == 0 && r.datas && r.datas.length) {
        session.setItem("roles", r.datas.join(","));
        resolve(r.datas)
      }
    })
  })
};


/**
 * @description: 获取所有组织
 */
export const appointment = (params: AccountParams) => {
  return new Promise<void>((resolve, reject) => {
    defHttp.post({ url: Api.Appointment }).then((res) => {
      resolve(tool.buildTree(res.datas, "0"))
    })
  })
}
/**
 * @description: id获取所属组织的岗位
 */
export const appointPos = (id) => {
  const formData = new FormData();
  formData.append('zwId', id);
  return new Promise<void>((resolve, reject) => {
    defHttp.post({ url: Api.AppointPos, params: formData }).then((res) => {
      res.datas.map(i => { i.label = i.name, i.value = i.id })
      resolve(res.datas)
    })
  })
}
/**
 * @description: 角色列表
 */
export const roleList = (id) => {
  const formData = new FormData();
  formData.append('zwId', id);
  return new Promise<void>((resolve, reject) => {
    defHttp.post({ url: Api.SelectGroupList, params: formData }).then((res) => {
      res.datas.map(i => {
        if (i.groupName == "系统角色") session.setItem("adminRole", i)
        i.label = i.groupName, i.value = i.groupid, i.id = i.groupid
      })
      resolve(res.datas)
    })
  })
}

/**
 * @description: 保存角色和菜单的关系
 */
export const saveRoleMenu = (params) => {
  return new Promise<void>((resolve, reject) => {
    defHttp.post({ url: Api.SaveRoleMenu, params })
      .then((r) => resolve(r.datas && r.resp_code == 0)).catch(e => resolve())
  })
}

/**
 * @description: 保存角色和菜单的关系
 */
export const saveUserMenu = (params) => {
  return new Promise<void>((resolve, reject) => {
    defHttp.post({ url: Api.SaveUserMenu, params })
      .then((r) => resolve(r.datas && r.resp_code == 0)).catch(e => resolve())
  })
}


/**
 * @description: 获取角色和菜单的关系
 */
export const getRoleMenus = (params) => {
  return new Promise<void>((resolve, reject) => {
    defHttp.post({ url: Api.GetRoleMenus, params })
      .then((r) => resolve(r.datas)).catch(e => resolve())
  })
}

/**
 * @description: 获取角色和菜单的关系
 */
export const getUserMenus = (params) => {
  return new Promise<void>((resolve, reject) => {
    defHttp.post({ url: Api.GetUserMenus, params })
      .then((r) => resolve(r.datas)).catch(e => resolve())
  })
}



/**
 * @description: 获取角色和菜单的关系
 */

export function allSys() {
  defHttp.post({ url: Api.allSys })
    .then((r) => {
      if (r && r.datas) {
        var l = r.datas.filter(i => i.sysName == '中台文件系统')
        if (l && l.length) session.setItem('sysFild', l[0])
      }
    })
}

/**
 * @description: getUserInfo
 */
export function getUserInfo() {
  return defHttp.get<GetUserInfoModel>({ url: Api.GetUserInfo });
}

export function getPermCode() {
  return new Promise<void>((resolve, reject) => {
    resolve(permissions)
  })

  // return defHttp.get<string[]>({ url: Api.GetPermCode });
}
export async function SendLoginSmsCode(phoneNumber: string) {
  return await defHttp.post<boolean>({ url: Api.SendLoginSmsCode + phoneNumber });
}

export async function doLogout() {
  await defHttp.post(
    {
      url: Api.Logout,
    },
    {
      joinPrefix: false,
    }
  );
}
export function doRefreshToken(params: RefreshTokenParams) {
  return defHttp.post<LoginResultModel>(
    {
      url: Api.RefreshToken,
      params,
    },
    {
      joinPrefix: false,
    }
  );
}
export function smsCodeLoginApi(params: SmsLoginParams, mode: ErrorMessageMode = 'modal') {
  return defHttp.post<LoginResultModel>(
    {
      url: Api.SmsCodeLogin,
      params,
    },
    {
      errorMessageMode: mode,
    }
  );
}

// 密码重置验证码
export function passwordResetCode(mobile) {
  return defHttp.post({
    url: Api.ResetCode + mobile,
  });
}

// 重置密码
export function forgetPasswordApi(data) {
  return defHttp.post({
    url: Api.ResetPassword + data.phoneNumber,
    data,
  });
}

export const getUserToken = (id: string) => {
  return defHttp.get<Record<'token' | 'refreshToken', string>>({
    url: `/third/login/id/${id}`,
  });
};

/**
 * 获取部门下所有人员基本信息
 * @params 
 *    depId  	部门id
*/
export const queryPersonByDepId = (params) => {
  const token = getJwtToken();
  params = Object.assign(params, { Authorization: token })
  return new Promise<void>((resolve) => {
    defHttp.post({ url: Api.GetPersonByDepId, params }).then((res) => {
      resolve(res)
    })
  })

};