package com.ho.filecenter.service.impl;

import com.ho.common.tools.constant.CommonConstant;
import com.ho.common.tools.entity.SimpleUser;
import com.ho.common.tools.exception.BaseResponseCode;
import com.ho.common.tools.exception.BusinessException;
import com.ho.filecenter.constant.FileConstant;
import com.ho.filecenter.entity.Power;
import com.ho.filecenter.entity.PowerDetail;
import com.ho.filecenter.mapper.PowerMapper;
import com.ho.filecenter.service.PowerDetailService;
import com.ho.filecenter.service.PowerService;
import com.ho.filecenter.vo.DetailVo;
import com.ho.filecenter.vo.PowerDetailVo;
import com.ho.filecenter.vo.PowerImport;
import com.ho.filecenter.vo.QueryPower;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author yy
 * @description 针对表【power】的数据库操作Service实现
 * @createDate 2023-03-16 10:59:38
 */
@Service
@Slf4j
public class PowerServiceImpl implements PowerService {
    @Autowired
    PowerMapper powerMapper;

    @Autowired
    PowerDetailService powerDetailService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importExcel(SimpleUser user, List<PowerImport> list) {
        //导入功能
        //存放基本信息表
        Power power = new Power();
        //存放明细表
        List<PowerImport> powerDetailList = new ArrayList<>();
        //基本信息入库
        power.setGroupId(user.getGroupId());
        PowerImport powerImport1 = list.get(0);
        //判断是否为正确的模板（根据t1是否为项目名称确定）
        if (!FileConstant.PaymentStatement.PROJECT_NAME.equals(powerImport1.getT1())) {
            throw new BusinessException(BaseResponseCode.PLEASE_CONFIRM_WHETHER_IMPORTED_TEMPLATE_CORRECT);
        }
        if (powerImport1.getT2() == null) {
            throw new BusinessException(BaseResponseCode.PROJECT_NAME_CANNOT_EMPTY);
        }
        power.setProjectName(powerImport1.getT2());
        PowerImport powerImport2 = list.get(1);
        //对时间都进行处理
        //（判断月份是否大于12月份）
        String time = powerImport2.getT2();
        if (time == null) {
            throw new BusinessException(BaseResponseCode.PLEASE_ENTER_MONTH);
        }
        if (time.contains("（格式：yyyy-mm）")) {
            throw new BusinessException(BaseResponseCode.PLEASE_DELETE_MONTH_FORMAT_PROMPTED_TEMPLATE);
        }
        if (time.length() != 7) {
            throw new BusinessException(BaseResponseCode.ERROR_FORMAT_SETTLEMENT_MONTH_ENTERED);
        }
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM");
        try {
            Date parse = sf.parse(time);
        } catch (ParseException e) {
            throw new BusinessException(BaseResponseCode.ERROR_FORMAT_SETTLEMENT_MONTH_ENTERED);
        }
        String replace = time.replace(".", "-");
        String substring = replace.substring(5, 7);
        int month = Integer.valueOf(substring);
        if (month > 12 || month == CommonConstant.ZERO) {
            throw new BusinessException(BaseResponseCode.EXCEL_TABLE_EXCEEDS_MAXIMUM_MONTH_PLEASE_VERIFY);
        }
        //根据项目名称和月份进行查询 看是否有重复数据
        DetailVo vo = new DetailVo();
        vo.setProjectName(power.getProjectName());
        vo.setSettleMonth(power.getSettleMonth());
        Power powerValue = powerMapper.selectByMonthAndName(vo);
        if (powerValue != null) {
            throw new BusinessException(BaseResponseCode.PROJECT_DATA_THAT_MONTH_PLEASE_VERIFY_MONTH);
        }
        power.setSettleMonth(replace);
        power.setMeterMan(powerImport2.getT11());
        PowerImport powerImport3 = list.get(2);
        power.setBiCycle(powerImport3.getT2());
        power.setChecker(powerImport3.getT11());
        int num = 0;
        for (int i = 5; i < list.size(); i++) {
            num = i;
            PowerImport powerImport = list.get(i);
            if (FileConstant.PaymentStatement.GROSS_GENERATION.equals(powerImport.getT1())) {
                break;
            } else {
                powerDetailList.add(powerImport);
            }
        }
        for (int i = num; i < list.size(); i++) {
            PowerImport powerImport = list.get(i);
            if (FileConstant.PaymentStatement.GROSS_GENERATION.equals(powerImport.getT1())) {
                if (powerImport.getT2() != null) {
                    power.setPowerAll(new BigDecimal(powerImport.getT2()));
                    continue;
                }

            } else if (FileConstant.PaymentStatement.SELF_CONSUMPTION.equals(powerImport.getT1())) {
                if (powerImport.getT2() != null) {
                    power.setPowerSelf(new BigDecimal(powerImport.getT2()));
                    continue;
                }

            } else if (FileConstant.PaymentStatement.ON_GRID_ENERGY.equals(powerImport.getT1())) {
                if (powerImport.getT2() != null) {
                    power.setPowerUp(new BigDecimal(powerImport.getT2()));
                    continue;
                }
            } else if (FileConstant.PaymentStatement.ABSORPTION_RATIO.equals(powerImport.getT1())) {
                if (powerImport.getT2() != null) {
                    power.setConsumeRatio(powerImport.getT2());
                    continue;
                }
            }
            if (powerImport.getT1() != null) {
                if (FileConstant.PaymentStatement.PowerJ.equals(powerImport.getT1())) {
                    if (powerImport.getT2() != null) {
                        power.setPowerJ(new BigDecimal(powerImport.getT2()));
                    }
                    if (powerImport.getT3() != null) {
                        power.setOrigPriceJ(new BigDecimal(powerImport.getT3()));
                    }
                    if (powerImport.getT4() != null) {
                        power.setDiscountPriceJ(new BigDecimal(powerImport.getT4()));
                    }
                    if (powerImport.getT5() != null) {
                        power.setFeeJ(new BigDecimal(powerImport.getT5()));
                    }
                    continue;
                } else if (FileConstant.PaymentStatement.PowerF.equals(powerImport.getT1())) {
                    if (powerImport.getT2() != null) {
                        power.setPowerF(new BigDecimal(powerImport.getT2()));
                    }
                    if (powerImport.getT3() != null) {
                        power.setOrigPriceF(new BigDecimal(powerImport.getT3()));
                    }
                    if (powerImport.getT4() != null) {
                        power.setDiscountPriceF(new BigDecimal(powerImport.getT4()));
                    }
                    if (powerImport.getT5() != null) {
                        power.setFeeF(new BigDecimal(powerImport.getT5()));
                    }
                    continue;
                } else if (FileConstant.PaymentStatement.PowerP.equals(powerImport.getT1())) {
                    if (powerImport.getT2() != null) {
                        power.setPowerP(new BigDecimal(powerImport.getT2()));
                    }
                    if (powerImport.getT3() != null) {
                        power.setOrigPriceP(new BigDecimal(powerImport.getT3()));
                    }
                    if (powerImport.getT4() != null) {
                        power.setDiscountPriceP(new BigDecimal(powerImport.getT4()));
                    }
                    if (powerImport.getT5() != null) {
                        power.setFeeP(new BigDecimal(powerImport.getT5()));
                    }
                    continue;
                } else if (FileConstant.PaymentStatement.PowerG.equals(powerImport.getT1())) {
                    if (powerImport.getT2() != null) {
                        power.setPowerG(new BigDecimal(powerImport.getT2()));
                    }
                    if (powerImport.getT3() != null) {
                        power.setOrigPriceG(new BigDecimal(powerImport.getT3()));
                    }
                    if (powerImport.getT4() != null) {
                        power.setDiscountPriceG(new BigDecimal(powerImport.getT4()));
                    }
                    if (powerImport.getT5() != null) {
                        power.setFeeG(new BigDecimal(powerImport.getT5()));
                    }
                    continue;
                } else if (FileConstant.PaymentStatement.SINGLE_PRICE.equals(powerImport.getT1())) {
                    if (powerImport.getT2() != null) {
                        power.setPowerSigle(new BigDecimal(powerImport.getT2()));
                    }
                    if (powerImport.getT4() != null) {
                        power.setOrigPriceSigle(new BigDecimal(powerImport.getT4()));
                    }
                    if (powerImport.getT4() != null) {
                        power.setDiscountPriceSigle(new BigDecimal(powerImport.getT4()));
                    }
                    if (powerImport.getT5() != null) {
                        power.setFeeSigle(new BigDecimal(powerImport.getT5()));
                    }

                    continue;
                } else if (FileConstant.PaymentStatement.RECEIVABLES.equals(powerImport.getT1())) {

                    if (powerImport.getT5() != null) {
                        power.setReceivableFee(new BigDecimal(powerImport.getT5()));
                    }
                    continue;
                }
            }
        }
        power.setCreateTime(new Date());
        //根据groupId和月份进行比较，有相同的则进行删除  加一个项目名称的判断条件
        List<Power> powerList = powerMapper.selectAll(power.getGroupId(), power.getSettleMonth(), powerImport1.getT2());
        //根据id删除主表，
        List<Integer> idList = powerList.stream().map(s -> {
                    return s.getId();
                }
        ).collect(Collectors.toList());
        if (!idList.isEmpty()) {
            powerMapper.batchDeletes(idList);
            powerDetailService.deleteBatch(new ArrayList<>(), idList);
        }
        // 在将进行入库 -->根据Id = pid  删除子表的数据 -->在将子表的数据进行入库
        //主表入库
        int i = powerMapper.insertSelective(power);
        //明细表入库（根据基本信息表的id先进行删除，在进行入库）
        if (!powerDetailList.isEmpty()) {
            List<PowerDetail> powerDetails = new ArrayList<>();
            for (PowerImport powerImport : powerDetailList) {
                PowerDetail powerDetail = new PowerDetail();
                powerDetail.setPid(power.getId());
                if (powerImport.getT1() != null) {
                    powerDetail.setGroupId(user.getGroupId());
                    powerDetail.setMeterPoint(powerImport.getT1());
                    if (powerImport.getT2() != null) {
                        powerDetail.setTno(powerImport.getT2());
                    }
                    if (powerImport.getT3() != null) {
                        powerDetail.setMultiFactor(new BigDecimal(powerImport.getT3()));
                    }
                    if (powerImport.getT4() != null) {
                        powerDetail.setPowerStartJ(new BigDecimal(powerImport.getT4()));
                    }
                    if (powerImport.getT7() != null) {
                        powerDetail.setPowerStartF(new BigDecimal(powerImport.getT7()));
                    }
                    if (powerImport.getT10() != null) {
                        powerDetail.setPowerStartP(new BigDecimal(powerImport.getT10()));
                    }
                    if (powerImport.getT13() != null) {
                        powerDetail.setPowerStartG(new BigDecimal(powerImport.getT13()));
                    }
                    if (powerImport.getT5() != null) {
                        powerDetail.setPowerEndJ(new BigDecimal(powerImport.getT5()));
                    }
                    if (powerImport.getT8() != null) {
                        powerDetail.setPowerEndF(new BigDecimal(powerImport.getT8()));
                    }
                    if (powerImport.getT11() != null) {
                        powerDetail.setPowerEndP(new BigDecimal(powerImport.getT11()));
                    }
                    if (powerImport.getT14() != null) {
                        powerDetail.setPowerEndG(new BigDecimal(powerImport.getT14()));
                    }
                    if (powerImport.getT6() != null) {
                        powerDetail.setPowerJ(new BigDecimal(powerImport.getT6()));
                    }
                    if (powerImport.getT9() != null) {
                        powerDetail.setPowerF(new BigDecimal(powerImport.getT9()));
                    }
                    if (powerImport.getT12() != null) {
                        powerDetail.setPowerP(new BigDecimal(powerImport.getT12()));
                    }
                    if (powerImport.getT15() != null) {
                        powerDetail.setPowerG(new BigDecimal(powerImport.getT15()));
                    }
                    if (powerImport.getT16() != null) {
                        powerDetail.setTotalPowerStart(new BigDecimal(powerImport.getT16()));
                    }
                    if (powerImport.getT17() != null) {
                        powerDetail.setTotalPowerEnd(new BigDecimal(powerImport.getT17()));
                    }
                    if (powerImport.getT18() != null) {
                        powerDetail.setTotalAmount(new BigDecimal(powerImport.getT18()));
                    }
                    powerDetails.add(powerDetail);
                }else{
                    throw new BusinessException(BaseResponseCode.SJEKK_EXCEL_DATA);
                }
            }
            if (!powerDetails.isEmpty()) {
                powerDetailService.addBatch(powerDetails);
            } else {
                throw new BusinessException(BaseResponseCode.SJEKK_EXCEL_DATA);
            }
        }
    }

