import moment from "moment";

import {
  post,
  get
} from '@/utils/request'
import Cookies from 'js-cookie'

//根据value值回显字典label值
export function dictDataEcho(value, arr) {
  if (value && arr) {
    value = value + "";
    const current = arr.find((x) => x.dictKey === value);
    if (current != undefined && current.dictValue) {
      return current.dictValue;
    }
    return "";
  }
  return "";
}

export function getDict(key) {
  return new Promise((resolve, reject) => {
    let dictObj = {}
    let arr = {}
    let num = 0
    if(!sessionStorage.getItem('dict')) {
      sessionStorage.setItem('dict', JSON.stringify(dictObj))
    }else{
      dictObj = JSON.parse(sessionStorage.getItem('dict'))
    }
    for (let i = 0; i < key.length; i++) {
      const element = key[i];
      if(dictObj[element]) {
        arr[element] = dictObj[element]
        num++
        if(num === key.length) {
          resolve(arr);
        }
      }else{
        post("/dictTenantData/page", {
          pageNum: 1,
          pageSize: 999,
          tenantId: Cookies.get('tenantId'),
          dictCode: element,
        }).then(res => {
          dictObj[element] = res.rows
          arr[element] = res.rows
          sessionStorage.setItem('dict', JSON.stringify(dictObj))
          num++
          console.log(num)
          if(num === key.length) {
            resolve(arr);
          }
        })
      }
    }
  })
  
}

// 金额千分符
export function moneyFormat(s, n) {
  if (s) {
    s = s + "";
    let str = s.slice(0, 1);
    if (str === "-") {
      s = s.slice(1, s.length);
    }
    n = n > 0 && n <= 20 ? n : 2;
    s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
    var l = s.split(".")[0].split("").reverse(),
      r = s.split(".")[1];
    var t = "";
    for (let i = 0; i < l.length; i++) {
      t += l[i] + ((i + 1) % 3 == 0 && i + 1 != l.length ? "," : "");
    }
    let result = t.split("").reverse().join("") + "." + r;
    if (str === "-") {
      return "-" + result;
    } else {
      return result;
    }
  } else {
    return "0.00";
  }
}

// 计算该日期是星期几
export function calculationWeek(val, format) {
  let weekArrayList = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
  let index = new Date(moment(val, format).format("yyyy-MM-DD")).getDay();
  let week = weekArrayList[index];
  return week;
}
