package com.tofly.watermeter.custom.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tofly.api.DepartmentClient;
import com.tofly.common.core.entity.ResultRespone;
import com.tofly.common.core.util.StringUtil;
import com.tofly.common.oauth.exception.ToflyDeniedException;
import com.tofly.pojo.Department;
import com.tofly.watermeter.custom.entity.Statistic;
import com.tofly.watermeter.custom.service.StatisticService;
import com.tofly.watermeter.em.Constant;
import com.tofly.watermeter.em.ExcelExportFileTypeEnum;
import com.tofly.watermeter.entity.Bwckdatail;
import com.tofly.watermeter.entity.Bwhbdatail;
import com.tofly.watermeter.entity.Bwrksbdatail;
import com.tofly.watermeter.entity.Bwsbyjgl;
import com.tofly.watermeter.mapper.BwrktotalMapper;
import com.tofly.watermeter.service.*;
import com.tofly.watermeter.strategy.ExcelStrategyContext;
import com.tofly.watermeter.util.ExcelUtil;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author FlashWJL
 * @date 2021/3/24 19:22
 */
@Service
@AllArgsConstructor
public class StatisticServiceImpl implements StatisticService {
    private final BwrksbdatailService sbService;
    private final BwckdatailService ckService;
    private final BwsbyjglService yjService;
    private final DepartmentClient client;
    private final WatermeterService meterService;
    private final FileService fileService;
    private final BwhbdatailService hbService;
    private final BwrktotalMapper bwrktotalMapper;
    private final ExcelStrategyContext excelStrategyContext;


    @Override
    public IPage<Map> getInstall(Page page, Statistic statistic) {
        return sbService.getInstall(page, statistic);
    }

    @Override
    public IPage<Map> getScrap(Page page, Statistic statistic) {
        return yjService.getScrap(page, statistic);
    }

    @Override
    public IPage<Map> getScrapInfo(Page page, Statistic statistic) {

//        return sbService.getScrapInfo(cj,kj,lx,"61");

        return yjService.getScrapInfo(page, statistic);
        //需要写
//        return sbService.page(page,Wrappers.<Bwrksbdatail>lambdaQuery().eq(Bwrksbdatail::getBwSbkj,kj)
//                .eq(Bwrksbdatail::getBwSbcj,cj).eq(Bwrksbdatail::getBwSblx,lx).eq(Bwrksbdatail::getBwSbzt,"61"));
    }

    @Override
    public IPage<Bwrksbdatail> getHbInfo(Page page, Statistic statistic) {
        return sbService.getHbInfo(page, statistic);


    }

    @Override
    public IPage<Map> getMeterFlow(Page page, Statistic statistic, HttpServletResponse response) {
//        Long cj = statistic.getBwSbcj();
//        Long kj = statistic.getBwSbkj();
//        Long lx = statistic.getBwSblx();
//        String sbbh = statistic.getSbbh();
//        Long sbzt = statistic.getSbzt();
        String templateFlag = statistic.getTemplateFlag();

        Page<Map> info = bwrktotalMapper.queryMeterInfo(page, statistic);

       /* IPage<Bwrksbdatail> info = sbService.page(page, Wrappers.<Bwrksbdatail>lambdaQuery()
                .and(StringUtil.isNotEmpty(sbbh), w -> w.like(Bwrksbdatail::getBwSbbh, sbbh).or().like(Bwrksbdatail::getBwKhbh, sbbh))
                .eq(StringUtil.isNotNull(cj), Bwrksbdatail::getBwSbcj, cj)
                .eq(StringUtil.isNotNull(kj), Bwrksbdatail::getBwSbkj, kj)
                .eq(StringUtil.isNotNull(lx), Bwrksbdatail::getBwSblx, lx)
                .eq(StringUtil.isNotNull(sbzt), Bwrksbdatail::getBwSbzt, sbzt));*/
        //如果传的是 1，则代表导出Excel数据
        if ("1".equals(templateFlag)) {
            // 根据templateServiceType,templateFlag获取对应模板数据
            ExcelExportFileTypeEnum excelExportFileTypeEnum = ExcelExportFileTypeEnum.getExcelExportFileTypeEnum("meterFlowService", templateFlag);
            if (null == excelExportFileTypeEnum) {
                return null;
            }
            //将查询的结果转json字符串的格式，因为导出的时候只能传一个字符串
            String resultListToString = JSONArray.toJSONString(info.getRecords());
            // 从模型类型枚举根据templateServiceType获取策略对应模板数据
            List<Map<String, Object>> dataList = excelStrategyContext.getExportData("meterFlowService", templateFlag, resultListToString);
            ExcelUtil.export(dataList.get(0), excelExportFileTypeEnum, Constant.FILE_PATH_TEST_EXPORT_EXCEL, response);
            return null;
        }
        return info;

    }

