import moment from 'moment';
import { getDefaultCurrency } from '@/utils/request';
export function fixedZero(val) {
  return val * 1 < 10 ? `0${val}` : val;
}

export function getTimeDistance(type) {
  const now = new Date();
  const oneDay = 1000 * 60 * 60 * 24;

  if (type === 'today') {
    now.setHours(0);
    now.setMinutes(0);
    now.setSeconds(0);
    return [moment(now), moment(now.getTime() + (oneDay - 1000))];
  }

  if (type === 'week') {
    let day = now.getDay();
    now.setHours(0);
    now.setMinutes(0);
    now.setSeconds(0);

    if (day === 0) {
      day = 6;
    } else {
      day -= 1;
    }

    const beginTime = now.getTime() - (day * oneDay);

    return [moment(beginTime), moment(beginTime + ((7 * oneDay) - 1000))];
  }

  if (type === 'month') {
    const year = now.getFullYear();
    const month = now.getMonth();
    const nextDate = moment(now).add(1, 'months');
    const nextYear = nextDate.year();
    const nextMonth = nextDate.month();

    return [moment(`${year}-${fixedZero(month + 1)}-01 00:00:00`), moment(moment(`${nextYear}-${fixedZero(nextMonth + 1)}-01 00:00:00`).valueOf() - 1000)];
  }

  if (type === 'year') {
    const year = now.getFullYear();

    return [moment(`${year}-01-01 00:00:00`), moment(`${year}-12-31 23:59:59`)];
  }
}

export function getPlainNode(nodeList, parentPath = '') {
  const arr = [];
  nodeList.forEach((node) => {
    const item = node;
    item.path = `${parentPath}/${item.path || ''}`.replace(/\/+/g, '/');
    item.exact = true;
    if (item.children && !item.component) {
      arr.push(...getPlainNode(item.children, item.path));
    } else {
      if (item.children && item.component) {
        item.exact = false;
      }
      arr.push(item);
    }
  });
  return arr;
}

export function digitUppercase(n) {
  const fraction = ['角', '分'];
  const digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
  const unit = [
    ['元', '万', '亿'],
    ['', '拾', '佰', '仟'],
  ];
  let num = Math.abs(n);
  let s = '';
  fraction.forEach((item, index) => {
    s += (digit[Math.floor(num * 10 * (10 ** index)) % 10] + item).replace(/零./, '');
  });
  s = s || '整';
  num = Math.floor(num);
  for (let i = 0; i < unit[0].length && num > 0; i += 1) {
    let p = '';
    for (let j = 0; j < unit[1].length && num > 0; j += 1) {
      p = digit[num % 10] + unit[1][j] + p;
      num = Math.floor(num / 10);
    }
    s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s;
  }

  return s.replace(/(零.)*零元/, '元').replace(/(零.)+/g, '零').replace(/^整$/, '零元整');
}
// 金额精度化
/**
 * @param {amount} 需要格式化的金额
 * @param {flag}   区分是单价格式化还是金额格式   price：单价格式  amount： 金额格式
 */
export function amountPrecision (amount, flag) {
  const precision = flag ? flag : 'price';
  const amt = amount ? amount : 0;
  const currencySign = getDefaultCurrency().currencySign;
  // const scale = precision == 'price' ? getDefaultCurrency().currencyPriceScale : getDefaultCurrency().currencyAmountScale;
  const scale = 2;
  const newAmount = currencySign + amt.toFixed(scale);
  return newAmount;
}

export const SpecificationMethod = (freeVallist, data, callback) => {
  // step1
  const step1Data = _proCateSelected(freeVallist, data);
  // step2
  const step2Data = _companyVfree(data, step1Data);
  // step3
  const step3Data = _disableTrue(data, step2Data);

  // callback
  callback(step3Data);
};

const _proCateSelected = (freeVallist, data) => {
  // freeVallist是自由辅助属性库，data是物料下所有商品
  const freeVal = freeVallist,
    step1ReturnVal = {};
  // 找到所选的标签存入checktrue
  // checktrue存入所选中id
  let checktrue = [],
    // checkname存入所选中name
    checkname = [],
    // grouplists存 所有规格id
    grouplists = [];
  for (let valFirst of freeVal) {
    for (let valSecond of valFirst.values) {
      // 将自由辅助属性库 所有id放在一个数组里
      grouplists.push(valSecond.id);
      // 把选中的属性放到checktrue
      if (checkedKey(valSecond, "isChecked") && valSecond.isChecked == true) {
        checktrue.push(valSecond.id);
        checkname.push(valSecond.name);
      }
      if (checkedKey(valSecond, "isDisabled")) {
        delete valSecond.isDisabled;
      }
    }
  }

  step1ReturnVal.checktrue = checktrue;
  step1ReturnVal.grouplists = grouplists;
  step1ReturnVal.checkname = checkname;
  return step1ReturnVal;
};

