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

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
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.service.ICacheService;
import com.mortals.framework.util.ThreadPool;
import com.mortals.framework.web.BaseCRUDJsonBodyMappingController;
import com.mortals.xhx.base.system.param.service.ParamService;
import com.mortals.xhx.common.code.AccessTypeEnum;
import com.mortals.xhx.common.code.GroupListEnum;
import com.mortals.xhx.common.key.RedisKey;
import com.mortals.xhx.common.pdu.RespData;
import com.mortals.xhx.common.pdu.site.SitePdu;
import com.mortals.xhx.feign.site.ISiteFeign;
import com.mortals.xhx.module.access.model.AccessEntity;
import com.mortals.xhx.module.access.model.AccessQuery;
import com.mortals.xhx.module.access.model.AccessStatLogEntity;
import com.mortals.xhx.module.access.service.AccessService;
import com.mortals.xhx.module.access.service.AccessStatLogService;
import com.mortals.xhx.module.ph.model.PhQueueQuery;
import com.mortals.xhx.module.ph.model.PhQueueStatEntity;
import com.mortals.xhx.module.ph.model.PhQueueStatQuery;
import com.mortals.xhx.module.ph.service.PhQueueStatService;
import com.mortals.xhx.module.pj.model.PjEvaluateStatEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StopWatch;
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;

/**
 * 排队叫号汇总统计
 *
 * @author zxfei
 * @date 2024-06-24
 */
@RestController
@RequestMapping("ph/queue/stat")
@Slf4j
public class PhQueueStatController extends BaseCRUDJsonBodyMappingController<PhQueueStatService, PhQueueStatEntity, Long> {

    @Autowired
    private ISiteFeign siteFeign;
    @Autowired
    private PhQueueStatService phQueueStatService;
    @Autowired
    private ICacheService cacheService;
    @Autowired
    private AccessService accessService;
    @Autowired
    private AccessStatLogService accessStatLogService;

    public PhQueueStatController() {
        super.setModuleDesc("排队叫号汇总统计");
    }

    @Override
    protected void init(Map<String, Object> model, Context context) {
        //通过站点 查询存在的部门 大厅等
        Object siteId = model.get("siteId");
        if (!ObjectUtils.isEmpty(siteId)) {
            Map<String, String> sectionNameMap = cacheService.hgetAll(RedisKey.KEY_SITE_QUEUE_SECTIONNAME_CHCHE + siteId);
            Map<String, String> hallNameMap = cacheService.hgetAll(RedisKey.KEY_SITE_QUEUE_HALLNAME_CHCHE + siteId);
            Map<String, String> windowFromnumMap = cacheService.hgetAll(RedisKey.KEY_SITE_QUEUE_WINDOW_CHCHE + siteId);
            Map<String, String> bussinessMap = cacheService.hgetAll(RedisKey.KEY_SITE_QUEUE_BUSNIESS_CHCHE + siteId);

            List<Map<String, String>> m1 = sectionNameMap.entrySet().stream()
                    .sorted((e1, e2) -> Integer.compare(Integer.parseInt(e2.getValue()), Integer.parseInt(e1.getValue())))
                    .map(item -> new HashMap<String, String>() {{
                        put(item.getKey(), item.getValue());
                    }}).collect(Collectors.toList());
            List<Map<String, String>> m2 = hallNameMap.entrySet().stream()
                    .sorted((e1, e2) -> Integer.compare(Integer.parseInt(e2.getValue()), Integer.parseInt(e1.getValue())))
                    .map(item -> new HashMap<String, String>() {{
                        put(item.getKey(), item.getValue());
                    }}).collect(Collectors.toList());
            List<Map<String, String>> m3 = windowFromnumMap.entrySet().stream()
                    .sorted((e1, e2) -> Integer.compare(Integer.parseInt(e2.getValue()), Integer.parseInt(e1.getValue())))
                    .map(item -> new HashMap<String, String>() {{
                        put(item.getKey(), item.getValue());
                    }}).collect(Collectors.toList());
            List<Map<String, String>> m4 = bussinessMap.entrySet().stream()
                    .sorted((e1, e2) -> Integer.compare(Integer.parseInt(e2.getValue()), Integer.parseInt(e1.getValue())))
                    .map(item -> new HashMap<String, String>() {{
                        put(item.getKey(), item.getValue());
                    }}).collect(Collectors.toList());

            this.addDict(model, "sectionNameList", m1);
            this.addDict(model, "hallNameList", m2);
            this.addDict(model, "windowFromnumList", m3);
            this.addDict(model, "businessList", m4);
            this.addDict(model, "groupList", GroupListEnum.getEnumMap());
        }

        super.init(model, context);
    }


