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

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tofly.common.core.util.DateUtil;
import com.tofly.common.oauth.exception.ToflyDeniedException;
import com.tofly.common.oauth.util.SecurityUtils;
import com.tofly.watermeter.custom.dto.ScrapStatisticsDto;
import com.tofly.watermeter.custom.entity.meterBusiness.dto.ImportTurnOver;
import com.tofly.watermeter.custom.entity.meterBusiness.dto.ImportTurnOverDto;
import com.tofly.watermeter.custom.entity.meterBusiness.dto.TurnOverDto;
import com.tofly.watermeter.custom.mapper.TimedTaskMapper;
import com.tofly.watermeter.custom.mapper.meterBusiness.TurnOverMapper;
import com.tofly.watermeter.custom.service.meterBusiness.TurnOverService;
import com.tofly.watermeter.custom.service.meterBusiness.export.ExportCommonCodeService;
import com.tofly.watermeter.entity.Bwrksbdatail;
import com.tofly.watermeter.entity.Bwsbyjgl;
import com.tofly.watermeter.service.BwrkdetailService;
import com.tofly.watermeter.service.BwrksbdatailService;
import com.tofly.watermeter.service.BwsbyjglService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

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

@Service
public class TurnOverServiceImpl implements TurnOverService {

    @Autowired
    private TurnOverMapper turnOverMapper;
    @Autowired
    private ExportCommonCodeService exportCommonCodeService;
    @Autowired
    private BwsbyjglService bwsbyjglService;
    @Autowired
    private BwrkdetailService bwrkdetailService;
    @Autowired
    private BwrksbdatailService bwrksbdatailService;

    private final static String TURM_OVER_TABLE = "TF_YWPN_BWSBYJGL_W";

    @Override
    public Page<Map> canTurnOver(Page page, TurnOverDto dto) {
        return turnOverMapper.canTurnOver(page, dto);
    }

    @Override
    public List<Map> count(HttpServletResponse response, TurnOverDto dto) {
        List<Map> count;
        if (dto.getIsTimeCount() == 0) {
            count = turnOverMapper.count(dto);
        } else {
            count = turnOverMapper.countByTime(dto);
        }

        if (dto.getExport() == 1) {
            if (dto.getIsTimeCount() == 0) {
                exportCommonCodeService.exportCode(response, "turnOverCountService", count);
            } else {
                exportCommonCodeService.exportCode(response, "turnOverCountByTimeService", count);
            }
        }
        return count;
    }

    @Override
    public Page<Map> queryInfo(HttpServletResponse response, Page page, TurnOverDto dto) {
        if (dto.getExport() == 1) {
            exportCommonCodeService.exportCode(response, "turnOverQueryInfoService", turnOverMapper.queryInfo(dto));
        }
        return turnOverMapper.queryInfo(page, dto);
    }

