package yangtz.cs.liu.campus.service.impl.schoolbudget;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.core.annotation.DeptFilter;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.mapper.SysDeptMapper;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import yangtz.cs.liu.campus.domain.purchase.SchoolPurchase;
import yangtz.cs.liu.campus.domain.schoolAtt.SchoolAtt;
import yangtz.cs.liu.campus.domain.schoolbudget.SchoolBudget;
import yangtz.cs.liu.campus.domain.schoolbudget.SchoolBudgetDetails;
import yangtz.cs.liu.campus.domain.schoolgrade.SchoolGrade;
import yangtz.cs.liu.campus.mapper.purchase.SchoolPurchaseMapper;
import yangtz.cs.liu.campus.mapper.schoolbudget.SchoolBudgetDetailsMapper;
import yangtz.cs.liu.campus.mapper.schoolbudget.SchoolBudgetMapper;
import yangtz.cs.liu.campus.service.schoolbudget.ISchoolBudgetService;
import yangtz.cs.liu.campus.vo.purchase.SchoolPurchaseVo;
import yangtz.cs.liu.campus.vo.schoolAtt.SchoolAttVO;
import yangtz.cs.liu.campus.vo.schoolbudget.SchoolBudgetVo;
import yangtz.cs.liu.campus.vo.teacher.SchoolTeacherVO;

import static com.baomidou.mybatisplus.core.toolkit.ObjectUtils.isNotNull;
import static com.baomidou.mybatisplus.core.toolkit.ObjectUtils.isNull;
import static com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank;
import static yangtz.cs.liu.campus.constant.EmployeeType.EMPLOYEE;
import static yangtz.cs.liu.campus.constant.GradeConstant.NEWTERM;


/**
 * 预算项目Service业务层处理
 *
 * @author wengxiu
 * @date 2023-01-05
 */
@Service
public class SchoolBudgetServiceImpl extends ServiceImpl<SchoolBudgetMapper, SchoolBudget> implements ISchoolBudgetService
{
    @Autowired
    private SchoolBudgetMapper schoolBudgetMapper;

    @Autowired
    private SchoolBudgetDetailsMapper schoolBudgetDetailsMapper;

    @Autowired
    private SysDeptMapper deptMapper;

    @Autowired
    private SchoolPurchaseMapper schoolPurchaseMapper;

    /**
     * 查询预算项目
     *
     * @param id 预算项目主键
     * @return 预算项目
     */
    @Override
    public SchoolBudgetVo selectSchoolBudgetById(Long id)
    {
        return schoolBudgetMapper.selectSchoolBudgetById(id);
    }

    /**
     * 查询预算项目列表
     *
     * @param schoolBudget 预算项目
     * @return 预算项目
     */
    @Override
    public List<SchoolBudgetVo> selectSchoolBudgetList(SchoolBudget schoolBudget)
    {
        List<SchoolBudgetVo> list = schoolBudgetMapper.selectSchoolBudgetList(schoolBudget);
        //查出对应明细
        for (SchoolBudgetVo schoolBudgetVo:list) {
            LambdaQueryWrapper<SchoolBudgetDetails> lqw = new LambdaQueryWrapper<>();
            lqw
                    .eq(SchoolBudgetDetails::getBudgetId,schoolBudgetVo.getId())
                    .orderByDesc(SchoolBudgetDetails::getCreateTime);
            List<SchoolBudgetDetails> details = schoolBudgetDetailsMapper.selectList(lqw);
            schoolBudgetVo.setSchoolBudgetDetailsList(details);
        }
        return list;
    }

