package com.ruoyi.buyerapi.service.impl;

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

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.buyerapi.domain.*;
import com.ruoyi.buyerapi.mapper.BuyerProjectMapper;
import com.ruoyi.buyerapi.service.IBuyerDeptDeviceService;
import com.ruoyi.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.buyerapi.mapper.BuyerDeviceWorkhourMapper;
import com.ruoyi.buyerapi.domain.BuyerDeviceWorkhour;
import com.ruoyi.buyerapi.service.IBuyerDeviceWorkhourService;

/**
 * 设备工时分摊记录Service业务层处理
 *
 * @author ruoyi
 * @date 2022-09-22
 */
@Service
public class BuyerDeviceWorkhourServiceImpl implements IBuyerDeviceWorkhourService
{
    @Autowired
    private BuyerDeviceWorkhourMapper buyerDeviceWorkhourMapper;

    @Autowired
    private IBuyerDeptDeviceService buyerDeptDeviceService;

    @Autowired
    private BuyerProjectMapper buyerProjectMapper;

    /**
     * 查询设备工时分摊记录
     *
     * @param id 设备工时分摊记录主键
     * @return 设备工时分摊记录
     */
    @Override
    public BuyerDeviceWorkhour selectBuyerDeviceWorkhourById(String id)
    {
        return buyerDeviceWorkhourMapper.selectBuyerDeviceWorkhourById(id);
    }

    /**
     * 查询设备工时分摊记录列表
     *
     * @param buyerDeviceWorkhour 设备工时分摊记录
     * @return 设备工时分摊记录
     */
    @Override
    public List<BuyerDeviceWorkhour> selectBuyerDeviceWorkhourList(BuyerDeviceWorkhour buyerDeviceWorkhour)
    {
        return buyerDeviceWorkhourMapper.selectBuyerDeviceWorkhourList(buyerDeviceWorkhour);
    }

    /**
     * 新增设备工时分摊记录
     *
     * @param buyerDeviceWorkhour 设备工时分摊记录
     * @return 结果
     */
    @Override
    public int insertBuyerDeviceWorkhour(BuyerDeviceWorkhour buyerDeviceWorkhour)
    {
        buyerDeviceWorkhour.setCreateTime(DateUtils.getNowDate());
        return buyerDeviceWorkhourMapper.insertBuyerDeviceWorkhour(buyerDeviceWorkhour);
    }

    /**
     * 修改设备工时分摊记录
     *
     * @param buyerDeviceWorkhour 设备工时分摊记录
     * @return 结果
     */
    @Override
    public int updateBuyerDeviceWorkhour(BuyerDeviceWorkhour buyerDeviceWorkhour)
    {
        buyerDeviceWorkhour.setUpdateTime(DateUtils.getNowDate());
        return buyerDeviceWorkhourMapper.updateBuyerDeviceWorkhour(buyerDeviceWorkhour);
    }

    /**
     * 批量删除设备工时分摊记录
     *
     * @param ids 需要删除的设备工时分摊记录主键
     * @return 结果
     */
    @Override
    public int deleteBuyerDeviceWorkhourByIds(String[] ids)
    {
        return buyerDeviceWorkhourMapper.deleteBuyerDeviceWorkhourByIds(ids);
    }

    /**
     * 删除设备工时分摊记录信息
     *
     * @param id 设备工时分摊记录主键
     * @return 结果
     */
    @Override
    public int deleteBuyerDeviceWorkhourById(String id)
    {
        return buyerDeviceWorkhourMapper.deleteBuyerDeviceWorkhourById(id);
    }

    @Override
    public int deleteBuyerDeviceWorkhour(BuyerDeviceWorkhour buyerDeviceWorkhour) {
        return buyerDeviceWorkhourMapper.deleteBuyerDeviceWorkhour(buyerDeviceWorkhour);
    }

    @Override
    public List<BuyerDeviceWorkhourByProject> listGrroupProject(BuyerDeviceWorkhourByProject buyerDeviceWorkhourByProject) {
        return buyerDeviceWorkhourMapper.listGrroupProject(buyerDeviceWorkhourByProject);
    }

