/**
 * Copyright (c) 2018-2099, Chill Zhuang 庄骞 (bladejava@qq.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.xiaoniu.subsystem.business.service.impl;


import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaoniu.common.core.exception.ServiceException;
import com.xiaoniu.common.core.utils.StringUtils;
import com.xiaoniu.common.core.utils.bean.BeanValidators;
import com.xiaoniu.subsystem.business.domain.Budget;
import com.xiaoniu.subsystem.business.domain.Expense;
import com.xiaoniu.subsystem.business.domain.vo.BudgetVO;
import com.xiaoniu.subsystem.business.mapper.BudgetMapper;
import com.xiaoniu.subsystem.business.mapper.ExpenseMapper;
import com.xiaoniu.subsystem.business.service.IBudgetService;
import jakarta.annotation.Resource;
import jakarta.validation.Validator;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 预算管理表 服务实现类
 *
 * @author sst
 * @since 2024-11-26
 */
@Service
public class BudgetServiceImpl extends ServiceImpl<BudgetMapper, Budget> implements IBudgetService {

    protected final Validator validator;
    @Resource
    protected ExpenseMapper expenseMapper;


    public BudgetServiceImpl(Validator validator) {
        this.validator = validator;
    }

    @Override
    public IPage<BudgetVO> selectBudgetPage(IPage<BudgetVO> page, BudgetVO budget) {
        return page.setRecords(baseMapper.selectBudgetPage(page, budget));
    }

    @Override
    public String importData(List<Budget> list, Boolean isUpdateSupport, Long userId) {
        if (CollectionUtils.isEmpty(list)) {
            throw new ServiceException("导入预算管理信息数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (Budget d : list) {
            try {
                Expense expense = expenseMapper.selectOne(new LambdaQueryWrapper<Expense>()
                        .eq(Expense::getTrainingTime, d.getTrainingTime())
                        .eq(Expense::getYear, d.getYear())
                        .eq(Expense::getFlightName, d.getFlightName()));
                if (null != expense) {
                    expenseMapper.updateById(expense.setOrganBudgetedAmount(d.getBudgetedAmount()));
                }
                // 验证是否存在这个数据
                Budget u = baseMapper.selectOne(new LambdaQueryWrapper<Budget>()
                        .eq(Budget::getFlightName, d.getFlightName())
                        .eq(Budget::getTissueUnitName, d.getTissueUnitName())
                        .eq(Budget::getYear, d.getYear()));
                if (StringUtils.isNull(u)) {
                    BeanValidators.validateWithException(validator, d);
                    d.setCreateUser(userId);
                    this.save(d);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、" + d.getTissueUnitName() + "单位，"
                            + d.getYear() + " 年度,专业 " + d.getFlightName() + "导入成功");
                } else if (isUpdateSupport) {
                    BeanValidators.validateWithException(validator, d);
                    d.setUpdateUser(userId);
                    d.setBudgetId(u.getBudgetId());
                    this.updateById(d);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、" + d.getTissueUnitName() + "单位，"
                            + d.getYear() + " 年度，专业 " + d.getFlightName() + "更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、" + d.getTissueUnitName()
                            + "单位，" + d.getYear() + " 年度，专业 " + d.getFlightName() + "已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、" + d.getTissueUnitName()
                        + "单位，" + d.getYear() + " 年度，专业 " + d.getFlightName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            if (10 < successNum){
                successMsg = new StringBuilder();
                successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条.");
            }else{
                successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
            }
        }
        return successMsg.toString();
    }

}
