// eslint-disable-next-line camelcase,@typescript-eslint/naming-convention
const reg_address =
  '(?<province>[^省]+自治区|.*?省|.*?行政区|.*?市)(?<city>[^市]+自治州|.*?地区|.*?行政单位|.+盟|市辖区|.*?市|.*?县)(?<county>[^县]+县|.+?(区{1})|.+市|.+旗|.+海域|.+岛)?(?<village>.*)';

function formatLocation(str: string) {
  if (!str) return;
  // 中国4个直辖市
  const municipality = ['重庆', '北京', '上海', '天津'];
  const subStr = str.substring(0, 2);
  const isExist = municipality.includes(subStr);
  if (isExist) {
    // eslint-disable-next-line no-param-reassign
    str = str.substring(2, str.length - 1);
    // eslint-disable-next-line no-param-reassign
    str = `${subStr}省${str}`;
  }
  const addr = str.match(reg_address);
  if (!addr) return;
  const groups = { ...addr.groups };
  // 如果是直辖市，截取地址后，把省字替换成市
  if (isExist) {
    groups.province = groups.province.replace('省', '');
  }
  // eslint-disable-next-line consistent-return
  return groups;
}
export default formatLocation;

/**
 * 格式化地区信息
 * @param {String} str 要格式化的地区信息
 * @returns Object {province: "", city: "", detail: ""}
 */
export function formatLocationStr(str = '') {
  const result = {
    province: '',
    city: '',
    detail: '',
  };

  const provinceRegExp = /(.+?(省|自治区))(.*)/;
  const provinceList = str.match(provinceRegExp);

  let restStr = str;
  if (provinceList) {
    // eslint-disable-next-line prefer-destructuring
    result.province = provinceList[1];
    // eslint-disable-next-line prefer-destructuring
    restStr = provinceList[3];
  }

  const cityRegExp = /(.+?(市|自治州|行政区))(.*)/;
  const cityList = restStr.match(cityRegExp);
  if (cityList) {
    // eslint-disable-next-line prefer-destructuring
    result.city = cityList[1];
    // eslint-disable-next-line prefer-destructuring
    result.detail = cityList[3];
  } else {
    result.detail = restStr;
  }

  // console.log(result)
  return result;
}