    @Override
    public List<BuyerDeviceWorkhourByProject> listGrroupYearMonth(BuyerDeviceWorkhourByProject buyerDeviceWorkhourByProject) {
        return buyerDeviceWorkhourMapper.listGrroupYearMonth(buyerDeviceWorkhourByProject);
    }

    @Override
    public List<Map<String, Object>> listForYearMonth(BuyerDeviceWorkhour buyerDeviceWorkhour) {
        List<Map<String, Object>> list = new ArrayList<>();
        // 总计
        Map<String, Object> totalMap = new LinkedHashMap<>();
        // 获取当月的所有设备
        List<BuyerDeviceWorkhour> buyerDeviceWorkhours = buyerDeviceWorkhourMapper.selectBuyerDeviceWorkhourList(buyerDeviceWorkhour);
        // 根据设备code分组
        Map<String,List<BuyerDeviceWorkhour>> mapListOfName = buyerDeviceWorkhours.stream().collect(Collectors.groupingBy(BuyerDeviceWorkhour::getCode));
        Object[] keys = mapListOfName.keySet().toArray();
        for(int i = 0; i < keys.length; i++){
            BuyerDeviceWorkhour deviceWorkhour = mapListOfName.get(keys[i]).get(0);
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("序号", i + 1);
            totalMap.put("序号", "合计");
            map.put("设备名称", deviceWorkhour.getName());
            map.put("设备编号", deviceWorkhour.getCode());
            totalMap.put("设备名称", "");
            totalMap.put("设备编号", "");
            // 获取设备信息
            BuyerDeptDevice _buyerDeptDevice = new BuyerDeptDevice();
            Map params = new HashMap<>();
            params.put("allcode", deviceWorkhour.getCode());
            _buyerDeptDevice.setParams(params);
            List<BuyerDeptDevice> devices = buyerDeptDeviceService.selectBuyerDeptDeviceList(_buyerDeptDevice);
            if(null != devices && devices.size() > 0){
                map.put("原值", devices.get(0).getOriginalValue());
                map.put("残值率", devices.get(0).getCrippleValueRate());
                map.put("折旧年限", devices.get(0).getDepreciableLife());
            }
            totalMap.put("原值", "");
            totalMap.put("残值率", "");
            totalMap.put("折旧年限", "");

            // 遍历查询项目情况
            // 统计工时
            Map<String,List<BuyerDeviceWorkhour>> mapListOfProject = mapListOfName.get(keys[i]).stream().collect(Collectors.groupingBy(BuyerDeviceWorkhour::getProjectId));
            Object[] projectKeys = mapListOfProject.keySet().toArray();
            for(int j = 0; j < projectKeys.length; j++){
                BigDecimal totalWorkOfProject = new BigDecimal(0);
                BuyerProject project = buyerProjectMapper.selectBuyerProjectById(projectKeys[j] + "");
                List<BuyerDeviceWorkhour> listOfProject = mapListOfProject.get(projectKeys[j]);
                // 叠加项目中的值
                for(BuyerDeviceWorkhour workhourOfProject : listOfProject){
                    totalWorkOfProject = totalWorkOfProject.add(null == workhourOfProject.getCost() ? BigDecimal.valueOf(0) : workhourOfProject.getCost());
                }
                if(null != project) {
                    map.put("“" + project.getName() + "”工时", totalWorkOfProject);
                    totalMap.put("“" + project.getName() + "”工时", totalMap.containsKey("“" + project.getName() + "”工时") ?
                            ((BigDecimal) totalMap.get("“" + project.getName() + "”工时")).add(totalWorkOfProject) :
                            totalWorkOfProject);
                    map.put("工时合计", map.containsKey("工时合计") ?
                            ((BigDecimal) map.get("工时合计")).add(totalWorkOfProject) :
                            totalWorkOfProject);
                    totalMap.put("工时合计", totalMap.containsKey("工时合计") ?
                            ((BigDecimal) totalMap.get("工时合计")).add(totalWorkOfProject) :
                            totalWorkOfProject);
                }
            }

            // 统计工时
            for(int j = 0; j < projectKeys.length; j++){
                BuyerProject project = buyerProjectMapper.selectBuyerProjectById(projectKeys[j] + "");
                // 判断是否满足：已提足折旧仍使用设备
                int isOld = -1;
                if(null != devices && devices.size() > 0 && null != devices.get(0).getBuyDate() && null != devices.get(0).getDepreciableLife()) {
                    Date vaildDate = DateUtil.beginOfMonth(DateUtil.offset(devices.get(0).getBuyDate(), DateField.YEAR, devices.get(0).getDepreciableLife())
                            .offset(DateField.MONTH, 1));
                    isOld = DateUtil.compare(DateUtil.parseDate(DateUtil.format(new Date(), "yyyy-MM-dd")), vaildDate);
                }
                if(isOld >= 0){
                    if(null != project) {
                        map.put("“" + project.getName() + "”折旧金额", "已提足折旧仍使用设备");
                        totalMap.put("“" + project.getName() + "”折旧金额", totalMap.containsKey("“" + project.getName() + "”折旧金额") ?
                                ((BigDecimal) totalMap.get("“" + project.getName() + "”折旧金额")).add(BigDecimal.valueOf(0)) :
                                BigDecimal.valueOf(0));
                        map.put("项目折旧金额合计", map.containsKey("项目折旧金额合计") ?
                                ((BigDecimal) map.get("项目折旧金额合计")).add(BigDecimal.valueOf(0)) :
                                BigDecimal.valueOf(0));
                        totalMap.put("项目折旧金额合计", totalMap.containsKey("项目折旧金额合计") ?
                                ((BigDecimal) totalMap.get("项目折旧金额合计")).add(BigDecimal.valueOf(0)) :
                                BigDecimal.valueOf(0));
                    }
                }else{
                    BigDecimal totalCostOfProject = new BigDecimal(0);
                    List<BuyerDeviceWorkhour> listOfProject = mapListOfProject.get(projectKeys[j]);
                    for(BuyerDeviceWorkhour workhourOfProject : listOfProject){
                        if(null != workhourOfProject.getOneCost()) {
                            totalCostOfProject = totalCostOfProject.add(workhourOfProject.getOneCost());
                        }
                    }
                    if(null != project) {
                        // 计算折旧金额
                        map.put("“" + project.getName() + "”折旧金额", totalCostOfProject);
                        totalMap.put("“" + project.getName() + "”折旧金额", totalMap.containsKey("“" + project.getName() + "”折旧金额") ?
                                ((BigDecimal) totalMap.get("“" + project.getName() + "”折旧金额")).add(totalCostOfProject) :
                                totalCostOfProject);
                        map.put("项目折旧金额合计", map.containsKey("项目折旧金额合计") ?
                                ((BigDecimal) map.get("项目折旧金额合计")).add(totalCostOfProject) :
                                totalCostOfProject);
                        totalMap.put("项目折旧金额合计", totalMap.containsKey("项目折旧金额合计") ?
                                ((BigDecimal) totalMap.get("项目折旧金额合计")).add(totalCostOfProject) :
                                totalCostOfProject);
                    }
                }
            }
            list.add(map);
        }
        list.add(totalMap);
        return list;
    }

    @Override
    public List<BuyerDeviceWorkhourByProject> listByProjectId(String projectId) {
        return buyerDeviceWorkhourMapper.listByProjectId(projectId);
    }

    /**
     * 查询员工工时分摊记录列表
     *
     * @return 员工工时分摊记录
     */
    @Override
    public List<String> workDatelist(BuyerDeviceWorkhour buyerDeviceWorkhour)
    {
        return buyerDeviceWorkhourMapper.workDatelist(buyerDeviceWorkhour);
    }
}