    @Override
    public LinkedHashMap<String, Map> getFlowDetails(Statistic statistic) {

        LinkedHashMap<String, Map> result = new LinkedHashMap<>();

        String sbbh = statistic.getSbbh();

        if (StringUtil.isEmpty(sbbh)) {
            throw new ToflyDeniedException("请输入水表编号");
        }
        Bwrksbdatail sbServiceOne = sbService.getOne(Wrappers.<Bwrksbdatail>lambdaQuery().eq(Bwrksbdatail::getBwSbbh, sbbh));
        Map rkMap = new HashMap();
        Map ckMap = new HashMap();
        Map xzMap = new HashMap();
        if (sbServiceOne != null) {
            //入库
            rkMap.put("sbcj", sbServiceOne.getSbcjName());
            rkMap.put("sbkj", sbServiceOne.getSbkjName());
            rkMap.put("sblx", sbServiceOne.getSblxName());
            rkMap.put("lsbh", sbServiceOne.getBwLsbh());
            rkMap.put("sbbh", sbServiceOne.getBwSbbh());
            rkMap.put("createDate", sbServiceOne.getCreateDate());
            rkMap.put("createUserName", sbServiceOne.getCreateUserName());

            Long ckId = sbServiceOne.getCkId();

            if (ckId != null) {
                //查询出库记录
                Bwckdatail ckServiceOne = ckService.getOne(Wrappers.<Bwckdatail>lambdaQuery().eq(Bwckdatail::getId, ckId)
                        .select(Bwckdatail::getBwLsbh, Bwckdatail::getBwSbcj, Bwckdatail::getBwSbkj,
                                Bwckdatail::getBwSblx, Bwckdatail::getBwLqry, Bwckdatail::getBwLqbm,
                                Bwckdatail::getCreateUser, Bwckdatail::getCreateDate));
                if (ckServiceOne != null) {
                    ResultRespone<Department> departmentResultRespone = client.getById(ckServiceOne.getBwLqbm());
                    String deptName = departmentResultRespone.getResult().getParentName();

                    ckMap.put("sbcj", ckServiceOne.getSbcjName());
                    ckMap.put("sbkj", ckServiceOne.getSbkjName());
                    ckMap.put("sblx", ckServiceOne.getSblxName());
                    ckMap.put("lsbh", ckServiceOne.getBwLsbh());
                    ckMap.put("sbbh", sbServiceOne.getBwSbbh());
                    ckMap.put("createDate", ckServiceOne.getCreateDate());
                    ckMap.put("createUserName", ckServiceOne.getCreateUserName());
                    ckMap.put("deptName", deptName);
                    ckMap.put("lqryName", ckServiceOne.getLqryName());

                }
            }

            if (sbServiceOne.getBwAzry() != null || sbServiceOne.getSbazdz() != null || sbServiceOne.getBwAzrq() != null) {
                xzMap.put("createDate", sbServiceOne.getBwAzrq());
                xzMap.put("createUserName", sbServiceOne.getAzryName());
            }

        }


        //换表
        List<Bwhbdatail> bwhbdatail = hbService.list(Wrappers.<Bwhbdatail>lambdaQuery().eq(Bwhbdatail::getBwJbbh, sbbh)
                .select(Bwhbdatail::getBwHbry, Bwhbdatail::getBwHbrq).orderByDesc(Bwhbdatail::getBwHbrq));

        Map hbMap = new HashMap();
        if (CollectionUtil.isNotEmpty(bwhbdatail)) {
            Bwhbdatail hb = bwhbdatail.get(0);
            hbMap.put("createDate", hb.getBwHbrq());
            hbMap.put("createUserName", hb.getHbryName());
        }

        //报废

/*        List<Bwsbyjgl> bwsbyjglList = yjService.list(Wrappers.<Bwsbyjgl>lambdaQuery().eq(Bwsbyjgl::getSbzsbh, sbbh)
                .select(Bwsbyjgl::getBwSbzd, Bwsbyjgl::getBwYjyy, Bwsbyjgl::getBwJsbm, Bwsbyjgl::getBwJsry,
                        Bwsbyjgl::getBwYjrq, Bwsbyjgl::getBwYjry, Bwsbyjgl::getCreateDate, Bwsbyjgl::getCreateUser,
                        Bwsbyjgl::getBwYjlx));
        Map map = new HashMap();
        if (bwsbyjglList != null && bwsbyjglList.size() > 0) {
            Bwsbyjgl yjServiceOne = bwsbyjglList.get(bwsbyjglList.size() - 1);
            ResultRespone<Department> departmentResultRespone1 = client.getById(yjServiceOne.getBwJsbm());
            String deptName1 = departmentResultRespone1.getResult().getParentName();

            map.put("sbInfo", sbServiceOne);
            map.put("yjdetail", yjServiceOne);
            map.put("jsDept", deptName1);
        }*/


        //退库
//            throw new ToflyDeniedException("宴权，宴权，宴权，这里没做  没做；不要乱传哈");
        //查询新表移交数据，但是可能会出现一个表多次新表移交退库的情况，所以取最后一次的记录（移交时间）
        Bwsbyjgl maxYjgl = yjService.getOne(Wrappers.<Bwsbyjgl>lambdaQuery().eq(Bwsbyjgl::getSbzsbh, sbbh)
                .eq(Bwsbyjgl::getBwYjlx, 1)
                .orderByDesc(Bwsbyjgl::getBwYjrq).apply("ROWNUM = 1"));
        Map tkMap = new HashMap();
        if (maxYjgl != null) {
            tkMap.put("createDate", maxYjgl.getBwYjrq());
            tkMap.put("createUserName", maxYjgl.getBwYjryName());
        }

        if (CollectionUtil.isNotEmpty(rkMap)) {
            result.put("1", rkMap);
        }
        if (CollectionUtil.isNotEmpty(ckMap)) {
            result.put("2", ckMap);
        }
        if (CollectionUtil.isNotEmpty(tkMap)) {
            result.put("8", tkMap);
        }
        if (CollectionUtil.isNotEmpty(xzMap)) {
            result.put("3", xzMap);
        }
        if (CollectionUtil.isNotEmpty(hbMap)) {
            result.put("9", hbMap);
        }
        /*if (CollectionUtil.isNotEmpty(map)) {
            result.put("7", map);
        }*/
        return result;
    }

