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.common.code.EnabledEnum;
import com.mortals.xhx.common.code.YesNoEnum;
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", YesNoEnum.getEnumMap());
        this.addDict(model, "workday2", YesNoEnum.getEnumMap());
        this.addDict(model, "workday3", YesNoEnum.getEnumMap());
        this.addDict(model, "workday4", YesNoEnum.getEnumMap());
        this.addDict(model, "workday5",YesNoEnum.getEnumMap());
        this.addDict(model, "workday6", YesNoEnum.getEnumMap());
        this.addDict(model, "workday7",YesNoEnum.getEnumMap());
        this.addDict(model, "isSite", YesNoEnum.getEnumMap());
        this.addDict(model, "status", EnabledEnum.getEnumMap());
       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);
    }

}