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

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tofly.common.core.util.DateUtil;
import com.tofly.common.ftp.config.FtpUtil;
import com.tofly.common.oauth.exception.ToflyDeniedException;
import com.tofly.xrtygis.custom.entity.vo.WaterVo;
import com.tofly.xrtygis.custom.mapper.FixedMapper;
import com.tofly.xrtygis.custom.mapper.WaterCostMapper;
import com.tofly.xrtygis.custom.service.CustomWaterService;
import com.tofly.xrtygis.custom.util.CommonMethod;
import com.tofly.xrtygis.entity.*;
import com.tofly.xrtygis.service.*;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 陈浩
 * @date 2021-3-23
 */
@Service
@AllArgsConstructor
public class CustomWaterServiceImpl implements CustomWaterService {

    private final static String TABLE_NAME = "TF_YWPN_COSTRLWATER_W";
    private final static String TABLE_UNIT = "TF_YWPN_COSTRLUNIT_W";

    private final CostrlwaterService costrlwaterService;
    private final CostrlunitService costrlunitService;
    private final WaterCostMapper waterCostMapper;
    private final CostrlpriceService costrlpriceService;
    private final FixedMapper fixedMapper;
    private final CostrlfixedService costrlfixedService;
    private final CostnotesService costnotesService;
    private final FileService fileService;


    /**
     * 日填报
     *
     * @param water 实际制水指标填报信息表
     * @return true or false
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean insertWater(Costrlwater water) {

        if ("1".equals(water.getMark())) {
            WaterVo waterVo = waterCostMapper.financeByMonth(DateUtil.getDateFormat(water.getUpDate(), "yyyy-MM"));
            if (waterVo != null) {
                throw new ToflyDeniedException("本月已进行财务填报");
            }
        } else {
            Long infoByDay = waterCostMapper.getInfoByDay(TABLE_NAME, DateUtil.getDateFormat(water.getUpDate(), "yyyy-MM-dd"), "0");
            if (null != infoByDay) {
                throw new ToflyDeniedException("该天已进行非财务填报");
            }
        }
        Costrlwater costrlwater = CommonMethod.calWater(water);

        return costrlwaterService.save(costrlwater);
    }

    /**
     * 删除日填报制水指标
     *
     * @param id 删除多个指标
     * @return boolean
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteWater(String id) {

        List<String> idList = Arrays.asList(id.split(","));

        for (String waterId : idList) {
            Costnotes costnotes = costnotesService.getOne(Wrappers.<Costnotes>lambdaQuery().eq(Costnotes::getUpid, waterId));
            if (null != costnotes) {
                if (costnotes.getFileids() != null){
                    List<File> list = fileService.list(Wrappers.<File>lambdaQuery()
                            .in(File::getId, Collections.singletonList(costnotes.getFileids())));
                    if (list != null && list.size() > 0){
                        List<String> filePathList = list
                                .stream().map(File::getFilePath).collect(Collectors.toList());
                        if (!filePathList.isEmpty()) {
                            filePathList.forEach(FtpUtil::deleteFile);
                        }
                    }
                }
                costnotesService.removeById(costnotes.getId());
            }
            Costrlwater one = costrlwaterService.getById(waterId);
            if (one != null) {
                Long info = waterCostMapper.getInfoByDay(TABLE_UNIT, DateUtil.getDateFormat(one.getUpDate(), "yyyy-MM-dd"), one.getMark());
                if (info != null) {
                    costrlunitService.removeById(info);
                }
            }
        }
        return costrlwaterService.removeByIds(idList);
    }

    /**
     * 修改制水指标
     *
     * @param costrlwater 制水指标信息表
     * @return true or false
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateWater(Costrlwater costrlwater) {

        Costrlwater water = CommonMethod.calWater(costrlwater);

        if (null == costrlwaterService.getById(costrlwater.getId())) {
            throw new ToflyDeniedException("未查询到该记录");
        }

        costrlwaterService.updateById(water);
        //最新制水指标
        Costrlwater trlWater = costrlwaterService.getById(costrlwater.getId());
        //最新单价
        Costrlprice price = costrlpriceService.getOne(Wrappers.<Costrlprice>lambdaQuery()
                .eq(Costrlprice::getYear, DateUtil.getDateFormat(trlWater.getUpDate(), "yyyy"))
                .eq(Costrlprice::getIsnew, "1"));

        Costrlfixed fixed = fixedMapper.viewDayFixed(DateUtil.getDateFormat(trlWater.getUpDate(), "yyyy-mm-dd"), trlWater.getMark());

        if (null != price && null != fixed) {
            costrlfixedService.updateById(CommonMethod.countFixed(fixed, price, water));
        }
        return true;

    }

    /**
     * 计算实际值、计划值、运行值
     *
     * @return map
     */
    @Override
    public Map<String, Object> waterTotal(String month) {
        Map<String, Object> totalMap = new HashMap<>();

        //预算值
        totalMap.put("budget", waterCostMapper.budgetByMonth(month));

        //财务填报
        totalMap.put("finance", waterCostMapper.financeByMonth(month));

        //实际值统计
        totalMap.put("real", waterCostMapper.realWaterCost(month));

        totalMap.put("realList", waterCostMapper.viewWater(month));

        return totalMap;
    }
}
