import { formatTime, formatDate, formatDateTime, BASE_URL, getHeaders } from './index.js'; // 引入时间格式化函数和BASE_URL

//@ts-ignore
import md5 from '@/utils/md5.js'
import util from '@/utils/util.js'

import config from '@/config'

export function login(username: string, password: string): Promise<{
  code: number;
  msg: string;
  data: {
    token: string;
    userLoginRequestVO: {
      id: number;
      user_name: string;
      user_login_name: string;
      user_type: string;
      user_pic_path: string | null;
      role_id: number | null;
      role_name: string | null;
      hosp_id: number | null;
      hospName: string | null;
      hospPic: string | null;
      hospCenterX: number | null;
      hospCenterY: number | null;
      role: string[] | null;
      assetsRole: number | null;
      roles: string[] | null;
    }
  }
}> {
  return new Promise((resolve, reject) => {
    uni.request({
      url: `${BASE_URL}/myUser/login2`,
      method: 'POST',// 请求方法：POST
      data: {
        mobile: username,
        password: md5.hexMD5(username + password),
        role: '007'
      },

      header: getHeaders(),

      success: async (res) => {




        if (res.statusCode === 200) {
          try {
            const res_ = await util.request({
              url: config.urls.login,
              method: 'POST',
              data: {
                username: username,
                password: md5.hexMD5(username + password),
                typecode: '007'
              }
            })
            if (res_?.data?.code === 0) {
              const staff = res_.data.data.userLoginInfo
              // 兼容旧逻辑，附加 role 别名
              uni.setStorageSync('staff', { ...staff, role: staff.role_ids })
              uni.setStorageSync('token', res_.data.token)
              resolve(res.data as any);

            } else {
              uni.showToast({ title: res_?.data?.msg || '登录失败', icon: 'error', duration: 3000 })
            }
          } catch (err: any) {
            // util.request 已有统一错误提示
            console.warn('login error', err)
          }
        } else {
          reject(res);
        }
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
}