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

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.annotation.UnAuth;
import com.mortals.framework.ap.GlobalSysInfo;
import com.mortals.framework.common.Rest;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.service.IUser;
import com.mortals.framework.util.DataUtil;
import com.mortals.framework.util.StringUtils;
import com.mortals.framework.web.BaseJsonBodyController;
import com.mortals.xhx.base.system.param.service.ParamService;
import com.mortals.xhx.common.code.YesNoEnum;
import com.mortals.xhx.common.key.Constant;
import com.mortals.xhx.feign.base.IApiBaseManagerFeign;
import com.mortals.xhx.feign.base.pdu.DeptPdu;
import com.mortals.xhx.feign.base.pdu.SitePdu;
import com.mortals.xhx.feign.rsp.ApiResp;
import com.mortals.xhx.feign.site.ISiteFeign;
import com.mortals.xhx.module.home.pdu.HomeQueryPdu;
import com.mortals.xhx.module.hotword.model.HotwordEntity;
import com.mortals.xhx.module.hotword.model.HotwordQuery;
import com.mortals.xhx.module.hotword.service.HotwordService;
import com.mortals.xhx.module.matter.model.MatterDatumEntity;
import com.mortals.xhx.module.matter.model.MatterDatumQuery;
import com.mortals.xhx.module.matter.model.MatterEntity;
import com.mortals.xhx.module.matter.model.MatterQuery;
import com.mortals.xhx.module.matter.service.MatterDatumService;
import com.mortals.xhx.module.matter.service.MatterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("home")
public class HomeController extends BaseJsonBodyController {

    @Autowired
    private IApiBaseManagerFeign iApiBaseManagerFeign;
    @Autowired
    private MatterDatumService matterDatumService;
    @Autowired
    private MatterService matterService;
    @Autowired
    private HotwordService hotwordService;
    @Autowired
    private ParamService paramService;
    @Autowired
    private ISiteFeign siteFeign;

    @PostMapping({"site/list"})
    public Rest<Object> list() {
        IUser user = this.getCurUser();
        if (user == null) {
            throw new AppException("用户未登录");
        }
        Rest<Object> ret = new Rest();
        Map<String, Object> model = new HashMap();
        String busiDesc = "查询用户站点列表";

        int code = 1;
        try {

            if (StringUtils.isNotEmpty(user.getSiteIds())) {
                SitePdu sitePdu = new SitePdu();
                List<String> siteIds = Arrays.asList(user.getSiteIds().split(","));
                List<Long> idList = new ArrayList<>();
                siteIds.forEach(s -> {
                    idList.add(DataUtil.converStr2Long(s, 0));
                });
                sitePdu.setIdList(idList);
                String resp = iApiBaseManagerFeign.getSitesByQuery(sitePdu);
                ApiResp<JSONObject> apiResp = JSON.parseObject(resp, ApiResp.class);
                if (apiResp.getCode() != YesNoEnum.YES.getValue()) {
                    throw new AppException("获取用户站点列表树数据失败：" + apiResp.getMsg());
                }
                if (apiResp.getData().get("data") != null) {
                    model.put("data", apiResp.getData().get("data"));
                } else {
                    model.put("data", Collections.emptyList());
                }
            } else {
                model.put("data", Collections.emptyList());
            }
            model.put("message_info", busiDesc + "成功");
            this.recordSysLog(this.request, busiDesc + " 【成功】");
        } catch (Exception var9) {
            code = -1;
            this.doException(this.request, busiDesc, model, var9);
        }

        ret.setCode(code);
        ret.setData(model);
        ret.setDict(model.get("dict"));
        ret.setMsg(model.get("message_info") == null ? "" : model.remove("message_info").toString());
        return ret;
    }

