// #ifdef APP-PLUS
import { chooseSystemMedia } from "@/uni_modules/uni-chooseSystemImage"
// #endif
import verConfig from "../ver.config"
import { t } from "@/locale";
import { getStorage } from './storage'
import { getCurrentInstance } from "vue";
import { useSystemStore } from "@/store";

let useSystem = null;
export const useGlobal = () => {
  const { appContext } = getCurrentInstance();
  return appContext.config.globalProperties;
}

export const getToken = (token = verConfig.tokenName) => {
  // const _token = JSON.parse(uni.getStorageSync(token) || '{}');
  // return _token.token || ''
  return getStorage(token);
}

export const Toast = (title, duration = 2000, icon = 'none') => new Promise((resolve, reject) => {
  uni.showToast({
    title,
    icon,
    duration,
    success: (res => resolve(res)),
    fail: (err => reject(err))
  })
})

export const query = (className, _instance) => new Promise((resolve, reject) => {
  let query = uni.createSelectorQuery()
  query.select(className).boundingClientRect(res => {
    resolve(res)
  }).exec()
})

export const Modal = ({ content, title = t('提示'), showCancel = true, cancelText = t('取消'), confirmText = t('确认') }) => new Promise((resolve, reject) => {
  uni.showModal({
    title,
    content,
    showCancel,
    cancelText,
    confirmText,
    success: (res => {
      if (res.confirm) {
        resolve(res.confirm)
      } else if (res.cancel) {
        reject(res.cancel)
      }
    }),
    fail: (err => {
      reject(err)
    })
  })
})
export const useImg = (url, options = {}) => {
  const { baseURL, api } = options;
  // if (url && url.charAt(0) === '/') {
  //   url = url.substring(0, url.length);
  // }
  if (/^http/.test(url)) {
    return url;
  }
  return api ? ((baseURL || verConfig.newUrl) + api + url) : ((baseURL || verConfig.newUrl) + url);
}

export const systemInfo = () => {
  const res = uni.getSystemInfoSync();
  return res
}



export const downFile = ({ file_name, file_url, file_path, cattype }) => {
  let url = file_url || file_path
  // #ifdef APP-PLUS
  let dtask = plus.downloader.createDownload(url, {
    filename: `file:///storage/emulated/0/lawyerApp/${file_name}${getFileSuffix(url)[1]}`
  }, (d, status) => {
    if (status == 200) {
      Toast('文件下载并保存成功');
    } else {
      Toast('保存失败')
    }
  })
  plus.io.resolveLocalFileSystemURL('file:///storage/emulated/0/lawyerApp/', entry => {
  }, function (error) {
    plus.io.requestFileSystem(plus.io.PRIVATE_DOC, fs => {
      fs.root.getDirectory('lawyerApp', { create: true }, dirEntry => {
        dtask.start();
      }, function (err) { });
    });
  });
  // #endif
  // #ifdef H5
  fetch(url).then(response => {
    if (!response.ok) {
      throw new Error('网络响应不正常');
    }
    return response.blob();
  }).then(blob => {
    const objectUrl = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = objectUrl;
    link.download = file_name;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(objectUrl);
  }).catch(error => {
    Toast('下载失败')
  });
  // #endif
}

export const uploadChooseImage = (sourceType = 'album', count = 1) => new Promise((resolve, reject) => {

  // #ifdef APP-PLUS
  // if (systemInfo().osName == 'android') {
  //   uploadSystemMedia('image', count).then(result => {
  //     resolve(result)
  //   })
  //     .catch(err => {
  //       reject(err)
  //     })
  //   return
  // }
  // #endif

  uni.chooseImage({
    count,
    sizeType: ['compressed'],
    sourceType: [sourceType],
    success: res => {
      console.log('----- uni.chooseImage res -----', JSON.stringify(res))
      if (count == 1) {
        const tempFilePath = res.tempFilePaths[0];
        const tempFile = res.tempFiles[0]
        return resolve({ tempFilePath, tempFile, errMsg: res.errMsg })
      }
      return resolve(res)
    },
    fail: err => {
      Toast(t('上传失败'));
      reject(err)
    }
  })
})