    //查全部
    @Override
    public List<SchoolBudgetVo> getList(SchoolBudget schoolBudget) {
        //List<SchoolBudgetVo> list = new ArrayList<>();
       /* LambdaQueryWrapper<SchoolBudget> lqw = new LambdaQueryWrapper<>();
        lqw
                .eq(isNotNull(schoolBudget.getBudgetYear()),SchoolBudget::getBudgetYear,schoolBudget.getBudgetYear())
                .like(isNotNull(schoolBudget.getBudgetName()),SchoolBudget::getBudgetName,schoolBudget.getBudgetName())
                .eq(isNotNull(schoolBudget.getDeptId()),SchoolBudget::getDeptId,schoolBudget.getDeptId())
                .eq(isNotBlank(schoolBudget.getIsGov()),SchoolBudget::getIsGov,schoolBudget.getIsGov())
                .orderByDesc(SchoolBudget::getCreateTime)
                ;
        List<SchoolBudget> budgets = schoolBudgetMapper.selectList(lqw);*/
        List<SchoolBudgetVo> budgets = schoolBudgetMapper.selectSchoolBudgetList(schoolBudget);
       if (StringUtils.isNull(budgets) || budgets.size() == 0){
            return new ArrayList<>();
        }
        //查子表数据
        for(SchoolBudgetVo budget : budgets){
           /* SchoolBudgetVo vo = new SchoolBudgetVo();
            BeanUtils.copyProperties(budget,vo);*/
            LambdaQueryWrapper<SchoolBudgetDetails> lambda = new LambdaQueryWrapper<>();
            lambda
                    .eq(SchoolBudgetDetails::getBudgetId,budget.getId())
                    .orderByDesc(SchoolBudgetDetails::getCreateTime);
            List<SchoolBudgetDetails> details = schoolBudgetDetailsMapper.selectList(lambda);
           /* vo.setSchoolBudgetDetailsList(details);
            list.add(vo);*/
           budget.setSchoolBudgetDetailsList(details);
            SchoolPurchase schoolPurchase1 = new SchoolPurchase();
            schoolPurchase1.setBudgetId(budget.getId());
            List<SchoolPurchaseVo> schoolPurchaseVos = schoolPurchaseMapper.selectPurchaseList(schoolPurchase1);
            BigDecimal bigDecimal = new BigDecimal("0");
            for (SchoolPurchaseVo schoolPurchase : schoolPurchaseVos) {
                BigDecimal add = bigDecimal.add(schoolPurchase.getSjPurchaseMoney());
                bigDecimal = add;
            }
            BigDecimal bigDecimal1 = new BigDecimal("10000");
            BigDecimal amountSpent = bigDecimal.divide(bigDecimal1);
            budget.setAmountSpent(amountSpent);
            //计算可用余额(单位为元)
            budget.setKyye((budget.getGiveMoney().subtract(amountSpent)).multiply(new BigDecimal("10000")));
        }
        return budgets;
    }

    //按主表id查详情
    @Override
    public SchoolBudgetVo queryInfo(Long id) {
        SchoolBudgetVo vo = new SchoolBudgetVo();
        SchoolBudget budget = schoolBudgetMapper.selectById(id);
        BeanUtils.copyProperties(budget,vo);
        LambdaQueryWrapper<SchoolBudgetDetails> lambda = new LambdaQueryWrapper<>();
        lambda
                .eq(SchoolBudgetDetails::getBudgetId,budget.getId())
                .orderByDesc(SchoolBudgetDetails::getCreateTime);
        List<SchoolBudgetDetails> details = schoolBudgetDetailsMapper.selectList(lambda);
        vo.setSchoolBudgetDetailsList(details);
        return vo;
    }

    @Override
    public int insertSchoolBudget(SchoolBudgetVo schoolBudgetVo) {
        schoolBudgetVo.setCreateTime(DateUtils.getNowDate());
        int rows = schoolBudgetMapper.insertSchoolBudget(schoolBudgetVo);
        //新增子表信息
        insertSchoolBudgetDetails(schoolBudgetVo);
        return rows;
    }

    @Override
    public int updateSchoolBudget(SchoolBudgetVo schoolBudgetVo) {

        //先删除之前的
        LambdaQueryWrapper<SchoolBudgetDetails> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SchoolBudgetDetails::getBudgetId,schoolBudgetVo.getId());
        schoolBudgetDetailsMapper.delete(lqw);

        //重新插入数据
        insertSchoolBudgetDetails(schoolBudgetVo);