    @Override
    public List<Power> queryList(Integer groupId, QueryPower power) {
        if (power == null) {
            power = new QueryPower();
        }
        List<Power> powerList = powerMapper.selectAll(groupId, power.getSettleMonth(), power.getProjectName());
        return powerList;
    }

    @Override
    public int insertSelective(Power power) {
        return powerMapper.insertSelective(power);
    }

    @Override
    public void update(PowerDetailVo vo) {
        //根据id查询基础信息表
        //根据时间和月份进行查询，判断是否存在
        DetailVo update = new DetailVo();
        update.setSettleMonth(vo.getSettleMonth());
        update.setId(vo.getId());
        Power powerValue = powerMapper.selectById(update);
        if (powerValue == null) {
            throw new BusinessException(BaseResponseCode.POWER_BILLS_NOT_RELEVANT_DATA_MONTH);
        }
        //（先根据id将明细表中的数据重新入库，
        //明细表中的pid =id 进行查询
        List<PowerDetail> powerDetails = powerDetailService.selectByPid(vo.getId());
        //判断查询是否为空
        List<PowerDetail> powerDetailList = vo.getPowerDetailList();
        if (powerDetailList != null) {
            if (!powerDetails.isEmpty()) {
                //分解成ids，后批量删除
                List<Integer> ids = powerDetails.stream().map(s -> {
                            return s.getId();
                        }
                ).collect(Collectors.toList());
                int i = powerDetailService.deleteBatch(ids, new ArrayList<>());
                //删除后入库
                if (!vo.getPowerDetailList().isEmpty()) {
                    powerDetailService.addBatch(vo.getPowerDetailList());
                }
            } else {
                if (!vo.getPowerDetailList().isEmpty()) {
                    powerDetailService.addBatch(vo.getPowerDetailList());
                }
            }
        }

        // 后将将基本信息进行更新）
        Power power = new Power();
        power.setId(vo.getId());
        if (powerValue != null) {
            power.setGroupId(powerValue.getGroupId());
        }
        power.setProjectName(vo.getProjectName());
        power.setSettleMonth(vo.getSettleMonth());
        power.setMeterMan(vo.getMeterMan());
        power.setBiCycle(vo.getBiCycle());
        power.setChecker(vo.getChecker());
        power.setPowerAll(vo.getPowerAll());
        power.setPowerSelf(vo.getPowerSelf());
        power.setPowerUp(vo.getPowerUp());
        power.setConsumeRatio(vo.getConsumeRatio());
        power.setPowerJ(vo.getPowerJ());
        power.setPowerF(vo.getPowerF());
        power.setPowerP(vo.getPowerP());
        power.setPowerG(vo.getPowerG());
        power.setPowerSigle(vo.getPowerSigle());
        power.setOrigPriceJ(vo.getOrigPriceJ());
        power.setOrigPriceF(vo.getOrigPriceF());
        power.setOrigPriceG(vo.getOrigPriceG());
        power.setOrigPriceP(vo.getOrigPriceP());
        power.setOrigPriceSigle(vo.getOrigPriceSigle());
        power.setDiscountPriceJ(vo.getDiscountPriceJ());
        power.setDiscountPriceF(vo.getDiscountPriceF());
        power.setDiscountPriceP(vo.getDiscountPriceP());
        power.setDiscountPriceG(vo.getDiscountPriceG());
        power.setDiscountPriceSigle(vo.getDiscountPriceSigle());
        power.setFeeJ(vo.getFeeJ());
        power.setFeeF(vo.getFeeF());
        power.setFeeP(vo.getFeeP());
        power.setFeeG(vo.getFeeG());
        power.setFeeSigle(vo.getFeeSigle());
        power.setReceivableFee(vo.getReceivableFee());
        power.setCreateTime(powerValue.getCreateTime());
        power.setCreator(vo.getCreator());
        powerMapper.updateByPrimaryKey(power);
    }

    @Override
    public Power selectById(DetailVo vo) {
        Power power = powerMapper.selectById(vo);
        return power;
    }

    @Override
    public List<Power> selectAll(Integer groupId, String settleMonth) {
        List<Power> powerList = powerMapper.selectAll(groupId, settleMonth, null);
        return powerList;
    }

    @Override
    public void batchDeletes(List<Integer> idList) {
        powerMapper.batchDeletes(idList);
    }
}