    @Override
    public List<Map> getCjSta(Statistic statistic) {
        String state = statistic.getQueryState();
        //1：库存统计，2：新装统计，3：出库统计，4：报废统计，5：换表统计，6：争议统计
        if ("1".equals(state)) {
            return bwrktotalMapper.getkcSta();
        } else if ("2".equals(state)) {
            return bwrktotalMapper.getXzSta();
        } else if ("3".equals(state)) {
            return bwrktotalMapper.getCkSta();
        } else if ("4".equals(state)) {
            return bwrktotalMapper.getBfSta();
        } else if ("5".equals(state)) {
            return bwrktotalMapper.getHbSta();
        } else if ("6".equals(state)) {
            return bwrktotalMapper.getZySta();
        }
        return null;
    }

    @Override
    public IPage<Map> getSyDate(Page page, Statistic statistic) {
        return hbService.getSyDate(page, statistic);
    }

    @Override
    public IPage<Map> getSyDateDetails(Page page, Statistic statistic, HttpServletResponse response) {
        Long cj = statistic.getBwSbcj();
        Long kj = statistic.getBwSbkj();
        Long lx = statistic.getBwSblx();
        Integer syDate = statistic.getSyDate();
        String templateFlag = statistic.getTemplateFlag();
        if (StringUtil.isNull(cj) || StringUtil.isNull(kj) || StringUtil.isNull(lx) || StringUtil.isNull(syDate)) {
            throw new ToflyDeniedException("请传递查询时必要参数");
        }
        //导出
        if ("1".equals(templateFlag)) {
            List<Map> mapList = hbService.getSyDateDetailsList(cj, kj, lx, syDate);
            // 根据templateServiceType,templateFlag获取对应模板数据
            ExcelExportFileTypeEnum excelExportFileTypeEnum = ExcelExportFileTypeEnum.getExcelExportFileTypeEnum("meterSyDateService", templateFlag);
            if (null == excelExportFileTypeEnum) {
                return null;
            }
            //将查询的结果转json字符串的格式，因为导出的时候只能传一个字符串
            String resultListToString = JSONArray.toJSONStringWithDateFormat(mapList, "yyyy-MM-dd HH:mm:ss");
            // 从模型类型枚举根据templateServiceType获取策略对应模板数据
            List<Map<String, Object>> dataList = excelStrategyContext.getExportData("meterSyDateService", templateFlag, resultListToString);
            ExcelUtil.export(dataList.get(0), excelExportFileTypeEnum, Constant.FILE_PATH_TEST_EXPORT_EXCEL, response);
            return null;
        } else {
            IPage<Map> iPage = hbService.getSyDateDetails(page, cj, kj, lx, syDate);
            return iPage;
        }
    }