    @Override
    protected void doListBefore(PhQueueStatEntity query, Map<String, Object> model, Context context) throws AppException {
        if (ObjectUtils.isEmpty(query.getHallName()) && ObjectUtils.isEmpty(query.getHallNameList()) && ObjectUtils.isEmpty(query.getHallNameNotList()))
            query.setHallNameList(Arrays.asList(""));
        if (ObjectUtils.isEmpty(query.getSectionName()) && ObjectUtils.isEmpty(query.getSectionNameList()) && ObjectUtils.isEmpty(query.getSectionNameNotList()))
            query.setSectionNameList(Arrays.asList(""));
        if (ObjectUtils.isEmpty(query.getBusiness()) && ObjectUtils.isEmpty(query.getBusinessList()) && ObjectUtils.isEmpty(query.getBusinessNotList()))
            query.setBusinessList(Arrays.asList(""));
        if (ObjectUtils.isEmpty(query.getWindowFromnum()) && ObjectUtils.isEmpty(query.getWindowFromnumList()) && ObjectUtils.isEmpty(query.getWindowFromnumNotList()))
            query.setWindowFromnumList(Arrays.asList(""));
        addGroup(query);
        model.put("siteId", query.getSiteId());
    }

    private static void addGroup(PhQueueStatEntity query) {
        if (!ObjectUtils.isEmpty(query.getSiteId())) {
            List<String> groupList = query.getGroupList();
            if (!groupList.contains("siteId")) {
                groupList.add("siteId");
            }
        }

        if (!ObjectUtils.isEmpty(query.getSectionName())
                || !ObjectUtils.isEmpty(query.getSectionNameList())
                || !ObjectUtils.isEmpty(query.getSectionNameNotList())) {
            List<String> groupList = query.getGroupList();
            if (!groupList.contains("sectionName")) {
                groupList.add("sectionName");
            }
        }
        if (!ObjectUtils.isEmpty(query.getHallName())
                || !ObjectUtils.isEmpty(query.getHallNameList())
                || !ObjectUtils.isEmpty(query.getHallNameNotList())) {
            List<String> groupList = query.getGroupList();
            if (!groupList.contains("hallName")) {
                groupList.add("hallName");
            }
        }

        if (!ObjectUtils.isEmpty(query.getWindowFromnum())
                || !ObjectUtils.isEmpty(query.getWindowFromnumList())
                || !ObjectUtils.isEmpty(query.getWindowFromnumNotList())) {
            List<String> groupList = query.getGroupList();
            if (!groupList.contains("windowFromnum")) {
                groupList.add("windowFromnum");
            }
        }

        if (!ObjectUtils.isEmpty(query.getBusiness())
                || !ObjectUtils.isEmpty(query.getBusinessList())
                || !ObjectUtils.isEmpty(query.getHallNameNotList())) {
            List<String> groupList = query.getGroupList();
            if (!groupList.contains("business")) {
                groupList.add("business");
            }
        }

    }

