package com.mortals.xhx.module.sitestat.web;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.common.Rest;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.framework.web.BaseCRUDJsonBodyMappingController;
import com.mortals.xhx.common.code.PlatformTypeEnum;
import com.mortals.xhx.common.code.YesNoEnum;
import com.mortals.xhx.common.pdu.RespData;
import com.mortals.xhx.common.pdu.site.SitePdu;
import com.mortals.xhx.feign.site.ISiteFeign;
import com.mortals.xhx.module.site.model.SiteEntity;
import com.mortals.xhx.module.site.model.SiteQuery;
import com.mortals.xhx.module.site.service.SiteService;
import com.mortals.xhx.module.sitestat.model.SitestatEntity;
import com.mortals.xhx.module.sitestat.model.SitestatQuery;
import com.mortals.xhx.module.sitestat.service.SitestatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 站点统计
 *
 * @author zxfei
 * @date 2022-06-27
 */
@RestController
@RequestMapping("sitestat")
@Slf4j
public class SitestatController extends BaseCRUDJsonBodyMappingController<SitestatService, SitestatEntity, Long> {

    @Autowired
    private ISiteFeign siteFeign;

    @Value("${platform.type:cloud}")
    private String platFormType;//版本，默认云服务版本
    @Autowired
    private SiteService siteService;


    public SitestatController() {
        super.setModuleDesc("站点统计");
    }





    @Override
    protected void init(Map<String, Object> model, Context context) {
        super.init(model, context);
    }


    @Override
    protected int infoAfter(Long id, Map<String, Object> model, SitestatEntity entity, Context context) throws AppException {
        if (platFormType.equalsIgnoreCase(PlatformTypeEnum.STANDALONE.getValue())) {
            SiteEntity siteEntity = siteService.get(entity.getSiteId());
            if (!ObjectUtils.isEmpty(siteEntity)) {
                entity.setLng(siteEntity.getLongitude());
                entity.setLat(siteEntity.getLatitude());
                entity.setAddress(siteEntity.getDetailAddress());
                entity.setLeadingOfficial(siteEntity.getLeadingOfficial());
                entity.setLeadingOfficialTelephone(siteEntity.getLeadingOfficialTelephone());
            }
        } else {
            Rest<SitePdu> resp = siteFeign.info(entity.getSiteId());
            if (resp.getCode() == YesNoEnum.YES.getValue()) {
                entity.setLng(resp.getData().getLongitude());
                entity.setLat(resp.getData().getLatitude());
                entity.setAddress(resp.getData().getDetailAddress());
                entity.setLeadingOfficial(resp.getData().getLeadingOfficial());
                entity.setLeadingOfficialTelephone(resp.getData().getLeadingOfficialTelephone());
            }
        }
        return super.infoAfter(id, model, entity, context);
    }

    /**
     * 构建站点树
     */
    @GetMapping(value = "siteTree")
    public String siteTree() {
        JSONObject jsonObject = new JSONObject();
        try {
            String siteTree = this.service.getSiteTree(getContext());
            return siteTree;
        } catch (Exception e) {
            log.error("构建站点树异常", e);
            jsonObject.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
            jsonObject.put(KEY_RESULT_MSG, super.convertException(e));
        }
        return jsonObject.toJSONString();
    }