    /**
     * 导入移交信息
     *
     * @param dto dto
     * @return boolean
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean importTurnOver(ImportTurnOverDto dto) {
        if (dto == null) {
            throw new ToflyDeniedException("传入数据为空");
        }
        Long type = dto.getType();
        List<ImportTurnOver> turnOver = dto.getTurnOver();

        if (turnOver == null || turnOver.isEmpty()) {
            throw new ToflyDeniedException("内容为空");
        }

        if (type == null) {
            throw new ToflyDeniedException("移交类型不能为空");
        }

        //收集水表编号（旧）
        List<String> codeOldList = turnOver.stream().map(ImportTurnOver::getCode).collect(Collectors.toList());
        List<String> codeNewList = turnOver.stream().map(ImportTurnOver::getNewCode).collect(Collectors.toList());
        //移交类型-水表退库
        if (type == 1) {
            List<Bwrksbdatail> integers = turnOverMapper.queryTableState(codeOldList, Collections.singletonList("2"));

            if (integers.size() != codeOldList.size()) {
                throw new ToflyDeniedException("水表编号数据异常,请确认数据");
            }
        }

        //查询厂家类型口径
        List<Bwrksbdatail> rksbdatailOld = turnOverMapper.queryTableState(codeOldList, null);

        //根据编号分组
        Map<String, List<Bwrksbdatail>> groupByCodeOld = rksbdatailOld.stream().collect(Collectors.groupingBy(Bwrksbdatail::getBwSbbh));

        List<Bwrksbdatail> rksbdatailNew;
        Map<String, List<Bwrksbdatail>> groupByCodeNew = null;
        if (type != 1) {
            if (codeNewList.isEmpty()) {
                throw new ToflyDeniedException("未传入信表编号");
            }
            rksbdatailNew = turnOverMapper.queryTableState(codeNewList, null);
            groupByCodeNew = rksbdatailNew.stream().collect(Collectors.groupingBy(Bwrksbdatail::getBwSbbh));
        }

        Bwsbyjgl yjgl;

        List<Bwsbyjgl> result = new ArrayList<>();

        String dateFormat = DateUtil.getDateFormat(new Date(), "yyyyMMdd-") + System.currentTimeMillis();

        String checkFlag = type == 1 ? "2" : "0";

        Long maxId = bwrkdetailService.getMaxId(TURM_OVER_TABLE);

        String contractNote = dto.getContractNote();

        for (ImportTurnOver it : turnOver) {

            yjgl = new Bwsbyjgl();
            yjgl.setBwLsbh(dateFormat);
            yjgl.setBwSbkj(StringUtils.isEmpty(it.getCal()) ? null : Long.parseLong(it.getCal()));
            yjgl.setSbkj(StringUtils.isEmpty(it.getNewCal()) ? null : Long.parseLong(it.getNewCal()));
            if (groupByCodeOld.containsKey(it.getCode())) {
                Bwrksbdatail tail = groupByCodeOld.get(it.getCode()).get(0);
                yjgl.setBwSbcj(tail.getBwSbcj());
                yjgl.setBwSblx(tail.getBwSblx());
//                yjgl.setBwSbkj(tail.getBwSbkj());
            }
            yjgl.setSbzsbh(it.getCode());
            yjgl.setContractNote(contractNote);
            yjgl.setBwYjlx(type);
            yjgl.setBwYjyy(it.getCause());
            if (type != 1) {
                yjgl.setUserName(it.getUserName());
                yjgl.setAddress(it.getAddress());
                if (groupByCodeNew != null && groupByCodeNew.containsKey(it.getNewCode())) {
                    Bwrksbdatail tail = groupByCodeNew.get(it.getNewCode()).get(0);
                    yjgl.setSbcj(tail.getBwSbcj());
                    yjgl.setSblx(tail.getBwSblx());
//                    yjgl.setSbkj(tail.getBwSbkj());
                    yjgl.setSbbh(it.getNewCode());
                }
                yjgl.setBwJsbm(dto.getAcceptDept());
                yjgl.setBwJsry(dto.getAcceptUser());
            }
            yjgl.setBwYjry(dto.getTurnOverUser());
            yjgl.setBwYjrq(new Date());
            yjgl.setBwYjbm(dto.getTurnOverDept());
            yjgl.setCheckFlag(checkFlag);
            yjgl.setId(maxId);
            yjgl.setCreateUser(SecurityUtils.getUserId());
            maxId++;
            yjgl.init();
            result.add(yjgl);
        }
        bwsbyjglService.saveBatch(result);
        List<String> tableCodeList = result.stream().map(Bwsbyjgl::getSbzsbh).collect(Collectors.toList());
        if (tableCodeList.size() > 0) {
            //退库
            if (type == 1) {
                turnOverMapper.updateTableState(tableCodeList, "8");
            } else {
                //报废
                turnOverMapper.updateTableState(tableCodeList, "7");
            }
        }
        return true;
    }

    /**
     * 获取不存在数据库水表编码
     *
     * @param code code
     * @return list
     */
    @Override
    public List<String> getNonEntityCode(String code, String sbzt) {
        if (StringUtils.isEmpty(code)) {
            throw new ToflyDeniedException("传入数据为空");
        }
        List<String> codeList = Arrays.stream(code.split(",")).distinct().collect(Collectors.toList());

        List<String> collect = turnOverMapper.queryTableState(codeList, Collections.singletonList(sbzt)).stream().distinct().map(Bwrksbdatail::getBwSbbh).collect(Collectors.toList());

        return codeList.stream().filter(cl -> !collect.contains(cl)).collect(Collectors.toList());
    }

    /**
     * 水表报废统计
     *
     * @param dto dto
     * @return list
     */
    @Override
    public List<Map> scrapStatistics(ScrapStatisticsDto dto) {
        return turnOverMapper.scrapStatistics(dto);
    }

    /**
     * 报废详情
     *
     * @param page page
     * @param dto  dto
     * @return page
     */
    @Override
    public Page<Map> scrapDetail(Page page, ScrapStatisticsDto dto) {
        String status = dto.getStatus();
        if (StringUtils.isEmpty(status)){
            throw new ToflyDeniedException("状态不能为空");
        }
        Page<Map> result = null;
        List<String> vendorList = Arrays.asList(dto.getVendor().split(","));
        switch(status) {
            case "0":
                result = bwrksbdatailService.page(page, Wrappers.<Bwrksbdatail>lambdaQuery()
                        .between(dto.getStartDate() != null && dto.getEndDate() != null,Bwrksbdatail::getCreateDate,dto.getStartDate(),dto.getEndDate())
                        .in(CollectionUtil.isNotEmpty(vendorList),Bwrksbdatail::getBwSbcj,vendorList)
                        .orderByAsc(Bwrksbdatail::getCreateDate));
                break;
            case "1":
                result = bwsbyjglService.page(page, Wrappers.<Bwsbyjgl>lambdaQuery()
                        .between(dto.getStartDate() != null && dto.getEndDate() != null,Bwsbyjgl::getBwYjrq,dto.getStartDate(),dto.getEndDate())
                        .ne(Bwsbyjgl::getBwYjlx,1)
                        .in(CollectionUtil.isNotEmpty(vendorList),Bwsbyjgl::getBwSbcj,vendorList)
                        .orderByAsc(Bwsbyjgl::getBwYjrq));
                break;
            default:
        }
        return result;
    }
}
