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

import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.annotation.UnAuth;
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.base.system.param.service.ParamService;
import com.mortals.xhx.module.site.model.SiteEntity;
import com.mortals.xhx.module.site.model.SiteQuery;
import com.mortals.xhx.module.site.model.SiteTreeSelect;
import com.mortals.xhx.module.site.service.SiteService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

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

/**
 * 站点
 *
 * @author zxfei
 * @date 2022-01-20
 */
@RestController
@RequestMapping("site")
@Slf4j
public class SiteController extends BaseCRUDJsonBodyMappingController<SiteService, SiteEntity, Long> {

    @Autowired
    private ParamService paramService;


    public SiteController() {
        super.setModuleDesc("站点");
    }

    @Override
    protected void init(Map<String, Object> model, Context context) {
        this.addDict(model, "haveSonArea", paramService.getParamBySecondOrganize("Site", "haveSonArea"));
        this.addDict(model, "workday1", paramService.getParamBySecondOrganize("Site", "workday1"));
        this.addDict(model, "workday2", paramService.getParamBySecondOrganize("Site", "workday2"));
        this.addDict(model, "workday3", paramService.getParamBySecondOrganize("Site", "workday3"));
        this.addDict(model, "workday4", paramService.getParamBySecondOrganize("Site", "workday4"));
        this.addDict(model, "workday5", paramService.getParamBySecondOrganize("Site", "workday5"));
        this.addDict(model, "workday6", paramService.getParamBySecondOrganize("Site", "workday6"));
        this.addDict(model, "workday7", paramService.getParamBySecondOrganize("Site", "workday7"));
        this.addDict(model, "level", paramService.getParamBySecondOrganize("Site", "level"));
        this.addDict(model, "building", paramService.getParamBySecondOrganize("Site", "building"));
        this.addDict(model, "isSite", paramService.getParamBySecondOrganize("Site", "isSite"));
        this.addDict(model, "status", paramService.getParamBySecondOrganize("Site", "status"));
       super.init(model, context);
    }


    /**
     * 构建站点树
     */
    @GetMapping(value = "siteTree")
    public String siteTree() {
        JSONObject jsonObject = new JSONObject();
        Map<String, Object> model = new HashMap<>();
        String busiDesc = this.getModuleDesc() + "构建站点树";
        try {
            List<SiteTreeSelect> siteTree = this.service.getSiteTree(getContext());
            if (ObjectUtils.isEmpty(siteTree)) {
                log.info("为初始化站点树，重新构建！");
                siteTree = this.service.siteTree(getContext());
            }
            model.put("siteTree", siteTree);
            this.init(model, getContext());
            recordSysLog(request, busiDesc + " 【成功】");
            jsonObject.put(KEY_RESULT_DATA, model);
            jsonObject.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
        } 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();
    }


    /**
     * 根据区域编码查询站点列表
     */
    @PostMapping(value = "getFlatSitesByAreaCode")
    @UnAuth
    public String getFlatSitesByAreaCode(@RequestBody SiteQuery site) {
        JSONObject jsonObject = new JSONObject();
        Map<String, Object> model = new HashMap<>();
        String busiDesc = "根据区域编码查询站点列表" + this.getModuleDesc();
        try {
            List<SiteEntity> siteEntityList = this.service.getFlatSitesByAreaCode(site.getAreaCode(), getContext());
            recordSysLog(request, busiDesc + " 【成功】");
            jsonObject.put(KEY_RESULT_DATA, siteEntityList);
            jsonObject.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
            jsonObject.put(KEY_RESULT_MSG, "查询站点列表成功！");
        } 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();
    }