    /**
     * 站点列表
     */
    @GetMapping(value = "maplist")
    public Rest<List<SitestatEntity>> maplist() {
        try {
            if (platFormType.equalsIgnoreCase(PlatformTypeEnum.STANDALONE.getValue())) {
                SiteQuery siteQuery = new SiteQuery();
                if (!getContext().getUser().isAdmin()) {
                    List<Long> siteIdList = StrUtil.split(getContext().getUser().getSiteIds(), ",".charAt(0), -1, true, e -> Long.parseLong(e));
                    siteQuery.setIdList(siteIdList);
                }

                List<SitestatEntity> collect = siteService.find(siteQuery).stream().map(item -> {
                    SitestatEntity sitestatEntity = this.service.selectOne(new SitestatQuery().siteId(item.getId()));
                    if (!ObjectUtils.isEmpty(sitestatEntity)) {
                        sitestatEntity.setSiteId(item.getId());
                        sitestatEntity.setSiteCode(item.getSiteCode());
                        sitestatEntity.setSiteName(item.getSiteName());
                        sitestatEntity.setLng(item.getLongitude());
                        sitestatEntity.setLat(item.getLatitude());
                        sitestatEntity.setAddress(item.getDetailAddress());
                        sitestatEntity.setLeadingOfficial(item.getLeadingOfficial());
                        sitestatEntity.setLeadingOfficialTelephone(item.getLeadingOfficialTelephone());
                        return sitestatEntity;
                    }
                    return null;
                }).filter(f -> f != null).collect(Collectors.toList());
                return Rest.ok("获取成功", collect);
            } else {
                SitePdu sitePdu = new SitePdu();
                sitePdu.setPage(1);
                sitePdu.setSize(-1);
                if (!getContext().getUser().isAdmin()) {
                    List<Long> siteIdList = StrUtil.split(getContext().getUser().getSiteIds(), ",".charAt(0), -1, true, e -> Long.parseLong(e));
                    sitePdu.setIdList(siteIdList);
                }
                Rest<RespData<List<SitePdu>>> resp = siteFeign.list(sitePdu);
                //根据站点id 获取统计信息
                List<SitestatEntity> collect = resp.getData().getData().stream().map(item -> {
                    SitestatEntity sitestatEntity = this.service.selectOne(new SitestatQuery().siteId(item.getId()));
                    if (!ObjectUtils.isEmpty(sitestatEntity)) {
                        sitestatEntity.setSiteId(item.getId());
                        sitestatEntity.setSiteCode(item.getSiteCode());
                        sitestatEntity.setSiteName(item.getSiteName());
                        sitestatEntity.setLng(item.getLongitude());
                        sitestatEntity.setLat(item.getLatitude());
                        sitestatEntity.setAddress(item.getDetailAddress());
                        sitestatEntity.setLeadingOfficial(item.getLeadingOfficial());
                        sitestatEntity.setLeadingOfficialTelephone(item.getLeadingOfficialTelephone());
                        return sitestatEntity;
                    }
                    return null;
                }).filter(f -> f != null).collect(Collectors.toList());
                return Rest.ok("获取成功", collect);
            }
        } catch (Exception e) {
            log.error("获取异常", e);
            return Rest.fail("获取异常！");
        }

    }


    /**
     * 站点信息
     */
    @GetMapping(value = "siteInfo")
    public String siteInfo(Long siteId) {
        JSONObject jsonObject = new JSONObject();
        String busiDesc = this.getModuleDesc() + "获取站点";
        jsonObject.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
        try {
            if (platFormType.equalsIgnoreCase(PlatformTypeEnum.STANDALONE.getValue())) {
                SiteEntity siteEntity = siteService.get(siteId, getContext());
                if (!ObjectUtils.isEmpty(siteEntity)) {
                    jsonObject.put(KEY_RESULT_DATA, siteEntity);
                    jsonObject.put(KEY_RESULT_MSG, busiDesc + "成功！");
                }
            } else {
                Rest<SitePdu> resp = siteFeign.info(siteId);
                if (resp.getCode() == YesNoEnum.YES.getValue()) {
                    jsonObject.put(KEY_RESULT_DATA, resp.getData());
                }
                jsonObject.put(KEY_RESULT_MSG, busiDesc + "成功！");
            }

        } catch (Exception e) {
            log.error("获取站点异常", e);
            jsonObject.put(KEY_RESULT_CODE, VALUE_RESULT_FAILURE);
            jsonObject.put(KEY_RESULT_MSG, super.convertException(e));
        }
        return jsonObject.toJSONString();
    }


}