package com.huiju.estateagents.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huiju.estateagents.common.CommConstant;
import com.huiju.estateagents.entity.TaPersonPositon;
import com.huiju.estateagents.entity.TdCity;
import com.huiju.estateagents.mapper.TdCityMapper;
import com.huiju.estateagents.service.ITdCityService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author jobob
 * @since 2019-08-07
 */
@Service
public class TdCityServiceImpl extends ServiceImpl<TdCityMapper, TdCity> implements ITdCityService {

    private Logger logger = LoggerFactory.getLogger(TdCityServiceImpl.class);

    @Autowired
    TdCityMapper tdCityMapper;

    @Autowired
    private TaPersonServiceImpl taPersonService;

    public List<TdCity> selectCity(String leveltype, String status) {
        return tdCityMapper.selectCity(leveltype, status);
    }


    @Override
    public List<TdCity> selectWxCity(String leveltype, Integer orgId) {
        List<TdCity> tdCityList = tdCityMapper.selectWxCity(orgId);
        return tdCityList;
    }

    /**
     * 根据经纬度获取城市详情信息
     *
     * @param location
     * @return
     */
    @Override
    public TdCity getLocationCity(String location, Integer orgId, String personId) {
        if (null == location) {
            return tdCityMapper.getOrgDefaultCity(orgId);
        }

        //获取高德地图的坐标
        String amapString = CommConstant.AMAP_HTTP + "?location=" + location + "&key=" + CommConstant.AMAP_KEY;
        RestTemplate restTemplate = new RestTemplate();
        String forObject = restTemplate.getForObject(amapString, String.class);
        JSONObject jsonObject = JSONObject.parseObject(forObject);
        //返回城市信息
        if (jsonObject.getString("status").equals("1")) {
            JSONObject addressComponent = jsonObject.getJSONObject("regeocode").getJSONObject("addressComponent");
            String citycode = addressComponent.getString("citycode");
            // 保存用户位置信息
            if (StringUtils.isNotBlank(personId)) {
                ExecutorService threadPool = Executors.newCachedThreadPool();
                threadPool.execute(() -> {
                    logger.info("保存用户位置信息开始");
                    TaPersonPositon record = new TaPersonPositon();
                    try {
                        String[] locationArr = location.split(",");
                        String address = jsonObject.getJSONObject("regeocode").getString("formatted_address");
                        record.setPersonId(personId);
                        record.setLon(locationArr[0]);
                        record.setLat(locationArr[1]);
                        record.setCitycode(citycode);
                        record.setCountry(addressComponent.getString("country"));
                        record.setProvince(addressComponent.getString("province"));
                        record.setCity(addressComponent.getString("city"));
                        record.setDistrict(addressComponent.getString("district"));
                        record.setAddress(address);
                        record.setCreateTime(LocalDateTime.now());
                        record.setOrgId(orgId);
                        Integer positionResult = taPersonService.savePersonPosition(record);
                        logger.info("保存用户位置信息返回：{}", positionResult);
                    } catch (Exception e) {
                        logger.error("保存用户位置信息 异常：", e);
                    }
                });
            }

            QueryWrapper<TdCity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("citycode", citycode);
            queryWrapper.eq("leveltype", 2);
            List<TdCity> tdCities = tdCityMapper.selectList(queryWrapper);
            if (tdCities.size() > 0) {
                List<TdCity> cityList = selectWxCity(null, orgId);
                Integer cityId = tdCities.get(0).getId();
                for (TdCity tdCity : cityList) {
                    if (tdCity.getId().equals(cityId)) {
                        return tdCity;
                    }
                }
            }
//            return null;
        }

        // 没有匹配到则返回默认城市
        return tdCityMapper.getOrgDefaultCity(orgId);
    }

}
