package com.yunfeiyun.agmp.fms.controller;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.yunfeiyun.agmp.common.core.controller.BaseController;
import com.yunfeiyun.agmp.common.core.domain.AjaxResult;
import com.yunfeiyun.agmp.common.core.page.TableDataInfo;
import com.yunfeiyun.agmp.common.enums.CommonEnums;
import com.yunfeiyun.agmp.common.enums.SpmOrderStatus;
import com.yunfeiyun.agmp.common.enums.SysWarnEnum;
import com.yunfeiyun.agmp.common.utils.ConfigUtils;
import com.yunfeiyun.agmp.common.utils.StringUtils;
import com.yunfeiyun.agmp.fms.domain.SpmOrder;
import com.yunfeiyun.agmp.fms.domain.reqvo.SelectCountOfScreenReqVo;
import com.yunfeiyun.agmp.fms.domain.reqvo.SysWarnReqVo;
import com.yunfeiyun.agmp.fms.domain.resvo.SpmOrderStatResVo;
import com.yunfeiyun.agmp.fms.domain.resvo.SysWarnResVo;
import com.yunfeiyun.agmp.fms.domain.resvo.SpmOrderOfScreenResVo;
import com.yunfeiyun.agmp.fms.domain.resvo.TssScanrcdStatResVo;
import com.yunfeiyun.agmp.fms.service.ISpmOrderService;
import com.yunfeiyun.agmp.fms.service.ISysWarnService;
import com.yunfeiyun.agmp.fms.service.ITssScanrcdService;
import com.yunfeiyun.agmp.fms.service.ITssTracecodeapplyService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 首页Controller
 *
 * @author 刘耀文
 */