    @PostMapping(value = "/stat")
    @UnAuth
    public Rest<String> addAttendanceRecordCustom(@RequestBody PhQueueQuery phQueueQuery) {
        Rest<String> ret = new Rest();
        Map<String, Object> model = new HashMap();
        Context context = this.getContext();
        String busiDesc = "查询" + this.getModuleDesc();
        int code = 1;
        try {
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    //天数区间分段计算
                    DateTime attendStart = DateUtil.parseDate(phQueueQuery.getTaketimeStart());
                    DateTime attendEnd = DateUtil.parseDate(phQueueQuery.getTaketimeEnd());
                    Long compare = DateUtil.between(attendEnd, attendStart, DateUnit.DAY);
                    StopWatch stopWatch = new StopWatch();
                    log.info("计算天数区间：{}", compare);



                    AccessQuery accessQuery = new AccessQuery();
                    accessQuery.setTagNotList(Arrays.asList(""));
                    List<AccessEntity> accessEntities = accessService.find(accessQuery);

                    for (AccessEntity accessEntity : accessEntities) {
                        SitePdu site = new SitePdu();
                        site.setId(accessEntity.getSiteId());
                        site.setSiteName(accessEntity.getSiteName());
                        site.setSiteCode(accessEntity.getSiteCode());
                        site.setAreaCode(accessEntity.getAreaCode());
                        updateSitePhStat(attendStart, compare, stopWatch, site, context);
                    }

/*                    SitePdu sitePdu = new SitePdu();
                    sitePdu.setSize(-1);
                    Rest<RespData<List<SitePdu>>> resp = siteFeign.list(sitePdu);
                    log.info("site resp：{}", JSON.toJSONString(resp));
                    if (resp.getCode() == 1) {
                        List<SitePdu> sitePduList = resp.getData().getData();
                        for (SitePdu site : sitePduList) {
                            updateSitePhStat(attendStart, compare, stopWatch, site, context);
                        }
                        //log.info("日期：{} 完成,耗时：{}ms", curDate.toDateStr(), stopWatch.getLastTaskTimeMillis());
                    }*/
                }
            };

            ThreadPool.getInstance().execute(runnable);

            model.put("message_info", busiDesc + "成功");
            this.recordSysLog(this.request, busiDesc + " 【成功】");
        } catch (Exception e) {
            code = -1;
            this.doException(this.request, busiDesc, model, e);
            model.put("message_info", e.getMessage());
        }

        this.init(model, context);
        ret.setCode(code);
        ret.setMsg(model.get("message_info") == null ? "" : model.remove("message_info").toString());
        return ret;

    }

    private void updateSitePhStat(DateTime attendStart, Long compare, StopWatch stopWatch, SitePdu site, Context context) {
        log.info("统计站点：{}", site.getSiteName());
        stopWatch.start("站点排号统计开始");
        AccessStatLogEntity statLogEntity = new AccessStatLogEntity();
        statLogEntity.initAttrValue();
        statLogEntity.setStatStartTime(new Date());
        statLogEntity.setType(AccessTypeEnum.排队机.getValue());
        statLogEntity.setCreateUserId(1L);
        statLogEntity.setCreateTime(new Date());
        statLogEntity.setSiteId(site.getId());
        statLogEntity.setSiteCode(site.getSiteCode());
        statLogEntity.setSiteName(site.getSiteName());

        AccessQuery accessQuery = new AccessQuery();
        accessQuery.setSiteId(site.getId() == null ? 0L : site.getId());
        AccessEntity accessEntity = accessService.selectOne(accessQuery);
        if (!ObjectUtils.isEmpty(accessEntity)) {
            statLogEntity.setAccessId(accessEntity.getId());
        }

        for (int i = 0; i <= compare.intValue(); i++) {
            DateTime curDate = DateUtil.offsetDay(attendStart, i);
            log.info("记录日期：{}", curDate.toDateStr());

            PhQueueStatEntity sitestatEntity = new PhQueueStatEntity();
            sitestatEntity.initAttrValue();
            sitestatEntity.setSiteId(site.getId());
            sitestatEntity.setSiteName(site.getSiteName());
            sitestatEntity.setSiteCode(site.getSiteCode());

            sitestatEntity.setYear(curDate.year());
            sitestatEntity.setMonth(curDate.month() + 1);
            sitestatEntity.setDay(curDate.dayOfMonth());
            //设置年月日
            phQueueStatService.updateSitePhStat(sitestatEntity, context);
        }
        stopWatch.stop();
        statLogEntity.setStatEndTime(new Date());
        statLogEntity.setDuration(stopWatch.getLastTaskTimeMillis());
        accessStatLogService.save(statLogEntity, context);
    }


    public static void main(String[] args) throws InterruptedException {
        StopWatch stopWatch = new StopWatch("stopwatch");
        stopWatch.start();
        Thread.sleep(1200);
        stopWatch.stop();

        System.out.println(stopWatch.getLastTaskTimeMillis());

        stopWatch.start();
        Thread.sleep(1200);
        stopWatch.stop();

        System.out.println(stopWatch.getLastTaskTimeMillis());

    }

}