import { ApiResult } from '@/configs/axios'
import ConfigService, { DownloadParameter } from '@/services/ConfigService'
import { array } from '@amcharts/amcharts4/core'
import { ElLoading, ElMessage } from 'element-plus'
import { padStart } from 'lodash'

/**
 * 补足数字位数
 * @param digit 数字
 * @param len 位数
 */
export const fillDigit = (digit: number, len: number) => {
  return padStart('' + digit, len, '0')
}

export const openNewBlank = (path:string) => {
  if(path!=''){
    const url = path.includes('http://') || path.includes('https://') ? path : `${window.location.origin}${path}`
    window.open(url, '_blank')
  }
}
export const downLoadFile = async (parameter:DownloadParameter)=>{
  const loading = ElLoading.service({
    lock:true,
    text:'加载中，请稍等'
  })
  const response = await ConfigService.GetTripDownloadTokenAsync(parameter)
  loading.close()
  if(response.data.resultCode==ApiResult.SUCCESS){
    window.open(`${window.location.origin}/download/${response.data.data}`, '_blank')
  }else{
    ElMessage.error({message:response.data.message})
  }
  
}
export const openCustomerService = ()=>{
  const url = 'https://work.weixin.qq.com/kfid/kfc378aada578ca8b0e'
  window.open(url, '_blank')
}
export const createSaleEditorLink = (id:number,tid:number,type:1|2,pid:number,ep:0|1,cp:0|1) =>{
  return `/editor/${id}/${tid}/${type}/${pid}/e/${ep}/c/${cp}`
}
export const createSaleCreateLink = (tid:number,type:1|2) =>{
  return `/editor/${tid}/${type}`
}
export const createOpEditorLink = (configId:number,tempType:number,tid:number) =>{
  return `/team_editor/${configId}/${tempType}/${tid}`
}
export const managerTemplateLink = (tid:number,type:1|2) =>{
  return `/manager_template/${tid}/${type}`
}
export const createPlayLink = (id:number,loginId:number,status:1|2) =>{
  return `/play/${id}/${loginId}/${status}`
}
/**
 * 判断设备
 */
export const isPC = () => {
  return !navigator.userAgent.match(/(iPhone|iPod|iPad|Android|Mobile|BlackBerry|Symbian|Windows Phone)/i)
}

export const query = (url?:string)=>{
  url = url??location.href
  let str = url.substr(url.indexOf('?') + 1)
  const arr = str.split('&')
  let json = {} as any
  for(let i = 0; i < arr.length; i++) {
    let item = arr[i].split('=')
    json[item[0]] = item[1]
  }

  if(url.indexOf(process.env.VUE_APP_SHARE_URL)!=-1&&!json.ViewSlideshow){
    json = {
      SalesTripId: str.slice(2)
    } as any
    return json
  }else return json
}

/**
 * 提取字符串中的文字
 */
export const getHtmlPlainText = (html_str:string) => {
  let re = new RegExp('<[^<>]+>', 'g')
  if (html_str) {
    let text = html_str.replace(re, '')
    return text
  } else {
    return ''
  }
}

// 计算距离天数
 export const dateDiffer = (DateEnd: string) => {
  //date1结束时间
  let date1 = new Date(DateEnd);
  //date2当前时间
  let date2 = new Date();
  date1 = new Date(date1.getFullYear(), date1.getMonth(), date1.getDate());
  date2 = new Date(date2.getFullYear(), date2.getMonth(), date2.getDate());
  const diff = date1.getTime() - date2.getTime(); //目标时间减去当前时间
  const diffDate = diff / (24 * 60 * 60 * 1000);  //计算当前时间与结束时间之间相差天数
  return diffDate
}

