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

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tofly.common.core.util.Date8Util;
import com.tofly.common.core.util.DateUtil;
import com.tofly.common.oauth.exception.ToflyDeniedException;
import com.tofly.common.oauth.util.SecurityUtils;
import com.tofly.xrtygis.custom.mapper.FixedMapper;
import com.tofly.xrtygis.custom.service.CustomPriceService;
import com.tofly.xrtygis.custom.util.CommonMethod;
import com.tofly.xrtygis.entity.Costrlfixed;
import com.tofly.xrtygis.entity.Costrlprice;
import com.tofly.xrtygis.entity.Costrlwater;
import com.tofly.xrtygis.service.CostrlfixedService;
import com.tofly.xrtygis.service.CostrlpriceService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author 陈浩
 * @date 2021-3-24
 */
@Service
@AllArgsConstructor
public class CustomPriceServiceImpl implements CustomPriceService {

    private final CostrlpriceService costrlpriceService;
    private final CostrlfixedService costrlfixedService;
    private final FixedMapper fixedMapper;

    /**
     * 添加指标单价
     *
     * @param costrlprice 指标单价信息表
     * @return true or false
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean insertPrice(Costrlprice costrlprice) {
        //查询是否存在最新单价
        Costrlprice price = costrlpriceService.getOne(Wrappers.<Costrlprice>lambdaQuery()
                .select(Costrlprice::getId)
                .eq(Costrlprice::getYear, costrlprice.getYear())
                .eq(Costrlprice::getIsnew, "1"));
        //有的话将当前单价状态修改为旧
        if (null != price){
            costrlpriceService.update(Wrappers.<Costrlprice>lambdaUpdate()
                    .eq(Costrlprice::getId,price.getId())
                    .set(Costrlprice::getIsnew,"0"));
        }
        costrlprice.setIsnew("1");
        return costrlpriceService.save(costrlprice);
    }

    /**
     * 删除指标单价
     *
     * @param ids 指标id
     * @return true or false
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deletePrice(String ids) {
        List<String> list = Arrays.asList(ids.split(","));

        list.forEach(id->{
            Costrlprice price = costrlpriceService.getById(id);
            if (price != null){
                if (Integer.parseInt(price.getYear()) < Date8Util.getYear()){
                    throw new ToflyDeniedException(price.getYear() + "年计划已过时，不允许删除");
                }
                if (Integer.parseInt(price.getYear()) == Date8Util.getYear()){
                    List<Costrlprice> list1 = costrlpriceService.list(Wrappers.<Costrlprice>lambdaQuery()
                            .eq(Costrlprice::getYear, price.getYear()));
                    if (null != list1 && list1.size() > 1){
                        throw new ToflyDeniedException(price.getYear() + "年份存在历史记录不允许删除");
                    }
                }
            }
        });
        return costrlpriceService.removeByIds(list);
    }

    /**
     * 修改指标单价
     *
     * @param costrlprice 指标单价信息
     * @return true or false
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updatePrice(Costrlprice costrlprice) {
        //首先查询出要修改的信息
        Costrlprice price = costrlpriceService.getById(costrlprice.getId());
        price.setId(0L);
        price.setIsnew("0");
        //将该条记录作为旧数据添加
        costrlpriceService.save(price);

        costrlprice.setCreateTime(new Date());
        costrlprice.setCreateUser(SecurityUtils.getUserId());
        costrlpriceService.updateById(costrlprice);

        if (costrlprice.getDlddjOne() != null || costrlprice.getDlddjTwo() != null || costrlprice.getWnzydj() != null){
            //最新单价消息
            Costrlprice ctp = costrlpriceService.getById(costrlprice.getId());
            //修改财务填报和非财务填报单变
            updateFixed(ctp,"0");
            updateFixed(ctp,"1");
        }
        return true;
    }

    /**
     * 查看历史指标单价
     *
     * @param page page
     * @param year year
     * @return true of false
     */
    @Override
    public Page viewPrice(Page page, String year, String start,String end) {
        return fixedMapper.getPriceHistory(page,year,start,end);
    }

    /**
     * 查询最新单价
     *
     * @param year 年份
     * @return list
     */
    @Override
    public Page viewNewPrice(Page page,String year) {
        return costrlpriceService.page(page,Wrappers.<Costrlprice>lambdaQuery()
                .eq(year != null,Costrlprice::getYear,year)
                .eq(Costrlprice::getIsnew,"1")
                .orderByAsc(Costrlprice::getYear));
    }


    /* *************************************公共方法*********************************** */

    private void updateFixed(Costrlprice price,String mark){
        List<Costrlfixed> fixeds = costrlfixedService.list(Wrappers.<Costrlfixed>lambdaQuery()
                .eq(Costrlfixed::getMark,mark)
                .likeRight(Costrlfixed::getUpDate,price.getYear()));
        if (!fixeds.isEmpty()){
            for (Costrlfixed fixed : fixeds) {
                Costrlwater water = fixedMapper.selectWaterInfo(DateUtil.getDateFormat(fixed.getUpDate(), "yyyy-MM-dd"), "0");
                costrlfixedService.updateById(CommonMethod.countFixed(fixed, price, water));
            }
        }
    }
}
