package org.king.modules.ad.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import jodd.util.MathUtil;
import org.apache.poi.ss.formula.functions.T;
import org.apache.shiro.SecurityUtils;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.king.common.system.api.ISysBaseAPI;
import org.king.common.system.base.controller.KingController;
import org.king.common.api.vo.Result;
import org.king.common.system.query.QueryGenerator;
import org.king.common.aspect.annotation.AutoLog;
import org.king.common.system.vo.LoginUser;
import org.king.modules.ad.entity.AdChargingRecord;
import org.king.modules.ad.entity.AdDevice;
import org.king.modules.ad.entity.BaseWharf;
import org.king.modules.ad.entity.ComChargingDevice;
import org.king.modules.ad.entity.ComChargingMonth;
import org.king.modules.ad.entity.Depart;
import org.king.modules.ad.entity.EntCompanyGeom;
import org.king.modules.ad.entity.WebCompany;
import org.king.modules.ad.service.IAdChargingRecordService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.king.modules.ad.service.IAdDeviceService;
import org.king.modules.ad.service.IBaseWharfService;
import org.king.modules.ad.service.IDepartService;
import org.king.modules.ad.service.IEntCompanyGeomService;
import org.king.modules.ad.service.IWebCompanyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.HandlerAdapter;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * @Description: 受电记录
 * @Author: king-boot
 * @Date: 2021-06-07
 * @Version: V1.0
 */
@Slf4j
@Api(tags = "受电记录")
@RestController
@RequestMapping("/ad/adChargingRecord")
public class AdChargingRecordController extends KingController<AdChargingRecord, IAdChargingRecordService> {

    @Autowired
    private IAdChargingRecordService adChargingRecordService;
    @Autowired
    private IDepartService departService;
    @Autowired
    private IBaseWharfService baseWharfService;
    @Autowired
    private IEntCompanyGeomService entCompanyGeomService;
    @Autowired
    private IWebCompanyService webCompanyService;
    @Autowired
    private ISysBaseAPI sysBaseAPI;