export const dateFormat = (value: number|string|Date = Date.now(), format = 'YYYY-MM-DD HH:mm:ss'): string => {
  if (typeof value === 'number' || typeof value === 'string') {
    var date = new Date(value)
  } else {
    var date = value
  }
  let showTime = format
  if (showTime.includes('SSS')) {
    const S = String(date.getMilliseconds())
    showTime = showTime.replace('SSS', S.padStart(3, '0'))
  }
  if (showTime.includes('YY')) {
    const Y = String(date.getFullYear())
    showTime = showTime.includes('YYYY') ? showTime.replace('YYYY', Y) : showTime.replace('YY', Y.slice(2, 4))
  }
  if (showTime.includes('M')) {
    const M = String(date.getMonth() + 1)
    showTime = showTime.includes('MM') ? showTime.replace('MM', M.padStart(2, '0')) : showTime.replace('M', M)
  }
  if (showTime.includes('D')) {
    const D = String(date.getDate())
    showTime = showTime.includes('DD') ? showTime.replace('DD', D.padStart(2, '0')) : showTime.replace('D', D)
  }
  if (showTime.includes('H')) {
    const H = String(date.getHours())
    showTime = showTime.includes('HH') ? showTime.replace('HH', H.padStart(2, '0')) : showTime.replace('H', H)
  }
  if (showTime.includes('m')) {
    const m = String(date.getMinutes())
    showTime = showTime.includes('mm') ? showTime.replace('mm', m.padStart(2, '0')) : showTime.replace('m', m)
  }
  if (showTime.includes('s')) {
    const s = String(date.getSeconds())
    showTime = showTime.includes('ss') ? showTime.replace('ss', s.padStart(2, '0')) : showTime.replace('s', s)
  }
  return showTime
}

export const formatDateTimeToRead = (dateStr:string,prefix:string='') =>{
  let minute = 1000 * 60;
  let hour = minute * 60;
  let day = hour * 24;
  let halfamonth = day * 15;
  let month = day * 30;
  let dateTimeStamp = Date.parse(dateStr.replaceAll('-',"/"))
  let result = ''
  let now = new Date().getTime();
  let diffValue = now - dateTimeStamp;
  if(diffValue < 0){
  //若日期不符则弹出窗口告之
  //alert("结束日期不能小于开始日期！");
    return ''
  }
  let monthC =diffValue/month;
  let weekC =diffValue/(7*day);
  let dayC =diffValue/day;
  let hourC =diffValue/hour;
  let minC =diffValue/minute;
  if(monthC>=1 && monthC<=12){
    result=parseInt(monthC.toString()) + "月前";
  }
  else if(monthC>12){
    result=dateStr
  }
  else if(weekC>=1){
    result=parseInt(weekC.toString()) + "周前";
  }
  else if(dayC>=1){
    result=parseInt(dayC.toString()) +"天前";
  }
  else if(hourC>=1){
    result=parseInt(hourC.toString()) +"小时前";
  }
  else if(minC>=1){
    result=parseInt(minC.toString()) +"分钟前";
  }else
    result= "刚刚";
  return prefix+result;
}

// 暂无数据img
export const noDataImg = (type:Number) =>{
  if(type==1) return require('@/assets/img/noData.png')
  if(type==2) return require('@/assets/img/theEend.png')
}

// 主色值
export const DominantColour = () =>{
  return [
    {ColorName:'红',ColorValue:'#E43939',Id:1},
    {ColorName:'橙',ColorValue:'#F79A2C',Id:2},
    {ColorName:'黄',ColorValue:'#FFF60B',Id:3},
    {ColorName:'绿',ColorValue:'#3DD948',Id:4},
    {ColorName:'青',ColorValue:'#39CAE4',Id:5},
    {ColorName:'蓝',ColorValue:'#2C31F1',Id:6},
    {ColorName:'紫',ColorValue:'#7A39E4',Id:7},
    {ColorName:'玫红',ColorValue:'#E65FC1',Id:8},
    {ColorName:'棕色',ColorValue:'#D0B478',Id:9},
    {ColorName:'白',ColorValue:'#FFFFFF',Id:10},
    {ColorName:'黑',ColorValue:'#000000',Id:11},
    {ColorName:'灰',ColorValue:'#BABABA',Id:12},
  ]
}

export const getRgbLevel = (colorarr:any) => {
  return colorarr[0] * 0.299 + colorarr[1] * 0.587 + colorarr[2] * 0.114
}

// base64 图
export const dataURLtoFile = (file:any) => {
  const reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onload = (e:any) => {
      const base64 = e.target.result
      // 添加 base64 文件，这里假设文件名为 'file'
      let basestr = base64.split(',')
      return base64
  };
}