// #ifdef APP-PLUS
export const uploadSystemMedia = (mediaType = 'image', count = 1) => new Promise((resolve, reject) => {
  chooseSystemMedia({
    count,
    pageOrientation: 'auto',
    mediaType: [mediaType],
    success: res => {
      if (count == 1) {
        const tempFilePath = res.filePaths[0];
        const tempFile = {
          path: res.filePaths[0],
          size: null
        }
        return resolve({ tempFilePath, tempFile, errMsg: 'chooseImage:ok' })
      }
      return resolve(res)
    },
    fail: err => {
      console.log('----- chooseSystemMedia err -----', JSON.stringify(err))
      Toast(t('上传失败'));
      reject(err)
    }
  })
})
// #endif

export const uploadChooseVideo = (sourceType = ['album'], camera = 'back', extension = ['mp4', 'avi', 'mov']) => new Promise((resolve, reject) => {
  uni.chooseVideo({
    extension,
    sourceType,
    camera,
    compressed: true,
    success: res => {
      // #ifdef H5
      const type = res.tempFile.type;
      if (!type.includes('video')) return Toast('请上传视频');
      // #endif
      const screenWidth = systemInfo().screenWidth;
      const aspect = res.width / res.height;
      const videoWidth = screenWidth + 'rpx'
      const videoheight = (screenWidth / aspect) + 'rpx'
      resolve({
        tempFilePath: res.tempFilePath,
        videoWidth, videoheight
      })
    },
    fail: err => {
      Toast('上传失败');
      reject(err)
    }
  })
})

export const getFileSuffix = (str) => {
  const lastDotIndex = str.lastIndexOf('.');

  if (lastDotIndex === -1) {
    return '';
  }
  return [str.substring(0, lastDotIndex), str.substring(lastDotIndex)];
}

export const stringToHex = () => {
  let str = (getStorage(verConfig.infoName) || {}).id + '/1'
  let hex = '';
  for (let i = 0; i < str.length; i++) {
    hex += str.charCodeAt(i).toString(16).padStart(2, '0');
  }
  return `cu${hex}`;
}

var keepDigits = function (number, digital) {
  if (digital === void 0) { digital = 2; }
  var res = number.toString();
  var zeroNum = digital - res.length;
  for (var i = 0; i < zeroNum; i++) {
    res = "0" + res;
  }
  return res;
};
export const format = function (time, format) {
  if (!time) return
  if (format === void 0) { format = "yyyy-MM-dd HH:mm:ss"; }
  if (typeof time === "number") {
    var len = time.toString().length;
    if (len === 10) {
      time *= 1000;
    }
  }
  var date = new Date(time);
  var formatTypes = {
    y: date.getFullYear(),
    M: date.getMonth() + 1,
    d: date.getDate(),
    H: date.getHours(),
    m: date.getMinutes(),
    s: date.getSeconds()
  };
  var res = format;
  for (var key in formatTypes) {
    if (Object.prototype.hasOwnProperty.call(formatTypes, key)) {
      var value = formatTypes[key];
      res = res.replace(new RegExp(key + "+"), keepDigits(value, 2));
    }
  }
  return res;
};
export const debounce = (func, delay) => {
  let timer;
  return function (...args) {
    clearTimeout(timer);
    timer = setTimeout(() => {
      func.apply(this, args);
    }, delay);
  };
}
export const throttle = (func, limit) => {
  let lastFunc;
  let lastRan;
  return function (...args) {
    const context = this;
    if (!lastRan) {
      func.apply(context, args);
      lastRan = Date.now();
    } else {
      clearTimeout(lastFunc);
      lastFunc = setTimeout(function () {
        if ((Date.now() - lastRan) >= limit) {
          func.apply(context, args);
          lastRan = Date.now();
        }
      }, limit - (Date.now() - lastRan));
    }
  };
}

export const uniappStorage = {
  getItem: (key) => {
    try {
      return uni.getStorageSync(key) || null
    } catch (error) {
      return null
    }
  },
  setItem: (key, value) => {
    try {
      uni.setStorageSync(key, value)
    } catch (error) { }
  }
}

export const openUrl = (url) => {
  // #ifdef H5
  window.location.href = url;
  // #endif
  // #ifdef APP
  plus.runtime.openURL(url)
  // #endif
}

export const refresh = (url) => {
  // #ifdef H5
  window.location.reload();
  // #endif
  // #ifdef APP
  uni.navigateTo({ url });
  // #endif
}