    /**
     * 分页列表查询
     *
     * @param adChargingRecord
     * @param pageNo           页码
     * @param pageSize         每页条数
     * @param req
     * @return
     */
    @AutoLog(value = "受电记录-分页列表查询")
    @ApiOperation(value = "受电记录-分页列表查询", notes = "受电记录-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(AdChargingRecord adChargingRecord,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<AdChargingRecord> queryWrapper = QueryGenerator.initQueryWrapper(adChargingRecord, req.getParameterMap());
        Page<AdChargingRecord> page = new Page<>(pageNo, pageSize);
        // 处理部门的数据
        String departId = req.getParameter("departId");
        if (StrUtil.isNotBlank(departId)) {
            List<String> idList = new ArrayList<>();
            idList.add(departId);
            this.checkChildrenExists(departId, idList);
            // 通过查询出所有的机构id查询作业地点数据
            List<Object> ecgNos = baseWharfService.listObjs(Wrappers.<BaseWharf>lambdaQuery().select(BaseWharf::getEcgNo).in(BaseWharf::getDepartNo, idList));
            if (ecgNos == null || ecgNos.size() == 0) {
                return Result.ok(new Page<AdChargingRecord>());
            }
            log.info("查询到的ecgNos：{}", ecgNos);
            // 通过ecgNo查询comNo
            List<Object> comNos = entCompanyGeomService.listObjs(Wrappers.<EntCompanyGeom>lambdaQuery().select(EntCompanyGeom::getComNo).in(EntCompanyGeom::getEcgNo, ecgNos));
            if (comNos == null || comNos.size() == 0) {
                return Result.ok(new Page<AdChargingRecord>());
            }
            log.info("查询到的comNos：{}", comNos);
            // 非空，查询条件增加设备的id
            queryWrapper.in("com_no", comNos);
        }
        // 处理作业单位查询条件
        if (StrUtil.isNotBlank(req.getParameter("comName"))) {
            List<Object> companyNames = webCompanyService.listObjs(Wrappers.<WebCompany>lambdaQuery().select(WebCompany::getComNo).eq(WebCompany::getComName, req.getParameter("comName")));
            if (companyNames == null || companyNames.size() == 0) {
                return Result.ok(new Page<AdChargingRecord>());
            }
            log.info("作业单位查询到的companyNames：{}", companyNames);
            queryWrapper.in("com_no", companyNames);
        }
        IPage<AdChargingRecord> pageList = adChargingRecordService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    private void checkChildrenExists(String departId, List<String> idList) {
        List<Depart> departList = departService.list(Wrappers.<Depart>lambdaQuery().eq(Depart::getUpdepartNo, departId));
        if (departList != null && departList.size() > 0) {
            for (Depart depart : departList) {
                idList.add(Convert.toStr(depart.getDepartNo()));
                this.checkChildrenExists(Convert.toStr(depart.getDepartNo()), idList);
            }
        }
    }

    /**
     * 通过id查询
     *
     * @param id 主键id
     * @return
     */
    @AutoLog(value = "受电记录-通过id查询")
    @ApiOperation(value = "受电记录-通过id查询", notes = "受电记录-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id") String id) {
        AdChargingRecord adChargingRecord = adChargingRecordService.getById(id);
        if (adChargingRecord == null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(adChargingRecord);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param adChargingRecord
     */
    @AutoLog(value = "受电记录-导出excel")
    @ApiOperation(value = "受电记录-导出excel", notes = "受电记录-导出excel")
    @RequestMapping(value = "/exportXls", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView exportXls(HttpServletRequest request, AdChargingRecord adChargingRecord) {
        QueryWrapper<AdChargingRecord> queryWrapper = QueryGenerator.initQueryWrapper(adChargingRecord, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        // 处理部门的数据
        String departId = request.getParameter("departId");
        boolean flag = true;
        if (StrUtil.isNotBlank(departId)) {
            List<String> idList = new ArrayList<>();
            idList.add(departId);
            this.checkChildrenExists(departId, idList);
            // 通过查询出所有的机构id查询作业地点数据
            List<Object> ecgNos = baseWharfService.listObjs(Wrappers.<BaseWharf>lambdaQuery().select(BaseWharf::getEcgNo).in(BaseWharf::getDepartNo, idList));
            if (ecgNos == null || ecgNos.size() == 0) {
                flag = false;
            }
            log.info("查询到的ecgNos：{}", ecgNos);
            // 通过ecgNo查询comNo
            List<Object> comNos = entCompanyGeomService.listObjs(Wrappers.<EntCompanyGeom>lambdaQuery().select(EntCompanyGeom::getComNo).in(EntCompanyGeom::getEcgNo, ecgNos));
            if (comNos == null || comNos.size() == 0) {
                flag = false;
            }
            log.info("查询到的comNos：{}", comNos);
            // 非空，查询条件增加设备的id
            queryWrapper.in("com_no", comNos);
        }
        // 处理作业单位查询条件
        if (StrUtil.isNotBlank(request.getParameter("comName"))) {
            List<Object> companyNames = webCompanyService.listObjs(Wrappers.<WebCompany>lambdaQuery().select(WebCompany::getComNo).eq(WebCompany::getComName, request.getParameter("comName")));
            if (companyNames == null || companyNames.size() == 0) {
                flag = false;
            }
            log.info("作业单位查询到的companyNames：{}", companyNames);
            queryWrapper.in("com_no", companyNames);
        }

        // Step.2 获取导出数据
        List<AdChargingRecord> exportList = new ArrayList<>();
        if (flag) {
            exportList = adChargingRecordService.list(queryWrapper);
        }

        // Step.3 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "受电记录"); //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.CLASS, AdChargingRecord.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("受电记录" + "报表", "导出人:" + sysUser.getRealname(), "受电记录"));
        mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
        return mv;
    }

    @AutoLog(value = "企业月供电统计")
    @ApiOperation(value = "企业月供电统计", notes = "企业月供电统计")
    @GetMapping(value = "/listMonth")
    public Result<?> listMonth(@RequestParam(required = false) String departId,
                               @RequestParam(required = false) String comNo,
                               @RequestParam String month) {
        Map<String, Object> result = new HashMap<>(4);
        List<Object> comNos = new ArrayList<>();
        boolean flag = true;
        if (StrUtil.isNotBlank(departId)) {
            List<String> idList = new ArrayList<>();
            idList.add(departId);
            this.checkChildrenExists(departId, idList);
            // 通过查询出所有的机构id查询作业地点数据
            List<Object> ecgNos = baseWharfService.listObjs(Wrappers.<BaseWharf>lambdaQuery().select(BaseWharf::getEcgNo).in(BaseWharf::getDepartNo, idList));
            if (ecgNos == null || ecgNos.size() == 0) {
                flag = false;
            }
            log.info("查询到的ecgNos：{}", ecgNos);
            // 通过ecgNo查询comNo
            comNos = entCompanyGeomService.listObjs(Wrappers.<EntCompanyGeom>lambdaQuery().select(EntCompanyGeom::getComNo).in(EntCompanyGeom::getEcgNo, ecgNos));
            if (comNos == null || comNos.size() == 0) {
                flag = false;
            }
            log.info("查询到的comNos：{}", comNos);
        }
        List<ComChargingMonth> list = new ArrayList<>();
        if (flag) {
            list = adChargingRecordService.listMonth(comNos, comNo, month);
        }
        // 处理分钟转成小时.计算总量
        BigDecimal totalShipNum = new BigDecimal(0);
        BigDecimal totalConsumption = new BigDecimal(0);
        BigDecimal totalChargeLength = new BigDecimal(0);
        for (ComChargingMonth comChargingMonth : list) {
            comChargingMonth.setChargeLength(NumberUtil.div(comChargingMonth.getChargeLength(), new BigDecimal(60), 2));
            totalShipNum = NumberUtil.add(totalShipNum, comChargingMonth.getShipNum());
            totalConsumption = NumberUtil.add(totalConsumption, comChargingMonth.getConsumption());
            totalChargeLength = NumberUtil.add(totalChargeLength, comChargingMonth.getChargeLength());
        }
        result.put("list", list);
        result.put("totalShipNum", totalShipNum);
        result.put("totalConsumption", totalConsumption);
        result.put("totalChargeLength", totalChargeLength);
        return Result.ok(result);
    }

    @AutoLog(value = "企业月供电-导出excel")
    @ApiOperation(value = "企业月供电-导出excel", notes = "企业月供电-导出excel")
    @RequestMapping(value = "/exportMonthXls", method = {RequestMethod.GET, RequestMethod.POST})
    public ModelAndView exportMonthXls(
                                       @RequestParam(required = false) String departId,
                                       @RequestParam(required = false) String comNo,
                                       @RequestParam String month) {

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        List<Object> comNos = new ArrayList<>();
        boolean flag = true;
        if (StrUtil.isNotBlank(departId)) {
            List<String> idList = new ArrayList<>();
            idList.add(departId);
            this.checkChildrenExists(departId, idList);
            // 通过查询出所有的机构id查询作业地点数据
            List<Object> ecgNos = baseWharfService.listObjs(Wrappers.<BaseWharf>lambdaQuery().select(BaseWharf::getEcgNo).in(BaseWharf::getDepartNo, idList));
            if (ecgNos == null || ecgNos.size() == 0) {
                flag = false;
            }
            log.info("查询到的ecgNos：{}", ecgNos);
            // 通过ecgNo查询comNo
            comNos = entCompanyGeomService.listObjs(Wrappers.<EntCompanyGeom>lambdaQuery().select(EntCompanyGeom::getComNo).in(EntCompanyGeom::getEcgNo, ecgNos));
            if (comNos == null || comNos.size() == 0) {
                flag = false;
            }
            log.info("查询到的comNos：{}", comNos);
        }
        List<ComChargingMonth> list = new ArrayList<>();
        if (flag) {
            list = adChargingRecordService.listMonth(comNos, comNo, month);
        }
        for (ComChargingMonth comChargingMonth : list) {
            comChargingMonth.setChargeLength(NumberUtil.div(comChargingMonth.getChargeLength(), new BigDecimal(60), 2));
        }

        // Step.3 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "企业月供电"); //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.CLASS, ComChargingMonth.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("企业月供电报表", "导出人:" + sysUser.getRealname(), "企业月供电"));
        mv.addObject(NormalExcelConstants.DATA_LIST, list);
        return mv;
    }

    @AutoLog(value = "设备统计")
    @ApiOperation(value = "设备统计", notes = "设备统计")
    @GetMapping(value = "/listDevice")
    public Result<?> listDevice(@RequestParam(required = false) String departId,
                               @RequestParam(required = false) String type,
                               @RequestParam(required = false) String status) {
        Map<String, Object> result = new HashMap<>(4);
        List<Object> comNos = new ArrayList<>();
        boolean flag = true;
        if (StrUtil.isNotBlank(departId)) {
            List<String> idList = new ArrayList<>();
            idList.add(departId);
            this.checkChildrenExists(departId, idList);
            // 通过查询出所有的机构id查询作业地点数据
            List<Object> ecgNos = baseWharfService.listObjs(Wrappers.<BaseWharf>lambdaQuery().select(BaseWharf::getEcgNo).in(BaseWharf::getDepartNo, idList));
            if (ecgNos == null || ecgNos.size() == 0) {
                flag = false;
            }
            log.info("查询到的ecgNos：{}", ecgNos);
            // 通过ecgNo查询comNo
            comNos = entCompanyGeomService.listObjs(Wrappers.<EntCompanyGeom>lambdaQuery().select(EntCompanyGeom::getComNo).in(EntCompanyGeom::getEcgNo, ecgNos));
            if (comNos == null || comNos.size() == 0) {
                flag = false;
            }
            log.info("查询到的comNos：{}", comNos);
        }
        List<ComChargingDevice> list = new ArrayList<>();
        if (flag) {
            list = adChargingRecordService.listDevice(comNos, type, status);
        }
        // 处理分钟转成小时.计算总量
        BigDecimal totalShipNum = new BigDecimal(0);
        BigDecimal totalConsumption = new BigDecimal(0);
        for (ComChargingDevice comChargingDevice : list) {
            // 字典翻译
            comChargingDevice.setType(sysBaseAPI.queryDictTextByKey("ad_device_type",comChargingDevice.getType()));
            comChargingDevice.setStatus(sysBaseAPI.queryDictTextByKey("ad_device_status",comChargingDevice.getStatus()));
            totalShipNum = NumberUtil.add(totalShipNum, comChargingDevice.getShipNum());
            totalConsumption = NumberUtil.add(totalConsumption, comChargingDevice.getConsumption());
        }
        result.put("list", list);
        result.put("totalShipNum", totalShipNum);
        result.put("totalConsumption", totalConsumption);
        result.put("totalDevice", list.size());
        return Result.ok(result);
    }

}