    /**
     * 根据区域id查询站点列表ids
     */
    @PostMapping(value = "getFlatSitesByAreaIds")
    @UnAuth
    public String getFlatSitesByAreaIds(@RequestBody SiteQuery site) {
        JSONObject jsonObject = new JSONObject();
        Map<String, Object> model = new HashMap<>();
        String busiDesc = "根据区域编码查询站点列表" + this.getModuleDesc();
        try {
            String siteIds = site.getAreaCodeList().stream().flatMap(areaId ->
                    this.service.getFlatSitesByAreaCode(areaId, getContext()).stream()
            ).map(item -> item.getId().toString()).distinct().collect(Collectors.joining(","));

            recordSysLog(request, busiDesc + " 【成功】");
            jsonObject.put(KEY_RESULT_DATA, siteIds);
            jsonObject.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
            jsonObject.put(KEY_RESULT_MSG, "查询站点列表成功！");
        } 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();
    }

    /**
     * 根据站点id查询站点列表子集，包含当前站点
     */
    @PostMapping(value = "getFlatSitesBySiteId")
    @UnAuth
    public String getFlatSitesBySiteId(@RequestBody SiteQuery site) {
        JSONObject jsonObject = new JSONObject();
        Map<String, Object> model = new HashMap<>();
        String busiDesc = "根据站点id查询站点列表子集" + this.getModuleDesc();
        try {
            List<SiteEntity> siteEntityList = this.service.getFlatSitesBySiteId(site.getId(), getContext());
            recordSysLog(request, busiDesc + " 【成功】");
            jsonObject.put(KEY_RESULT_DATA, siteEntityList);
            jsonObject.put(KEY_RESULT_CODE, VALUE_RESULT_SUCCESS);
            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();
    }


    @Override
    protected int infoAfter(Long id, Map<String, Object> model, SiteEntity entity, Context context) throws AppException {
        this.service.changeUrlPath(entity);
        return super.infoAfter(id, model, entity, context);
    }

    /**
     * 条件查询，无分页信息
     * @param query
     * @return
     */
    @PostMapping({"list/noPage"})
    @UnAuth
    public Rest<Object> getList(@RequestBody SiteQuery query) {
        Rest<Object> ret = new Rest();
        Map<String, Object> model = new HashMap();
        Context context = this.getContext();
        String busiDesc = "查询" + this.getModuleDesc();
        int code=1;
        try {
            if(CollectionUtils.isNotEmpty(query.getAreaCodeList())){
                List<SiteEntity> siteEntityList= query.getAreaCodeList().parallelStream().flatMap(areaId ->
                        this.service.getFlatSitesByAreaCode(areaId, getContext()).stream()
                ).distinct().collect(Collectors.toList());
                model.put("data", siteEntityList);
            }else {
                List<SiteEntity> result = this.getService().find(query, context);
                model.put("data", result);
            }
            model.put("message_info", busiDesc + "成功");
            this.recordSysLog(this.request, busiDesc + " 【成功】");
        } catch (Exception var9) {
            code = -1;
            this.doException(this.request, busiDesc, model, var9);
        }
        //this.init(model, context);
        ret.setCode(code);
        ret.setData(model);
        //ret.setDict(model.remove("dict"));
        ret.setMsg(model.get("message_info") == null ? "" : model.remove("message_info").toString());
        return ret;
    }

    /**
     * 包含站点下面的模块以及模块下面的数据统计
     * @param query
     * @return
     */
    @PostMapping({"list/allInfo"})
    @UnAuth
    public Rest<Object> list(@RequestBody SiteQuery query) {
        Rest<Object> ret = new Rest();
        Map<String, Object> model = new HashMap();
        Context context = this.getContext();
        String busiDesc = "查询" + this.getModuleDesc();

        int code=1;
        try {
            List<SiteEntity> result = this.getService().getListAllInfoByQuery(query, context);
            model.put("data", result);
            model.put("message_info", busiDesc + "成功");
            this.recordSysLog(this.request, busiDesc + " 【成功】");
        } catch (Exception var9) {
            code = -1;
            this.doException(this.request, busiDesc, model, var9);
        }
        this.init(model, context);
        ret.setCode(code);
        ret.setData(model);
        ret.setDict(model.remove("dict"));
        ret.setMsg(model.get("message_info") == null ? "" : model.remove("message_info").toString());
        return ret;
    }
}