export const converMoney = (money, rate = 1) => {
  useSystem = useSystemStore();
  const symbol = useSystem.getSymbol;
  if (!money) return '0.00';
  money = typeof money === 'string' ? (money - 0) : money;
  rate = Number(symbol.rate)
  const newMoney = (money / rate).toFixed(2);
  return `${newMoney}`
}

export const Moneyhtml = (money, flag = false, isConver = true) => {
  useSystem = useSystemStore();
  const symbol = useSystem.getSymbol;
  if (!money) return '0.00';
  const price = Number(money).toFixed(2);
  let newMoney = price;
  if (isConver) newMoney = converMoney(price, symbol.rate)
  const arr = newMoney.split('.');
  if (flag) return `<span class="price">${arr[0]}</span><span class="decimal">.${arr[1]}</span>`;
  return newMoney
}

export const converAboutMoney = (money, symbol, CnyItem) => {
  if (!money) return '0.00';
  money = typeof money === 'string' ? (money - 0) : money;
  let rate = Number(symbol.rate || 1)
  const newMoney = (money / rate).toFixed(2);
  return {
    CnyMoney: (money / (CnyItem?.rate || 1)).toFixed(2),
    newMoney
  }
}

export const MoneyAbouthtml = (money, flag = false) => {
  useSystem = useSystemStore();
  const symbol = useSystem.getSymbol;
  const rateList = useSystem.getRateList;
  const CnyItem = rateList.find(item => item.code === 'CNY');

  if (!money) return '0.00';
  const price = typeof money === 'string' ? (money - 0) : money;
  const { CnyMoney, newMoney } = converAboutMoney(price, symbol, CnyItem);
  const cnyArr = CnyMoney.split('.');
  const arr = newMoney.split('.');
  let html = `<span class="icon">${CnyItem?.symbol}</span><span class="price">${cnyArr[0]}</span><span class="decimal">.${cnyArr[1]}</span>`
  let rateHtml = `<span class="icon">${symbol.symbol}</span><span class="price">${arr[0]}</span><span class="decimal">.${arr[1]}</span>`
  if (flag) {
    if (symbol.code === 'CNY') {
      const USDItem = rateList.find(item => item.code === 'USD');
      const usdArr = (price / (USDItem?.rate || 1)).toFixed(2).split('.');
      rateHtml = `<span class="icon">${USDItem.symbol}</span><span class="price">${usdArr[0]}</span><span class="decimal">.${usdArr[1]}</span>`
    }
    return `${html}<span class="icon2">&nbsp;≈&nbsp;</span><span class="icon">${rateHtml}`;

  };
  return `<span class="icon">${CnyItem.symbol}</span>${CnyMoney}<span class="icon2">&nbsp;≈&nbsp;</span><span class="icon">${symbol.symbol}</span>${newMoney}`
}

export const TimeOut = (callback = () => { }, time = 2000) => {
  let timer = setTimeout(() => {
    callback();
    clearTimeout(timer);
  }, time)
  return timer;
}

export const getDeviceInfo = () => {
  return uni.getDeviceInfo();
}

export const getEnterOptions = () => {
  return uni.getEnterOptionsSync()
}

export const urlStrToArr = (str = "", separator = ",") => {
  return str
    .split(separator)
    .map((item) => item.trim())
    .filter((item) => item);
}

export const openUrlBlank = (url) => {

  if (!url || typeof url !== 'string') {
    console.error('无效的 URL：', url);
    return;
  }

  // #ifdef H5
  window.open(url, '_blank');
  // #endif

  // #ifdef APP-PLUS
  plus.runtime.openURL(url)
  // #endif
};

/**
 * 格式化货币显示 - 根据当前语言返回对应的货币符号
 * @param {number|string} amount 金额
 * @param {boolean} showAmount 是否显示金额，默认true
 * @returns {string} 格式化后的货币字符串
 */
export const formatCurrency = (amount, showAmount = true) => {
  useSystem = useSystemStore();
  const symbol = useSystem.getSymbol;
  if (!showAmount) {
    return symbol;
  }
  if (!amount && amount !== 0) {
    return `${symbol.symbol}0.00`;
  }
  const formattedAmount = Number(amount).toFixed(2);
  return `${symbol.symbol}${formattedAmount}`;
};