@RestController
@RequestMapping("/fms/screen")
public class FmsScreenController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(FmsScreenController.class);
    @Resource
    private ITssTracecodeapplyService tssTracecodeapplyService;
    @Resource
    private ITssScanrcdService tssScanrcdService;
    @Resource
    private ISysWarnService sysWarnService;
    @Resource
    private ISpmOrderService spmOrderService;


    /**
     * 溯源大屏营收情况统计
     */
    @PreAuthorize("@ss.hasPermi('fms:screen:trace:code:stat')")
    @GetMapping("/trace/code/stat")
    public AjaxResult traceCodeStat() {
        SelectCountOfScreenReqVo reqVo = new SelectCountOfScreenReqVo();

        reqVo.setStartTime(LocalDateTime.of(LocalDate.now(), LocalTime.MIN).format(DateTimeFormatter.ofPattern(CommonEnums.PATTERN_DATETIME.getCode())));
        Map<String, Object> map1 = getCount(reqVo);

        reqVo.setStartTime(LocalDateTime.of(LocalDate.now(), LocalTime.MIN).with(DayOfWeek.MONDAY).format(DateTimeFormatter.ofPattern(CommonEnums.PATTERN_DATETIME.getCode())));
        Map<String, Object> map2 = getCount(reqVo);

        reqVo.setStartTime(LocalDateTime.now().with(TemporalAdjusters.firstDayOfMonth()).with(LocalTime.MIN).format(DateTimeFormatter.ofPattern(CommonEnums.PATTERN_DATETIME.getCode())));
        Map<String, Object> map3 = getCount(reqVo);

        reqVo.setStartTime(LocalDateTime.now().with(TemporalAdjusters.firstDayOfYear()).with(LocalTime.MIN).format(DateTimeFormatter.ofPattern(CommonEnums.PATTERN_DATETIME.getCode())));
        Map<String, Object> map4 = getCount(reqVo);

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("countOfDay", map1);
        resultMap.put("countOfWeek", map2);
        resultMap.put("countOfMonth", map3);
        resultMap.put("countOfYear", map4);

        return AjaxResult.success(resultMap);
    }

    /**
     * 溯源大屏预警信息列表查询
     */
    @PreAuthorize("@ss.hasPermi('fms:screen:sys:warn:list')")
    @GetMapping("/sys/warn/list")
    public AjaxResult sysWarnList(SysWarnReqVo reqVo) {
        List<SysWarnResVo> sysWarnResVos = sysWarnService.selectSysWarnListOfScreen(reqVo);
        return AjaxResult.success(sysWarnResVos);
    }

    /**
     * 溯源大屏最新物流列表查询
     */
    @PreAuthorize("@ss.hasPermi('fms:screen:spm:order:list')")
    @GetMapping("/spm/order/list")
    public AjaxResult spmOrderList(SpmOrder spmOrder) {
        List<SpmOrderOfScreenResVo> spmOrderOfScreenResVos = spmOrderService.selectSpmOrderOfScreenList(spmOrder);
        return AjaxResult.success(spmOrderOfScreenResVos);
    }

    /**
     * 溯源大屏农产品销售情况数据查询
     */
    @PreAuthorize("@ss.hasPermi('fms:screen:spm:order:stat')")
    @GetMapping("/spm/order/stat")
    public AjaxResult spmOrderStat(SelectCountOfScreenReqVo reqVo) {
        String nowDate = LocalDateTime.of(LocalDate.now(), LocalTime.MIN).format(DateTimeFormatter.ofPattern(CommonEnums.PATTERN_DATE.getCode()));
        if (StringUtils.isEmpty(reqVo.getStartTime())) {
            reqVo.setStartTime(nowDate);
        }

        Map<String, Object> stringObjectMap1 = spmOrderService.selectSpmOrderStat(reqVo);
        reqVo.setStartTime(null);
        reqVo.setStartTimeSend(nowDate);
        reqVo.setOrderStatus(SpmOrderStatus.SENDING.getCode());
        Map<String, Object> stringObjectMap2 = spmOrderService.selectSpmOrderStat(reqVo);
        reqVo.setStartTimeSend(null);
        reqVo.setStartTimeArrival(nowDate);
        reqVo.setOrderStatus(SpmOrderStatus.received.getCode());
        Map<String, Object> stringObjectMap3 = spmOrderService.selectSpmOrderStat(reqVo);

        Map<String, Object> resultMap = new HashMap<>();
        if (stringObjectMap1 == null) {
            resultMap.put("saleWeight", "0");
            resultMap.put("saleOrderNum", "0");
        } else {
            resultMap.put("saleWeight", stringObjectMap1.get("sum") == null ? "0" : stringObjectMap1.get("sum").toString());
            resultMap.put("saleOrderNum", stringObjectMap1.get("count") == null ? "0" : stringObjectMap1.get("count").toString());
        }
        if (stringObjectMap2 == null) {
            resultMap.put("sendWeight", "0");
        } else {
            resultMap.put("sendWeight", stringObjectMap2.get("sum") == null ? "0" : stringObjectMap2.get("sum").toString());
        }
        if (stringObjectMap3 == null) {
            resultMap.put("sendNum", "0");
        } else {
            resultMap.put("sendNum", stringObjectMap3.get("count") == null ? "0" : stringObjectMap3.get("count").toString());
        }

        return AjaxResult.success(resultMap);
    }

    /**
     * 溯源大屏农产品销量top5
     */
    @PreAuthorize("@ss.hasPermi('fms:screen:spm:order:goods:stat')")
    @GetMapping("/spm/order/goods/stat")
    public AjaxResult spmOrderGoodsStat(SelectCountOfScreenReqVo reqVo) {
        return AjaxResult.success(spmOrderService.selectSpmOrderByGoodsStat(reqVo));
    }
    
    /**
     * 溯源大屏农产品销售额top5
     */
    @PreAuthorize("@ss.hasPermi('fms:screen:spm:order:money:stat')")
    @GetMapping("/spm/order/money/stat")
    public AjaxResult spmOrderMoneyStat(SelectCountOfScreenReqVo reqVo) {
    	return AjaxResult.success(spmOrderService.selectSpmOrderMoneyByGoodsStat(reqVo));
    }

    /**
     * 溯源大屏省市发货量统计查询
     */
    @PreAuthorize("@ss.hasPermi('fms:screen:spm:order:province:city:stat')")
    @GetMapping("/spm/order/province/city/stat")
    public AjaxResult spmOrderProvinceCityStat(SelectCountOfScreenReqVo reqVo) {
        List<SpmOrderStatResVo> spmOrderStatResVos = spmOrderService.selectCountGroupByProvince(reqVo);
        List<SpmOrderStatResVo> spmOrderStatResVos1 = spmOrderService.selectCountGroupByCity(reqVo);
        JSONArray jsonArray = new JSONArray();
        for (SpmOrderStatResVo spmOrderStatResVo : spmOrderStatResVos) {
            JSONObject jsonObject = JSONObject.from(spmOrderStatResVo);
            JSONArray array = new JSONArray();
            for (SpmOrderStatResVo orderStatResVo : spmOrderStatResVos1) {
                if (spmOrderStatResVo.getOrderConsigneeprovince().equals(orderStatResVo.getOrderConsigneeprovince())) {
                    array.add(orderStatResVo);
                }
            }
            jsonObject.put("citys", array);
            jsonArray.add(jsonObject);
        }
        return AjaxResult.success(jsonArray);
    }

    /**
     * 溯源大屏农产品销量流向
     */
    @PreAuthorize("@ss.hasPermi('fms:screen:spm:order:city:stat')")
    @GetMapping("/spm/order/city/stat")
    public TableDataInfo spmOrderCityStat(SelectCountOfScreenReqVo reqVo) {
        startPage();
        List<SpmOrderStatResVo> spmOrderStatResVos = spmOrderService.selectCountGroupByCity(reqVo);
        return getDataTable(spmOrderStatResVos);
    }

    /**
     * 溯源大屏省市扫码数统计查询
     */
    @PreAuthorize("@ss.hasPermi('fms:screen:scanrcd:province:city:stat')")
    @GetMapping("/scanrcd/province/city/stat")
    public AjaxResult scanrcdProvinceCityStat(SelectCountOfScreenReqVo reqVo) {
        List<TssScanrcdStatResVo> tssScanrcdStatResVos = tssScanrcdService.selectCountByProvince(reqVo);
        List<TssScanrcdStatResVo> tssScanrcdStatResVos1 = tssScanrcdService.selectCountByCity(reqVo);
        JSONArray jsonArray = new JSONArray();
        for (TssScanrcdStatResVo tssScanrcdStatResVo : tssScanrcdStatResVos) {
            JSONObject jsonObject = JSONObject.from(tssScanrcdStatResVo);
            JSONArray array = new JSONArray();
            for (TssScanrcdStatResVo scanrcdStatResVo : tssScanrcdStatResVos1) {
                if (tssScanrcdStatResVo.getScanrcdProvince().equals(scanrcdStatResVo.getScanrcdProvince())) {
                    array.add(scanrcdStatResVo);
                }
            }
            jsonObject.put("citys", array);
            jsonArray.add(jsonObject);
        }
        return AjaxResult.success(jsonArray);
    }

    /**
     * 查询项目所在地坐标
     * @param reqVo
     * @return
     */
    @PreAuthorize("@ss.hasPermi('fms:screen:project:coordinate')")
    @GetMapping("/project/coordinate")
    public AjaxResult projectCoordinate(SelectCountOfScreenReqVo reqVo) {
        String str = ConfigUtils.ConfigKeyEnum.PROJECT_LOCATION_WEATHER_PARAM.valueOf();
        JSONObject jsonObject = JSONObject.parseObject(str);
        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("zoneLatitude", jsonObject.getString("lat"));
        jsonObject1.put("zoneLongitude", jsonObject.getString("lng"));
        jsonObject1.put("city", jsonObject.getString("city"));
        return AjaxResult.success(jsonObject1);

    }

    public Map<String, Object> getCount(SelectCountOfScreenReqVo reqVo) {
        Integer totalNum = tssTracecodeapplyService.selectCountOfTssTracecodeapply(reqVo);
        reqVo.setOrderStatus("1");
        Integer useNum = tssTracecodeapplyService.selectCountOfTssTracecodeapply(reqVo);
        reqVo.setOrderStatus(null);
        Integer rcdNUm = tssScanrcdService.selectCountOfTssScanrcd(reqVo);
        reqVo.setWarnClass(SysWarnEnum.SysWarnClass.SCAN_CODE_PROCESS.getCode());
        Integer warnNum = sysWarnService.selectCount(reqVo);
        reqVo.setWarnClass(null);

        Map<String, Object> map = new HashMap<>();
        map.put("totalNum", totalNum);
        map.put("useNum", useNum);
        map.put("rcdNUm", rcdNUm);
        map.put("warnNum", warnNum);
        return map;
    }

}
