import store from '../../../store';
import rsCode from '../../../utils/rsCode';
import {
  getToken
} from 'utils/auth';

function loadFromServer(codes) {
  if (!codes) {
    console.error(' load region with no code');
  }
  let headerAuthorization = undefined;
  if (store.getters.token) {
    headerAuthorization = getToken(); // 让每个请求携带token--['Authorization']为自定义key 请根据实际情况自行修改
  }
  // url : baseURL+"",//路径
  let rs;
  $.ajax({
    type: 'get',
    url: process.env.BASE_API + '/vehicle/sysRegion',
    async: false,
    headers: {
      Authorization: headerAuthorization
    },
    dataType: 'json',
    data: {
      idListJson: JSON.stringify(codes)
    },
    success: function (result) {
      // 返回数据根据结果进行相应的处理
      if (result.code === rsCode.RS_CODE_SUC) {
        rs = result.data;
      } else {
        console.log('请求地区信息出错。');
      }
    },
    error: function () {
      console.log('请求地区信息出错。');
    }
  });
  return rs;
}


function loadSonsFromServer(code) {
  if (!code) {
    console.error(' load region with no code');
  }
  let headerAuthorization = undefined;
  if (store.getters.token) {
    headerAuthorization = getToken(); // 让每个请求携带token--['Authorization']为自定义key 请根据实际情况自行修改
  }
  // url : baseURL+"",//路径
  let rs;
  $.ajax({
    type: 'get',
    url: process.env.BASE_API + '/vehicle/sysRegion/sons/' + code,
    headers: {
      Authorization: headerAuthorization
    },
    async: false,
    data: {},
    success: function (result) {
      // 返回数据根据结果进行相应的处理
      if (result.code === rsCode.RS_CODE_SUC) {
        rs = result.data;
      } else {
        console.log('请求地区信息出错。');
      }
    },
    error: function () {
      console.log('请求地区信息出错。');
    }
  });

  return rs;
}

export function getSonRegionByCodes(code) {
  let actualCode = code;
  if (!actualCode) {
    actualCode = rsCode.REGION_CODE_CHAINA;
  }
  let sonRegions = store.getters.sonRegions(actualCode);
  if (!sonRegions) {
    let datas = loadSonsFromServer(actualCode);
    store.dispatch("cacheSonRegions", {
      code: actualCode,
      sons: datas
    });
    sonRegions = datas;
  }

  // 创建axios实例
  return sonRegions;
}


export function getRegionByCodes(codes) {
  if (!codes) {
    console.error('empty region codes');
    return null;
  }
  let regions = [];
  let hasLoaded = true;
  for (let index in codes) {
    let region = store.getters.region(codes[index]);
    if (!region) {
      hasLoaded = false;
      break;
    }
    regions = [...regions, region];
  }

  if (!hasLoaded) {
    let datas = loadFromServer(codes);
    for (let index = datas.length - 1; index >= 0; index--) {
      regions = [datas[index], ...regions];
    }
    store.dispatch("cacheRegion", regions);
  }
  return regions;
}