    @PostMapping({"dept/list"})
    @UnAuth
    public Rest<Object> deptList(@RequestBody HomeQueryPdu queryPdu) {
//        IUser user = this.getCurUser();
//        if(user==null){
//            throw new AppException("用户未登录");
//        }
        Rest<Object> ret = new Rest();
        Map<String, Object> model = new HashMap();
        String busiDesc = "查询站点部门列表";
        int code = 1;
        try {

            if (queryPdu.getSiteId() != null) {
                DeptPdu deptPdu = new DeptPdu();
                deptPdu.setSiteId(queryPdu.getSiteId());
                deptPdu.setSize(-1);
                String resp = iApiBaseManagerFeign.getDeptByQuery(deptPdu);
                ApiResp<JSONObject> apiResp = JSON.parseObject(resp, ApiResp.class);
                if (apiResp.getCode() != YesNoEnum.YES.getValue()) {
                    throw new AppException("获取用户站点部门列表失败：" + apiResp.getMsg());
                }
                if (apiResp.getData().get("data") != null) {
                    model.put("data", apiResp.getData().get("data"));
                } else {
                    model.put("data", Collections.emptyList());
                }
            } else {
                model.put("data", Collections.emptyList());
            }
            model.put("message_info", busiDesc + "成功");
            this.recordSysLog(this.request, busiDesc + " 【成功】");
        } catch (Exception var9) {
            code = -1;
            this.doException(this.request, busiDesc, model, var9);
        }

        ret.setCode(code);
        ret.setData(model);
        ret.setDict(model.get("dict"));
        ret.setMsg(model.get("message_info") == null ? "" : model.remove("message_info").toString());
        return ret;
    }

    @PostMapping({"info"})
    @UnAuth
    public Rest<Object> homePageInfo(@RequestBody HomeQueryPdu homeQueryPdu) {
        Rest<Object> ret = new Rest();
        Map<String, Object> model = new HashMap();
        String busiDesc = "获取首页数据";
        int code = VALUE_RESULT_SUCCESS;
        try {
            List<String> hotwordEntities = hotwordService.find(new HotwordQuery().siteId(homeQueryPdu.getSiteId())).stream()
                    .map(HotwordEntity::getHotwords)
                    .flatMap(item-> StrUtil.split(item,",".charAt(0)).stream())
                    .collect(Collectors.toList());
            model.put("hotWords", hotwordEntities);
            MatterQuery matterQuery = new MatterQuery();
            matterQuery.setSiteId(homeQueryPdu.getSiteId());
            int matterCont = matterService.count(matterQuery, this.getContext());
            matterQuery.setIsRecommend(YesNoEnum.YES.getValue());
            List<MatterEntity> matterList = matterService.find(matterQuery, this.getContext());
            model.put("matterList", matterList);   //热门事项
            model.put("matterCont", matterCont);   //入驻事项数量
            MatterDatumQuery matterDatumQuery = new MatterDatumQuery();
            matterDatumQuery.setSiteId(homeQueryPdu.getSiteId());
            int datumCont = matterDatumService.count(matterDatumQuery, this.getContext());
            matterDatumQuery.setIsRecommend(YesNoEnum.YES.getValue());
            List<MatterDatumEntity> datumList = matterDatumService.find(matterDatumQuery, this.getContext());
            model.put("datumList", datumList);    //热门表单
            model.put("datumCont", datumCont);    //入驻表单数量

            model.put("localPrint", 20);     //本地打印数量
            model.put("onlineSubmit", 20);   //在线提交数量
            model.put("dayThrift", 66);      //今日节约
            model.put("totalThrift", 996);    //累计节约
            model.put("message_info", busiDesc + "成功");
            Rest<com.mortals.xhx.common.pdu.site.SitePdu> info = siteFeign.info(homeQueryPdu.getSiteId());
            model.put("title", info.getData().getSiteName()); //标题
            HotwordEntity hotwordEntity = hotwordService.selectOne(new HotwordQuery().siteId(homeQueryPdu.getSiteId()));
            model.put("blankCount", hotwordEntity==null?20:hotwordEntity.getPrintDisplay()); //空白样表数量

            this.recordSysLog(this.request, busiDesc + " 【成功】");
        } catch (Exception var9) {
            code = VALUE_RESULT_FAILURE;
            this.doException(this.request, busiDesc, model, var9);
        }

        ret.setCode(code);
        ret.setData(model);
        ret.setDict(model.get("dict"));
        ret.setMsg(model.get("message_info") == null ? "" : model.remove("message_info").toString());
        return ret;
    }
}
