/*
 * Author: wangjian
 * 生成ServiceImpl
 */
package com.tofly.watermeter.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tofly.common.core.util.Date8Util;
import com.tofly.common.core.util.DateUtil;
import com.tofly.common.core.util.StringUtil;
import com.tofly.common.oauth.exception.ToflyDeniedException;
import com.tofly.watermeter.config.ComConstans;
import com.tofly.watermeter.config.ForeignConfig;
import com.tofly.watermeter.custom.dto.*;
import com.tofly.watermeter.custom.entity.KhSearch;
import com.tofly.watermeter.custom.entity.quality.QualityStatis;
import com.tofly.watermeter.custom.entity.webserverbean.CustomerAddorUpdate;
import com.tofly.watermeter.custom.entity.webserverbean.InstallCustom;
import com.tofly.watermeter.custom.service.websb.WebSBservice;
import com.tofly.watermeter.custom.util.SnowflakeUtils;
import com.tofly.watermeter.em.Constant;
import com.tofly.watermeter.em.ExcelExportFileTypeEnum;
import com.tofly.watermeter.entity.*;
import com.tofly.watermeter.mapper.QfkhjbxxMapper;
import com.tofly.watermeter.mapper.YhbingqyMapper;
import com.tofly.watermeter.service.*;
import com.tofly.watermeter.util.JxlsUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 营销档案客户基本信息表
 *
 * @author wangjieliu
 * @date Fri Mar 19 00:00:00 CST 2021
 */
@Slf4j
@Service("qfkhjbxxService")
@AllArgsConstructor
public class QfkhjbxxServiceImpl extends ServiceImpl<QfkhjbxxMapper, Qfkhjbxx> implements QfkhjbxxService {

    private final QfcbqfmxlsService qfcbqfmxlsService;
    private final QfmidjfjlEService qfmidjfjlEService;
    private final QfmidsfjlEService sfService;
    private final WebSBservice webSBservice;
    private final ReadmeterhisService readmeterhisService;
    private final ForeignConfig foreignConfig;
    private final QfkhjbxxYsxzService qfkhjbxxYsxzService;
    private final YhbingqyMapper yhbingqyMapper;
    private final GjglService gjglService;


    @Override
    public List<Qfkhjbxx> getZjData(String presentMonth) {
        return baseMapper.getZjData(presentMonth);
    }


    @Override
    public List<Map> getCodeByFids() {
        return baseMapper.getCodeByFids();
    }

    @Override
    public List<Map> getIdByFid(Integer fid) {
        return baseMapper.getIdByFid(fid);
    }


    @Override
    public String getCodeById(Long id) {
        return baseMapper.getCodeById(id);
    }

    @Override
    public Map synKH(String inputContent) {
        List<Qfkhjbxx> qfkhjbxxList = baseMapper.getLisrKh(inputContent);

        Qfkhjbxx qfkhjbxx = qfkhjbxxList.get(0);
        qfkhjbxx.setSfjt(qfkhjbxx.getSfjt().equals("1") ? "是" : "否");
        qfkhjbxx.setSfjl(qfkhjbxx.getSfjl().equals("1") ? "是" : "否");
        qfkhjbxx.setSfjf(qfkhjbxx.getSfjf().equals("1") ? "是" : "否");
        qfkhjbxx.setSfYsdh(qfkhjbxx.getSfYsdh().equals("1") ? "是" : "否");
        qfkhjbxx.setCbzq(qfkhjbxx.getCbzq().equals("1") ? "双月" : "单月");


        String yhbh = qfkhjbxx.getYhbh();
        Map map = new HashMap();
        if (StringUtil.isNotEmpty(yhbh)) {
            //抄表历史
            List<Qfcbqfmxls> mxLs = qfcbqfmxlsService.list(Wrappers.<Qfcbqfmxls>lambdaQuery().eq(Qfcbqfmxls::getYhbh, yhbh)
                    .select(Qfcbqfmxls::getYhbh, Qfcbqfmxls::getCbrq, Qfcbqfmxls::getCbfsCode, Qfcbqfmxls::getScds,
                            Qfcbqfmxls::getBcds, Qfcbqfmxls::getBcjjl, Qfcbqfmxls::getCbb));
            //计费记录
            List<QfmidjfjlE> qfmidjfjlES = qfmidjfjlEService.list(Wrappers.<QfmidjfjlE>lambdaQuery().eq(QfmidjfjlE::getYhbh, yhbh)
                    .select(QfmidjfjlE::getYhbh, QfmidjfjlE::getCbyf, QfmidjfjlE::getSl, QfmidjfjlE::getYsje, QfmidjfjlE::getSfry,
                            QfmidjfjlE::getSfrq, QfmidjfjlE::getZzsje));
            //收费记录
            List<QfmidsfjlE> qfmidsfjlEList = sfService.list(Wrappers.<QfmidsfjlE>lambdaQuery().eq(QfmidsfjlE::getYhbh, yhbh).select(QfmidsfjlE::getYhbh, QfmidsfjlE::getCbyf,
                    QfmidsfjlE::getScds, QfmidsfjlE::getBcds, QfmidsfjlE::getSl, QfmidsfjlE::getFyje, QfmidsfjlE::getSsje, QfmidsfjlE::getKfje,
                    QfmidsfjlE::getSfrq, QfmidsfjlE::getSfry, QfmidsfjlE::getSfyf, QfmidsfjlE::getJbsf));

            map.put("jfRecord", qfmidjfjlES);
            map.put("sfRecord", qfmidsfjlEList);
            map.put("cbmxLs", mxLs);
        }
        map.put("khInfo", qfkhjbxx);


        return map;
    }

