import config from '../config.js';

const getStateCreateTime = (stateList, type) => {
	if(stateList && stateList.length != 0){
		const task = stateList.find(item => item.tasksheetState === type);
		return task?.createTime;
	}else{
		return ''
	}
}

const formatTime = date => {
  date = new Date(date);
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${formatNumber(hour)}:${formatNumber(minute)}:${formatNumber(second)}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

const formatDate = date => {
  date = new Date(date);
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()

  return `${year}-${formatNumber(month)}-${formatNumber(day)}`
}

const formatDateTime = date => {
  return `${formatDate(date)} ${formatTime(date)}`
}

let loadingCount = 0;
let noError = true;
let timer = null;
const request = option => {
  if (noError && loadingCount == 0) {
    // uni.showLoading({
    //   title: '加载中',
    //   mask: true
    // });
  }
  if (timer) {
	loadingCount--;
    clearTimeout(timer);
	timer = null;
  }
  loadingCount++;
  // console.log("request00:",config.baseUrl + option.url);
  return new Promise((resolve, reject) => {
    const commonSuccess = res => {
      if (typeof res.data == 'object') {
        let data = res.data.data || res.data.tableData;
        res.data.tableData = data;
      }
	  if (res.data.Token) {
	    uni.setStorageSync("token", res.data.Token);
	  }
	  if (res.statusCode != 200 || (res.data.code != undefined && res.data.code != 0 &&res.data.code != 1002)) {
	    res.statusCode = res.statusCode == 200 ? 500 : res.statusCode;
	    if (option.fail) {
	      option.fail(res);
	    }
	    return reject(res);
	  }
	  timer = setTimeout(() => {
	    loadingCount--;
	    // console.log("success loadingCount:", loadingCount);
	    if (loadingCount == 0) {
	      if (noError) {
	        // uni.hideLoading();
	      }
	      noError = true;
	      timer = null;
	    }
	  }, 300);
	  if (option.success) {
	    option.success(res);
	  }
	  resolve(res);
    }
    const commonFail = err => {
		noError = false;
		// uni.hideLoading();
		if (--loadingCount == 0) {
		  noError = true;
		}
		if (option.fail) {
		  option.fail(err);
		}
		uni.showToast({
		  title: "网络错误: " + JSON.stringify(err),
		  icon: 'error', // 图标，有效值为 'success', 'loading', 'none'
		  duration: 3000 // 提示的延迟时间，单位毫秒，默认:1500
		});
		console.warn(`request: ${option.url}, ${JSON.stringify(err)}`);
		reject(err);
    }
	//console.log("request0:",config.baseUrl + option.url);
	let staff = uni.getStorageSync('staff');
	let staffisnull = (staff == null || staff == undefined || staff == '');
    uni.request({
      url: config.baseUrl + option.url,
      data: option.data,
      header: option.header || {
        'content-type': 'application/json',
        'Authorization': staffisnull?null:`Bearer ${uni.getStorageSync('token')}`,
        'hosp-ID': staffisnull?config.defaultHospId:staff.hosp_id,
        'user-ID': staffisnull?null:staff.id,
        'datetime': formatDateTime(new Date),
        'createby': staffisnull?null:staff.id,
      },
      method: option.method || 'POST',
      success: commonSuccess,
      fail: commonFail,
      complete: option.complete,
    });
  }).catch((err) => {
    noError = false;
    // uni.hideLoading();
    if (--loadingCount == 0) {
      noError = true;
    }
    //console.log("error loadingcount:", uni.getStorageSync('staff') == null?null:uni.getStorageSync('staff').hosp_id);
	//console.log("err：",err.data.message,"staff:",uni.getStorageSync('staff'));
    if (err?.data?.message.includes("非法token")) {
		//初始化
		uni.setStorageSync('staff', null);
		uni.setStorageSync('openid', null);
		uni.setStorageSync('token', null);
		
		uni.showToast({
		  title: "非法用户或登录过期，请重新登录。",
		  icon: 'error', // 图标，有效值为 'success', 'loading', 'none'
		  duration: 3000 // 提示的延迟时间，单位毫秒，默认:1500
		});
	} else {
		uni.showToast({
		  title: "网络通信错误:" + JSON.stringify(err?.data?.msg || err),
		  icon: 'error', // 图标，有效值为 'success', 'loading', 'none'
		  duration: 3000 // 提示的延迟时间，单位毫秒，默认:1500
		});
	}
    return err;
  });
}

const upload = option => {
	if (timer) {
	  loadingCount--;
	  clearTimeout(timer);
	  timer = null;
	}
	loadingCount++;
	return new Promise((resolve, reject) => {
	  const ret = {
	    data: `{"mydata": {"filename": ""}}`,
	  };
	  const commonSuccess = (res) => {
	    timer = setTimeout(() => {
	      loadingCount--;
	      if (loadingCount == 0) {
	        uni.hideLoading();
	        timer = null;
	      }
	    }, 300);
	    if (option.success) {
	      option.success(res);
	    }
	    resolve(res);
	  };
	  var commonFail = (err) => {
	    noError = false;
	    uni.hideLoading();
	    loadingCount--;
	    uni.showToast({
	      title: "网络错误: " + JSON.stringify(err),
	      icon: 'error', // 图标，有效值为 'success', 'loading', 'none'
	      duration: 3000 // 提示的延迟时间，单位毫秒，默认:1500
	    });
	    reject(err);
	  };
	  if (!option.filePath) {
	    uni.hideLoading();
	    return resolve(ret);
	  }
	  let staff = uni.getStorageSync('staff');
	  let staffisnull = (staff == null || staff == undefined || staff == '');
	  uni.uploadFile({
	    url: config.baseUrl + option.url,
	    header: {
	      Authorization: staffisnull?null:`Bearer ${uni.getStorageSync('token')}`,
	      'hosp-ID': staffisnull?config.defaultHospId:staff.hosp_id,
	      'user-ID': staffisnull?null:staff.id
	    },
	    filePath: option.filePath,
	    name: "file" || option.name,
	    success: commonSuccess,
	    fail: commonFail,
	    complete: option.complete,
	  });
	}).catch((err) => {
		console.log('err',err)
	  noError = false;
	  uni.hideLoading();
	  if (--loadingCount == 0) {
	    noError = true;
	  }
	  uni.showToast({
	    title: "网络错误: " + JSON.stringify(err),
	    icon: 'error', // 图标，有效值为 'success', 'loading', 'none'
	    duration: 3000 // 提示的延迟时间，单位毫秒，默认:1500
	  });
	  return err;
	});
}

function areArraysEqualById(arr1, arr2) {
  // 如果数组长度不相等，直接返回 false
  if (arr1.length !== arr2.length) return false;

  // 创建两个 Map 用于存储每个数组的元素 id 及其出现的次数
  const map1 = new Map();
  const map2 = new Map();

  // 遍历第一个数组，将元素 id 存储到 map1 中
  for (let item of arr1) {
    map1.set(item.id, (map1.get(item.id) || 0) + 1);
  }

  // 遍历第二个数组，将元素 id 存储到 map2 中
  for (let item of arr2) {
    map2.set(item.id, (map2.get(item.id) || 0) + 1);
  }

  // 比较两个 map 的键值对
  if (map1.size !== map2.size) return false;

  for (let [key, value] of map1) {
    if (map2.get(key) !== value) return false;
  }

  return true;
}

//判断对象是否未空
function isNull(e) {
	return e==null || e==undefined || e=='';
}

export default {
  request: request,
  formatTime: formatTime,
  formatDate: formatDate,
  formatDateTime: formatDateTime,
  upload: upload,
  areArraysEqualById: areArraysEqualById,
  getStateCreateTime: getStateCreateTime,
  isNull
}