// 比较选中的与同类型商品自由属性 (第二步)
const _companyVfree = (data, step1Data) => {
  // 物料下所有商品的自由辅助属性
  const Vfrees = data.goodsInfos,
    step2ReturnVal = {};

  let checktrue = step1Data.checktrue,
      grouplists = step1Data.grouplists,
      checkname = step1Data.checkname,
      selectRelation = [],
      Vfreelists = [],
      newseclectR = [];
  // 将选择的值与物料所有属性做包含判断
  for (let vfreeFirst of Object.keys(Vfrees)) {
    if (_isContained(Vfrees[vfreeFirst], checktrue)) {
      selectRelation = selectRelation.concat(Vfrees[vfreeFirst]);
      newseclectR.push([...Vfrees[vfreeFirst]]);
    }
    for (let vfreeSecond of Vfrees[vfreeFirst]) {
      Vfreelists.push(vfreeSecond);
    }
  }

  selectRelation = Array.from(new Set(selectRelation));
  Vfreelists = Array.from(new Set(Vfreelists));
  const nonExist = _comvaluesIs(grouplists, Vfreelists);

  step2ReturnVal.selectRelation = selectRelation;
  step2ReturnVal.nonExist = nonExist;
  step2ReturnVal.checktrue = checktrue;
  step2ReturnVal.checkname = checkname;
  return step2ReturnVal;
};

//对无商品自由属性变虚线框 （第三步）
const _disableTrue = (data, step2Data) => {
  const freeArr = data.polyAttrsDtoList,
    step3ReturnVal = {};
  let selectRelation = step2Data.selectRelation,
    nonExist = step2Data.nonExist,
    checktrue = step2Data.checktrue,
    checkname = step2Data.checkname;
  for (let selectRelatVal of selectRelation) {
    for (let freeArrFirst of freeArr) {
      for (let freeArrSecond of freeArrFirst.values) {
        if (nonExist.indexOf(freeArrSecond.id) != -1) {
          freeArrSecond.isDisableTrue = true;
        }
        if (freeArrSecond.id == selectRelatVal) {
          freeArrSecond.isDisabled = false;
        } else if (!checkedKey(freeArrSecond, "isDisabled")) {
          freeArrSecond.isDisabled = true;
        }
      }
    }
  }

  step3ReturnVal.checktrue = checktrue;
  step3ReturnVal.checkname = checkname;
  step3ReturnVal.freeArr = freeArr;
  step3ReturnVal.data = data;

  return step3ReturnVal;
};

// 对象中找key值是否存在
export const checkedKey = (val, key) => {
  const flag = Object.prototype.hasOwnProperty.call(val, key);
  return flag;
};

// a是否包含b，包含返回true
export const _isContained = (a, b) => {
  if (!(a instanceof Array) || !(b instanceof Array)) return false;
  if (a.length < b.length) return false;
  var aStr = a.toString();
  for (var i = 0, len = b.length; i < len; i++) {
    if (aStr.indexOf(b[i]) == -1) return false;
  }
  return true;
};

// 数组是否相等
export const _isArrEqual = (a, b) => {
  if (!(a instanceof Array) || !(b instanceof Array)) return false;
  if (a.length != b.length) return false;
  // 数组去重排序
  const aval = Array.from(new Set([...a].sort())).toString();
  const bval = Array.from(new Set([...b].sort())).toString();
  if (aval == bval) return true;
};

// 比较所有聚合列表中是否都存在
export const _comvaluesIs = (val, nextval) => {
  let resval = [];
  if (!(val instanceof Array) || !(nextval instanceof Array)) return false;
  for (let i = 0; i < val.length; i++) {
    if (nextval.indexOf(val[i]) == -1) {
      resval.push(val[i]);
    }
  }
  return resval;
};

// 删除指定元素
export const _removeByValue = (arr, val) => {
  for (var arrVal of arr) {
    if (arrVal == val) {
      arr.splice(i, 1);
      break;
    }
  }
};

//除法函数，用来得到精确的除法结果
//返回值：arg1除以arg2的精确结果
export const accDiv = (arg1, arg2) => {
  var t1 = 0,
    t2 = 0,
    r1,
    r2;
  try {
    t1 = arg1.toString().split(".")[1].length;
  } catch (e) {}
  try {
    t2 = arg2.toString().split(".")[1].length;
  } catch (e) {}
  // with (Math) {
  r1 = Number(arg1.toString().replace(".", ""));
  r2 = Number(arg2.toString().replace(".", ""));
  return r1 / r2 * Math.pow(10, t2 - t1);
  // }
};




//乘法函数，用来得到精确的乘法结果
//返回值：arg1乘以arg2的精确结果
export const accMul = (arg1, arg2) => {
  var m = 0,
    s1 = arg1.toString(),
    s2 = arg2.toString();

  try {
    m += s1.split(".")[1].length;
  } catch (e) {}
  try {
    m += s2.split(".")[1].length;
  } catch (e) {}
  return (
    Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m)
  );
};
