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.model.OrderCol;
import com.mortals.framework.model.PageInfo;
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.baseset.model.BasesetEntity;
import com.mortals.xhx.module.baseset.model.BasesetQuery;
import com.mortals.xhx.module.baseset.service.BasesetService;
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;
    @Autowired
    private BasesetService basesetService;

    @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({"depts"})
    @UnAuth
    public Rest<Object> depts(@RequestBody HomeQueryPdu queryPdu) {
        Rest<Object> ret = new Rest();
        Map<String, Object> model = new HashMap();
        String busiDesc = "查询站点部门";
        int code = VALUE_RESULT_SUCCESS;
        model.put("deptMap", new HashMap<>());
        try {
            if (queryPdu.getSiteId() != null) {
                Map<String, String> deptMap = matterService.find(new MatterQuery().siteId(queryPdu.getSiteId())).stream().collect(Collectors.toMap(x -> x.getDeptCode(), y -> y.getDeptName(), (o, n) -> n));
                model.put("deptMap", deptMap);
            }
            model.put("message_info", busiDesc + "成功");
            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.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 {
            HotwordQuery hotwordQuery = new HotwordQuery();
            hotwordQuery.siteId(homeQueryPdu.getSiteId());
            List<OrderCol> orderColList = new ArrayList<>();
            orderColList.add(new OrderCol("wordsSource", OrderCol.ASCENDING));
            orderColList.add(new OrderCol("searchCount", OrderCol.DESCENDING));
            hotwordQuery.setOrderColList(orderColList);

            PageInfo pageInfo = new PageInfo();
            int nums = GlobalSysInfo.getParamIntValue(Constant.PARAMS_HOTWORDS_DEFAULT_NUM, 10);
            pageInfo.setPrePageResult(nums);

            List<HotwordEntity> hotwordEntities = hotwordService.find(hotwordQuery, pageInfo, null).getList();
/*            List<String> hotwordEntities = hotwordService.find(hotwordQuery, new PageInfo(), null).getList().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", 0);   //在线提交数量
            model.put("dayThrift", 66);      //今日节约
            model.put("totalThrift", 996);    //累计节约
            Rest<com.mortals.xhx.common.pdu.site.SitePdu> info = siteFeign.info(homeQueryPdu.getSiteId());
            model.put("title", info == null ? "" : info.getData().getSiteName()); //标题

            //HotwordEntity hotwordEntity = hotwordService.selectOne(hotwordQuery.siteId(homeQueryPdu.getSiteId()));

            BasesetEntity basesetEntity = basesetService.selectOne(new BasesetQuery().siteId(homeQueryPdu.getSiteId()));

            model.put("blankCount", basesetEntity == null ? 20 : basesetEntity.getPrintDisplay()); //空白样表数量
            model.put("newsSource", basesetEntity == null ? 1 : basesetEntity.getNewsSource()); //新闻来源
            model.put("message_info", busiDesc + "成功");
            // this.addDict(model, "newsSource", NewsSourceEnum.getEnumMap());
            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;
    }
}
