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

import cn.hutool.core.net.url.UrlBuilder;
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.ICacheService;
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.common.code.YesNoEnum;
import com.mortals.xhx.common.key.Constant;
import com.mortals.xhx.common.key.RedisKey;
import com.mortals.xhx.common.pdu.RespData;
import com.mortals.xhx.common.pdu.app.AppPdu;
import com.mortals.xhx.common.pdu.dept.DeptPdu;
import com.mortals.xhx.feign.app.IAppFeign;
import com.mortals.xhx.feign.base.IApiBaseManagerFeign;
import com.mortals.xhx.feign.base.pdu.SitePdu;
import com.mortals.xhx.feign.dept.IDeptFeign;
import com.mortals.xhx.feign.rsp.ApiResp;
import com.mortals.xhx.feign.site.ISiteFeign;
import com.mortals.xhx.module.app.model.AppConfigEntity;
import com.mortals.xhx.module.app.model.AppConfigQuery;
import com.mortals.xhx.module.app.service.AppConfigService;
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.device.model.DeviceMatterDatumEntity;
import com.mortals.xhx.module.device.model.DeviceMatterDatumQuery;
import com.mortals.xhx.module.device.service.DeviceMatterDatumService;
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 lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

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

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

    @Autowired
    private IApiBaseManagerFeign iApiBaseManagerFeign;
    @Autowired
    private MatterDatumService matterDatumService;
    @Autowired
    private MatterService matterService;
    @Autowired
    private HotwordService hotwordService;
    @Autowired
    private DeviceMatterDatumService deviceMatterDatumService;
    @Autowired
    private ISiteFeign siteFeign;
    @Autowired
    private BasesetService basesetService;
    @Autowired
    private IDeptFeign deptFeign;
    @Autowired
    private ICacheService cacheService;
    @Autowired
    private IAppFeign appFeign;
    @Autowired
    private AppConfigService appConfigService;


    @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);

                if(!ObjectUtils.isEmpty(queryPdu.getDeviceCode())){
                    List<Long> deptIdList = deviceMatterDatumService.find(new DeviceMatterDatumQuery().deviceCode(queryPdu.getDeviceCode())).stream().map(item -> item.getDeptId()).collect(Collectors.toList());
                    deptPdu.setIdList(deptIdList);
                }
                Rest<RespData<List<DeptPdu>>> apiResp = deptFeign.list(deptPdu);
               // ApiResp<JSONObject> apiResp = JSON.parseObject(resp, ApiResp.class);
                if (apiResp.getCode() != YesNoEnum.YES.getValue()) {
                    throw new AppException("获取用户站点部门列表失败：" + apiResp.getMsg());
                }
                if (apiResp.getData().getData()!= null) {
                    model.put("data", apiResp.getData().getData());
                } 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) {
                if (!ObjectUtils.isEmpty(queryPdu.getDeviceCode())) {
                    Map<String, String> deptMap = deviceMatterDatumService.find(new DeviceMatterDatumQuery().siteId(queryPdu.getSiteId()).deviceCode(queryPdu.getDeviceCode())).stream().collect(Collectors.toMap(x -> x.getDeptCode(), y -> y.getDeptName(), (o, n) -> n));
                    ;
                    model.put("deptMap", deptMap);
                    // deptPdu.setIdList(deptIdList);
                } else {
                    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", cacheService.getLong(RedisKey.KEY_DAY_VIEW)==null?0:cacheService.getLong(RedisKey.KEY_DAY_VIEW));     //本地打印数量
            model.put("onlineSubmit", 0);   //在线提交数量

            //Long todayThrift = cacheService.incrForToday(RedisKey.KEY_DAYTHRIFT);
            model.put("dayThrift", cacheService.getLong(RedisKey.KEY_DAY_VIEW)==null?0:cacheService.getLong(RedisKey.KEY_DAY_VIEW)*2);      //今日节约
            model.put("totalThrift", cacheService.getLong(RedisKey.KEY_DAY_VIEW_TOTAL)==null?0:cacheService.getLong(RedisKey.KEY_DAY_VIEW_TOTAL)*2);    //累计节约
            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()); //新闻来源


         //添加设备热门事项与热门材料
            if(!ObjectUtils.isEmpty(homeQueryPdu.getDeviceCode())){
                DeviceMatterDatumQuery deviceMatterDatumQuery = new DeviceMatterDatumQuery();
                deviceMatterDatumQuery.setDeviceCode(homeQueryPdu.getDeviceCode());
                deviceMatterDatumQuery.setIsRecommend(YesNoEnum.YES.getValue());
                deviceMatterDatumQuery.setOrderColList(Arrays.asList(new OrderCol("isRecommend",OrderCol.DESCENDING)));
                List<DeviceMatterDatumEntity> matterDatumEntityList = deviceMatterDatumService.find(deviceMatterDatumQuery, null);
                //热门事项取5个
                List<DeviceMatterDatumEntity> matterEntities = matterDatumEntityList.stream().distinct().limit(5).collect(Collectors.toList());
                model.put("hotMatterList", matterEntities); //热门事项
                List<MatterDatumEntity> matterDatumEntities = matterDatumEntityList.stream().flatMap(item -> {
                    List<MatterDatumEntity> datumEntities = matterDatumService.find(new MatterDatumQuery().matterId(item.getMatterId()));
                    return datumEntities.stream();

                }).filter(f->!ObjectUtils.isEmpty(f)).filter(f -> f.getIsRecommend()!=null&&f.getIsRecommend() == YesNoEnum.YES.getValue()).limit(5).collect(Collectors.toList());
                //热门材料取5个
               // List<DeviceMatterDatumEntity> matterDatumEntities = matterDatumEntityList.stream().limit(5).collect(Collectors.toList());
                model.put("hotDatumList", matterDatumEntities); //热门热门材料
            }

            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;
    }

    /**
     * 自助服务应用
     *
     * @return
     */
    @GetMapping({"app/list"})
    @UnAuth
    public String appList(Long siteId) {
        String serverName = request.getHeader("server-name");
        Integer serverPort = DataUtil.converStr2Int(request.getHeader("server-port"), 0);

        log.info("【应用请求】【请求体】-->serverName{} ,port:{}", serverName, serverPort);

        Rest<List<AppPdu>> ret = new Rest();
        List<AppPdu> collect = new ArrayList<>();
        int code = VALUE_RESULT_SUCCESS;

        AppConfigQuery query = new AppConfigQuery();
        query.setSiteId(siteId);
        query.setOrderColList(Arrays.asList(new OrderCol("order")));

        List<AppConfigEntity> appConfigEntities = appConfigService.find(query);
        if (!ObjectUtils.isEmpty(appConfigEntities)) {
            List<Long> AppIdList = appConfigEntities.stream().map(item -> item.getAppId()).collect(Collectors.toList());
            AppPdu appPdu = new AppPdu();
            appPdu.setIdList(AppIdList);
            appPdu.setSize(-1);
            Rest<RespData<List<AppPdu>>> appRest = appFeign.list(appPdu);
            String domainUrl = UrlBuilder.ofHttp(serverName).setPort(serverPort > 0 ? serverPort : 11078).build();

            log.info("appRest:" + JSON.toJSONString(appRest));
            log.info("domainUrl:" + domainUrl);
            if (appRest.getCode() == YesNoEnum.YES.getValue()) {
                collect = appRest.getData().getData().stream()
                        .peek(item -> {
                            item.setCustUrl(UrlBuilder.ofHttp(domainUrl).addPath(item.getCustUrl()).build());
                            log.info(item.getCustUrl());
                            log.info(item.getAppIconPath());
                        }).collect(Collectors.toList());
            }
        } else {
            String appWhiteStr = GlobalSysInfo.getParamValue(Constant.PARAMS_WHITE_APP_LIST, "中心简介,办事指南,意见建议,通知公告");
            Set<String> appWhiteSet = StrUtil.split(appWhiteStr, ",").stream().collect(Collectors.toSet());
            try {
                AppPdu appPdu = new AppPdu();
                appPdu.setSiteId(siteId);
                appPdu.setSize(-1);
                appPdu.setType(1);
                Rest<RespData<List<AppPdu>>> appRest = appFeign.list(appPdu);
                String domainUrl = UrlBuilder.ofHttp(serverName).setPort(serverPort > 0 ? serverPort : 11078).build();
                log.info("appRest:" + JSON.toJSONString(appRest));
                log.info("domainUrl:" + domainUrl);
                if (appRest.getCode() == YesNoEnum.YES.getValue()) {
                    collect = appRest.getData().getData().stream().filter(f -> appWhiteSet.contains(f.getAppName()))
                            .peek(item -> {
                                item.setCustUrl(UrlBuilder.ofHttp(domainUrl).addPath(item.getCustUrl()).build());
                                log.info(item.getCustUrl());
                                log.info(item.getAppIconPath());
                            }).collect(Collectors.toList());
                }
            } catch (Exception e) {
                code = VALUE_RESULT_FAILURE;
            }
        }
        ret.setCode(code);
        ret.setData(collect);
        log.info("【应用请求】【响应体】-->{}", JSONObject.toJSONString(ret));
        return JSONObject.toJSONString(ret);
    }

}