    @Override
    public boolean deleteAll() {
        return baseMapper.deleteAll();
    }

    @Override
    public Qfkhjbxx getKhInfoByYhbh(String yhbh) {
        return baseMapper.getKhInfoByJbbh(yhbh);
    }

    @Override
    public Long getIdByCode(int pcid, String sbcj) {
        return baseMapper.getIdByCode(pcid, sbcj);
    }

    @Override
    public boolean updateBatchCustom(List<InstallCustom> newInstallList) {
        return baseMapper.updateBatchCustom(newInstallList);
    }

    @Override
    public boolean getUpdateAndInsert() {
//        //获取当天时间
//        Date currentDate = Date8Util.getCurrentDate();
//        //当前时间转格式
//        String currentDay = DateUtil.parseDateToStr("yyyyMMddHHmmss" , currentDate);
//        //5S后的时间
//        String lastDay = DateUtil.parseDateToStr("yyyyMMddHHmmss" , Date7Utils.addSecond(currentDate , 10));
        //获取当天时间
        Date currentDate = Date8Util.getCurrentDate();
        //当前时间转格式
        String currentDay = DateUtil.parseDateToStr("yyyyMMdd", currentDate);
        //5S后的时间
        String lastDay = DateUtil.parseDateToStr("yyyyMMdd", Date8Util.addHour(currentDate, 24L));
        CustomerAddorUpdate customerAddorUpdate = new CustomerAddorUpdate();
        //1：新增；2：修改
        //修改
        customerAddorUpdate.setTYPE("2");
        customerAddorUpdate.setSTART_DATE(currentDay);
        customerAddorUpdate.setEND_DATE(lastDay);
        customerAddorUpdate.setACTION("query");
        List<Qfkhjbxx> updateKhList = webSBservice.getUpdateAndInsert(customerAddorUpdate);
        //新增
        customerAddorUpdate.setTYPE("1");
        List<Qfkhjbxx> insertKhList = webSBservice.getUpdateAndInsert(customerAddorUpdate);
        //数据库操作
        if (StringUtil.isNotNull(updateKhList) && updateKhList.size() > 0) {
            baseMapper.updateKh(updateKhList);
        }
        if (StringUtil.isNotNull(insertKhList) && insertKhList.size() > 0) {

            this.saveBatch(insertKhList);
        }

        return true;
    }