    @Override
    public IPage<Bwrksbdatail> getInstallInfo(Page page, Statistic statistic) {
        Long cj = statistic.getBwSbcj();
        Long kj = statistic.getBwSbkj();
        Long lx = statistic.getBwSblx();
        Date start = statistic.getStartTime();
        Date end = statistic.getEndTime();
        return sbService.page(page, Wrappers.<Bwrksbdatail>lambdaQuery().eq(Bwrksbdatail::getBwSbkj, kj)
                .eq(Bwrksbdatail::getBwSbcj, cj).eq(Bwrksbdatail::getBwSblx, lx)
                .eq(Bwrksbdatail::getBwSbzt, "57")
                .between(StringUtil.isNotNull(start) && StringUtil.isNotNull(end), Bwrksbdatail::getBwAzrq, start, end));
    }

    @Override
    public IPage<Map> getCkSb(Page page, Statistic statistic) {
        return sbService.getCkSb(page, statistic);
    }

    @Override
    public IPage<Bwckdatail> getCkSbInfo(Page page, Statistic statistic) {
        Long cj = statistic.getBwSbcj();
        Long kj = statistic.getBwSbkj();
        Long lx = statistic.getBwSblx();
        Date start = statistic.getStartTime();
        Date end = statistic.getEndTime();
        return ckService.page(page, Wrappers.<Bwckdatail>lambdaQuery().eq(Bwckdatail::getBwSbkj, kj).eq(Bwckdatail::getBwSblx, lx)
                .eq(Bwckdatail::getBwSbcj, cj)
                .between(StringUtil.isNotNull(start) && StringUtil.isNotNull(end), Bwckdatail::getCreateDate, start, end));
    }

    @Override
    public List<Map> getHb(Statistic statistic, HttpServletResponse response) {
        return sbService.getHb(statistic, response);
    }


}