        SchoolBudget schoolBudget = new SchoolBudget();
        BeanUtils.copyProperties(schoolBudgetVo,schoolBudget);
        schoolBudget.update();
        return schoolBudgetMapper.updateById(schoolBudget);
    }

    @Override
    public Boolean checkIsExist(SchoolBudgetVo schoolBudget) {
        LambdaQueryWrapper<SchoolBudget> name = new LambdaQueryWrapper<>();
        name.eq(SchoolBudget::getBudgetName,schoolBudget.getBudgetName());

        SchoolBudget duty = schoolBudgetMapper.selectOne(name);

        return StringUtils.isNotNull(duty);
    }

    @Override
    public List<SchoolBudgetVo> selectExportList(SchoolBudget schoolBudget) {
        LambdaQueryWrapper<SchoolBudget> lqw = new LambdaQueryWrapper<>();
        lqw
                .eq(isNotNull(schoolBudget.getBudgetYear()),SchoolBudget::getBudgetYear,schoolBudget.getBudgetYear())
                .like(isNotNull(schoolBudget.getBudgetName()),SchoolBudget::getBudgetName,schoolBudget.getBudgetName())
                .eq(isNotNull(schoolBudget.getDeptId()),SchoolBudget::getDeptId,schoolBudget.getDeptId())
                .eq(isNotNull(schoolBudget.getIsGov()),SchoolBudget::getIsGov,schoolBudget.getIsGov())
                .orderByDesc(SchoolBudget::getCreateTime)
                ;
        List<SchoolBudget> budgets = schoolBudgetMapper.selectList(lqw);
        if(isNull(budgets) || budgets.size() == 0){
            return new ArrayList<>();
        }
        List<SchoolBudgetVo> list = new ArrayList<>();
        for(SchoolBudget budget : budgets){
            SchoolBudgetVo vo = new SchoolBudgetVo();
            BeanUtils.copyProperties(budget,vo);
            LambdaQueryWrapper<SchoolBudgetDetails> det = new LambdaQueryWrapper<>();
            det.eq(SchoolBudgetDetails::getBudgetId,budget.getId()).orderByDesc(SchoolBudgetDetails::getCreateTime);
            List<SchoolBudgetDetails> detailsList = schoolBudgetDetailsMapper.selectList(det);
            vo.setSchoolBudgetDetailsList(detailsList);
            list.add(vo);
        }
        return list;
    }

    @Override
    public String importSchoolBudgetVoList(List<SchoolBudgetVo> list) {
        // 准备记录日志数据
        int successNum = 0;
        StringBuilder successMsg = new StringBuilder();
        // 遍历并逐个导入
        for (SchoolBudgetVo schoolBudgetVo : list) {
            try {
                schoolBudgetVo.insert();
                schoolBudgetMapper.insertSchoolBudget(schoolBudgetVo);
                if(StringUtils.isNotNull(schoolBudgetVo.getSchoolBudgetDetailsList()) ||
                        schoolBudgetVo.getSchoolBudgetDetailsList().size() > 0){
                    for (SchoolBudgetDetails schoolBudgetDetails : schoolBudgetVo.getSchoolBudgetDetailsList()) {
                        schoolBudgetDetails.setBudgetId(schoolBudgetVo.getId());
                        schoolBudgetDetails.insert();
                        schoolBudgetDetailsMapper.insert(schoolBudgetDetails);
                    }
                }
                successNum++;
                successMsg.append("<br/>" + successNum + "数据" + " 导入成功");
            } catch (Exception e) {
                throw new ServiceException("导入失败");
            }
        }
        successMsg.insert(0, "恭喜您，数据已导入成功！共有 " + successNum + " 条，数据如下：");
        return successMsg.toString();
    }


    @Override
    public void checkImport(List<SchoolBudgetVo> list) {
        //检验是否为空
        if (StringUtils.isNull(list) || list.size() == 0) {
            throw new ServiceException("导入数据不能为空");
        }

        // 准备记录日志数据
        int failureNum = 0;
        StringBuilder failureMsg = new StringBuilder();
        for (SchoolBudgetVo schoolBudgetVo : list) {
            if (StringUtils.isEmpty(schoolBudgetVo.getBudgetYear())) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、预算年度为空,请您重新输入! ");
            } else if (StringUtils.isEmpty(schoolBudgetVo.getDeptName())) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、科室为空,请您重新输入! ");
            } else if (StringUtils.isEmpty(schoolBudgetVo.getBudgetName())) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、项目名称为空,请您重新输入! ");
            } /*else if (StringUtils.isNull(schoolBudgetVo.getGiveMoney())) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、批复总额为空,请您重新输入! ");
            }*/ else if (StringUtils.isNull(schoolBudgetVo.getIsGov())) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、是否政府采购为空,请您重新输入! ");
            } else {
                //获取科室Id
                SysDept dept = deptMapper.selectDeptByDeptName(schoolBudgetVo.getDeptName());
                if(StringUtils.isNull(dept)){
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、科室名称不存在,请您重新输入! ");
                }else{
                    schoolBudgetVo.setDeptId(dept.getDeptId());
                }

                //验证批复总额
                if(StringUtils.isNull(schoolBudgetVo.getSchoolBudgetDetailsList()) ||
                        schoolBudgetVo.getSchoolBudgetDetailsList().size() == 0){
                    schoolBudgetVo.setGiveMoney(BigDecimal.ZERO);
                }else{
                    //设置为正确的批复总额
                    BigDecimal giveMoney = BigDecimal.ZERO;
                   /* giveMoney = schoolBudgetVo.getSchoolBudgetDetailsList()
                            .stream()
                            .map(SchoolBudgetDetails::getMoneyDetailed)
                            .reduce(BigDecimal::add)
                            .get();
*/
                    for(SchoolBudgetDetails details : schoolBudgetVo.getSchoolBudgetDetailsList()){
                        giveMoney = giveMoney.add(details.getMoneyDetailed());
                    }
                    schoolBudgetVo.setGiveMoney(giveMoney);
                }
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
    }


    /**
     * 新增子表信息
     */
    public void insertSchoolBudgetDetails(SchoolBudgetVo schoolBudget)
    {
        List<SchoolBudgetDetails> schoolBudgetDetailsList = schoolBudget.getSchoolBudgetDetailsList();
        Long id = schoolBudget.getId();
        if (StringUtils.isNotNull(schoolBudgetDetailsList))
        {
            for (SchoolBudgetDetails schoolBudgetDetails : schoolBudgetDetailsList)
            {
                schoolBudgetDetails.setBudgetId(id);
                schoolBudgetDetails.insert();
                schoolBudgetDetailsMapper.insert(schoolBudgetDetails);
            }
        }
    }
}