    @Override
    public IPage<Qfkhjbxx> getKhLike(Page page, String phone, String yhbh, String yhxm, String inputcontent,String yhdz,String sbbh,String sfzh) {
        return baseMapper.getKhLike(page, phone, yhbh, yhxm, inputcontent, yhdz,sbbh,sfzh);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object saveYhInfo(ForeignYhInfoDto dtos) {

        List<String> inyhbh = new ArrayList<>();
        List<Qfkhjbxx> ins = new ArrayList<>();
        List<QfkhjbxxYsxz> ysxzs = new ArrayList<>();

        //更新用户信息
        List<Qfkhjbxx> upts = new ArrayList<>();
        List<String> lxyhnh = new ArrayList<>();
        List<QfkhjbxxYsxz> upysxzs = new ArrayList<>();
        //存放销户的用户信息
        List<String> closingYh = new ArrayList<>();
        for (ForeignQfkhjbxxDto dto : dtos.getDatas()) {
            Qfkhjbxx qfkhjbxx = new Qfkhjbxx();
            BeanUtils.copyProperties(dto, qfkhjbxx);
            if (ComConstans.INT_ONE.equals(dto.getType())) {
                qfkhjbxx.setYhzt(ComConstans.INT_ZERO);
                ins.add(qfkhjbxx);
                inyhbh.add(qfkhjbxx.getYhbh());
                if (fillQfkhjbxxYsxz(null, ysxzs, dto)) {
                    return "新建用户无用水性质";
                }
                continue;
            }
            fillQfkhjbxxYsxz(lxyhnh, upysxzs, dto);
            upts.add(qfkhjbxx);
            //是否销户
            if ("9".equals(qfkhjbxx.getYhzt())) {
                closingYh.add(qfkhjbxx.getYhbh());
            }
        }
        if (!ins.isEmpty()) {
            this.remove(new QueryWrapper<Qfkhjbxx>().lambda().in(Qfkhjbxx::getYhbh, inyhbh));
            log.info("网厅推送新增用户信息：" + ins.toString());
            if (!this.saveBatch(ins)) {
                throw new RuntimeException("新增失败");
            }
            qfkhjbxxYsxzService.remove(new QueryWrapper<QfkhjbxxYsxz>().lambda().in(QfkhjbxxYsxz::getYhbh, inyhbh));
            qfkhjbxxYsxzService.saveBatchQfkhjbxxYsxz(ysxzs);

        }
        String monthPlan = readmeterhisService.getMaxMonthPlan();
        if (!upts.isEmpty()) {
            //更新客户信息
            log.info("网厅推送更改用户信息：" + upts.toString());
            this.baseMapper.updateKh(upts);
            //更新抄表用户信息
            readmeterhisService.updateYhInfo(upts, monthPlan);
            if (CollUtil.isNotEmpty(lxyhnh)) {
                qfkhjbxxYsxzService.remove(new QueryWrapper<QfkhjbxxYsxz>().lambda().in(QfkhjbxxYsxz::getYhbh, lxyhnh));
                qfkhjbxxYsxzService.saveBatchQfkhjbxxYsxz(upysxzs);
            }
        }
        //删除销户的分配绑定信息
        if (!closingYh.isEmpty()) {
            yhbingqyMapper.delete(Wrappers.<Yhbingqy>lambdaQuery().in(Yhbingqy::getYhbh, closingYh));
        }
        return true;
    }

    /**
     * 填充用户信息用水类型
     *
     * @param lxyhnh  用户编号集合
     * @param upysxzs 用水类型对象集合
     * @param dto     用户信息数据
     */
    private boolean fillQfkhjbxxYsxz(List<String> lxyhnh, List<QfkhjbxxYsxz> upysxzs, ForeignQfkhjbxxDto dto) {
        if (CollUtil.isNotEmpty(dto.getYslxs())) {
            if (lxyhnh != null) {
                lxyhnh.add(dto.getYhbh());
            }
            for (WaterPropertiesDto ysdto : dto.getYslxs()) {
                QfkhjbxxYsxz qfkhjbxxYsxz = new QfkhjbxxYsxz();
                BeanUtils.copyProperties(ysdto, qfkhjbxxYsxz);
                qfkhjbxxYsxz.setYhbh(dto.getYhbh());
                qfkhjbxxYsxz.setId(SnowflakeUtils.getId(foreignConfig.getDate(), foreignConfig.getWorkerId(), ComConstans.SNOWFLAKE_YH_TYPE));
                upysxzs.add(qfkhjbxxYsxz);
            }
            return false;
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object updateYhAmountOrWaterVolume(AmountOrWaterVolumeDto dto) {

        List<AmountOrWaterVolumeInfoDto> datas = dto.getDatas().stream()
                .filter(d -> d.getScds() != null || d.getQfje() != null || StringUtils.isNotEmpty(d.getQfzq()) || StringUtils.isNotEmpty(d.getSfqf()) || d.getZhye() != null)
                .collect(Collectors.toList());
        if (CollUtil.isEmpty(datas)) {
            return "变更数据信息为空！";
        }

        //更新用户上次读数、账号余额、是否欠费信息
        List<AmountOrWaterVolumeInfoDto> scdss = datas.stream().filter(d -> d.getScds() != null).collect(Collectors.toList());

        this.baseMapper.updateYhWaterVolumeInfos(dto.getDatas());

        //更新抄表上次读数
        String monthPlan = readmeterhisService.getMaxMonthPlan();
        readmeterhisService.updateYhWaterVolumeInfos(scdss, monthPlan);


        return true;
    }

    @Override
    public IPage<Qfkhjbxx> commonKh(Page<Qfkhjbxx> page, KhSearch khSearch, HttpServletResponse response) {
        String qybm = khSearch.getQybm();
        String qydbm = khSearch.getQydbm();
        String sbcj = khSearch.getSbcj();
        String yhzt = khSearch.getYhzt();
        String cbb = khSearch.getCbb();
        String ysxz = khSearch.getYsxz();
        List<String> cbqyList = null;
        List<String> cbqydList = null;
        List<String> sbcjList = null;
        List<String> yhztList = null;
        List<String> cbbList = null;
        List<String> ysxzList = null;
        String templateFlag = khSearch.getTemplateFlag();
        if (StringUtil.isNotEmpty(qybm)) {
            cbqyList = Arrays.asList(qybm.split(","));
        }
        if (StringUtil.isNotEmpty(qydbm)) {
            cbqydList = Arrays.asList(qydbm.split(","));
        }
        if (StringUtil.isNotEmpty(sbcj)) {
            sbcjList = Arrays.asList(sbcj.split(","));
        }
        if (StringUtil.isNotEmpty(yhzt)) {
            yhztList = Arrays.asList(yhzt.split(","));
        }
        if (StringUtil.isNotEmpty(cbb)) {
            cbbList = Arrays.asList(cbb.split(","));
        }
        if (StringUtil.isNotEmpty(ysxz)) {
            ysxzList = Arrays.asList(ysxz.split(","));
        }
        if ("1".equals(templateFlag)) {
            List<Qfkhjbxx> qfkhjbxxList = baseMapper.commonKhList(ysxzList, cbqyList, cbqydList, khSearch, sbcjList, yhztList, cbbList);
            // 根据templateServiceType,templateFlag获取对应模板数据
            ExcelExportFileTypeEnum excelExportFileTypeEnum = ExcelExportFileTypeEnum.getExcelExportFileTypeEnum("clientInfoDeatils", "1");
            if (null == excelExportFileTypeEnum) {
                return null;
            }
            Map<String, Object> model = new HashMap<>(10);
            model.put("dataMap", qfkhjbxxList);
//            model.put("exportTime","导出时间");
            // 从模型类型枚举根据templateServiceType获取策略对应模板数据
            JxlsUtils.exportExcel(excelExportFileTypeEnum, model, response, Constant.FILE_PATH_TEST_EXPORT_EXCEL);
            return null;
        }
        IPage<Qfkhjbxx> qfkhjbxxIPage = baseMapper.commonKh(page, ysxzList, cbqyList, cbqydList, khSearch, sbcjList, yhztList, cbbList);
        if (qfkhjbxxIPage.getRecords().size() == 0) {
            throw new ToflyDeniedException("暂未查询到用户信息");
        }
        return qfkhjbxxIPage;
    }

    @Override
    public IPage<Qfkhjbxx> allotInfo(Page<Qfkhjbxx> page, KhSearch khSearch, String collectionNumber, String isWatchType) {
        if (StringUtil.isEmpty(collectionNumber)) {
            throw new ToflyDeniedException("请选择归集");
        }
        String qybm = khSearch.getQybm();
        String qydbm = khSearch.getQydbm();
        String sbkj = khSearch.getSbkj();
        String cbb = khSearch.getCbb();
        String cbpq = khSearch.getCbpq();
        String ysxz = khSearch.getYsxz();
        String sfncys = khSearch.getSfncys();
        String jyz = khSearch.getJyz();
        List<String> cbqyList = null;
        List<String> cbqydList = null;
        List<String> sbkjList = null;
        List<String> cbbList = null;
        List<String> cbpqList = null;
        List<String> ysxzList = null;
        String inputcontent = khSearch.getInputcontent();
        if (StringUtil.isNotEmpty(qybm)) {
            cbqyList = Arrays.asList(qybm.split(","));
        }
        if (StringUtil.isNotEmpty(qydbm)) {
            cbqydList = Arrays.asList(qydbm.split(","));
        }
        if (StringUtil.isNotEmpty(sbkj)) {
            sbkjList = Arrays.asList(sbkj.split(","));
        }
        if (StringUtil.isNotEmpty(cbb)) {
            cbbList = Arrays.asList(cbb.split(","));
        }
        if (StringUtil.isNotEmpty(cbpq)) {
            cbpqList = Arrays.asList(cbpq.split(","));
        }
        if (StringUtil.isNotEmpty(ysxz)) {
            ysxzList = Arrays.asList(ysxz.split(","));
        }
        //根据归集号，筛选未分配的数据
        return baseMapper.allotInfo(page, cbqyList, cbqydList, sbkjList, cbbList, cbpqList, ysxzList,
                inputcontent, collectionNumber, isWatchType, sfncys, jyz);
    }

    @Override
    public IPage<Map> collectAnalyzeOne(Page<Gjgl> page, QualityStatis qualityStatis, HttpServletResponse response) {
        return gjglService.collectAnalyzeOne(page, qualityStatis, response);
    }

    @Override
    public List<Map> collectAnalyzeTwo(String startDate, String endDate, String collectionNumber, HttpServletResponse response) {
        return gjglService.collectAnalyzeTwo(startDate, endDate, collectionNumber, response);
    }

    @Override
    public IPage<Map> collectAnalyzeThree(Page<Gjglxq> page, String startDate, String endDate, String collectionNumber, HttpServletResponse response) {
        return gjglService.collectAnalyzeThree(page, startDate, endDate, collectionNumber, response);
    }

}
