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

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.common.core.domain.entity.SchoolTeacher;
import yangtz.cs.liu.campus.domain.teacher.SchoolTeacherWages;
import yangtz.cs.liu.campus.mapper.teacher.SchoolTeacherMapper;
import yangtz.cs.liu.campus.mapper.teacher.SchoolTeacherWagesMapper;
import yangtz.cs.liu.campus.service.teacher.ISchoolTeacherWagesService;
import yangtz.cs.liu.campus.vo.student.SchoolTeacherWagesVO;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import static cn.hutool.core.util.ObjectUtil.isNotNull;
import static cn.hutool.core.util.ObjectUtil.isNull;
import static com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank;

@Service
public class SchoolTeacherWagesServiceImpl extends ServiceImpl<SchoolTeacherWagesMapper, SchoolTeacherWages> implements ISchoolTeacherWagesService {

    @Autowired
    private SchoolTeacherWagesMapper schoolTeacherWagesMapper;

    @Autowired
    private SchoolTeacherMapper schoolTeacherMapper;

    @Override
    public List<SchoolTeacherWages> queryList(SchoolTeacherWages schoolTeacherWages) {
        LambdaQueryWrapper<SchoolTeacherWages> lqw = new LambdaQueryWrapper<>();
        lqw
                .like(isNotBlank(schoolTeacherWages.getTeacherName()), SchoolTeacherWages::getTeacherName, schoolTeacherWages.getTeacherName())
                .eq(isNotNull(schoolTeacherWages.getTeacherId()), SchoolTeacherWages::getTeacherId, schoolTeacherWages.getTeacherId())
                .apply(ObjectUtil.isNotNull(schoolTeacherWages.getParams().get("beginTime")),
                        "date_format(wages_time,'%Y-%m-%d') >= date_format('" + schoolTeacherWages.getParams().get("beginTime") + "','%Y-%m-%d') ")
                .apply(ObjectUtil.isNotNull(schoolTeacherWages.getParams().get("endTime")),
                        "date_format(wages_time,'%Y-%m-%d') <= date_format('" + schoolTeacherWages.getParams().get("endTime") + "','%Y-%m-%d') ")
                .orderByDesc(SchoolTeacherWages::getWagesTime);
        return schoolTeacherWagesMapper.queryList(schoolTeacherWages);
    }

    @Override
    public String importStudent(List<SchoolTeacherWagesVO> dataManagementList, boolean updateSupport, String operName) {
        if (StringUtils.isNull(dataManagementList) || dataManagementList.size() == 0) {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (SchoolTeacherWagesVO teacherWages : dataManagementList) {
            try {
                /*
                 * 验证是否存在这个学生
                 *学号不能重复，姓名不能重复，身份证号不能重复，校园卡不能重复
                 * */
                SchoolTeacherWages schoolTeacherWages = new SchoolTeacherWages();
                BeanUtils.copyProperties(teacherWages, schoolTeacherWages);
                int i = judgIsExit(schoolTeacherWages);
                if (i == 0) {
                    this.save(schoolTeacherWages);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、学生 " + teacherWages.getTeacherName() + " 导入成功");
                } else if (i == 1) {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、老师姓名 " + teacherWages.getTeacherName() + " 已存在");
                } else{
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、学生身份证 " + teacherWages.getIdCard() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + teacherWages.getTeacherName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();

    }

    @Override
    public String updateTeacherWages(SchoolTeacherWages schoolTeacherWages) {
        int i = judgIsExit(schoolTeacherWages);
        if (i == 0) {
            this.updateById(schoolTeacherWages);
            return "修改成功";
        } else if (i == 1) {
            return "老师姓名" + schoolTeacherWages.getTeacherName() + "已存在，更新失败";
        } else{
            return "身份证号" + schoolTeacherWages.getIdCard() + "已存在,更新失败";
        }
    }

    @Override
    public String addTeacherWages(SchoolTeacherWages schoolTeacherWages) {
        int i = judgIsExit(schoolTeacherWages);
        if (i == 0) {
            this.save(schoolTeacherWages);
            return "新增成功";
        } else if (i == 1) {
            return "老师姓名" + schoolTeacherWages.getTeacherName() + "已存在，新增失败";
        } else {
            return "身份证号" + schoolTeacherWages.getIdCard() + "已存在,新增失败";
        }
    }

    @Override
    public int insertByTeacherId(Long teacherId,SchoolTeacherWages schoolTeacherWages) {
        SchoolTeacher schoolTeacher = schoolTeacherMapper.selectById(teacherId);
        schoolTeacherWages.setTeacherName(schoolTeacher.getTeacherName());
        schoolTeacherWages.setTeacherTel(schoolTeacher.getTeacherTel());
        return schoolTeacherWagesMapper.insert(schoolTeacherWages);
    }

    /**
     * 检查导入的数据
     * @param list
     */
    @Override
    public void checkData(List<SchoolTeacherWages> list) {
        if (StringUtils.isNull(list) || list.size() == 0) {
            throw new ServiceException("导入用户数据不能为空！");
        }
        // 准备记录日志数据
        int failureNum = 0;
        StringBuilder failureMsg = new StringBuilder();
        for (SchoolTeacherWages schoolTeacherWages : list) {
            if (StringUtils.isEmpty(schoolTeacherWages.getTeacherName())) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、教师姓名为空,请您重新输入! ");
            } else if (StringUtils.isEmpty(schoolTeacherWages.getTeacherTel())) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、教师联系方式为空,请您重新输入! ");
            } else if (StringUtils.isNull(schoolTeacherWages.getWagesTime())) {
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、工资日期为空，请您重新输入！");
            } else if (isNotNull(schoolTeacherWages.getWagesTime())) {
                try {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    Date schoolTeacherWagesDate = schoolTeacherWages.getWagesTime();
                    sdf.format(schoolTeacherWagesDate);
                } catch (Exception e) {
                    throw new ServiceException("格式不对，请检查日期格式");
                }
            }
//            else {
//                LambdaQueryWrapper<SchoolTeacherWages> lqw = new LambdaQueryWrapper<>();
//                lqw
//                        .eq(SchoolTeacherWages::getTeacherTel, schoolTeacherWages.getTeacherTel());
//                SchoolTeacherWages teacherWages = schoolTeacherWagesMapper.selectOne(lqw);
//                if (isNull(teacherWages)){
//                    failureNum++;
//                    failureMsg.append("<br/>" + failureNum + "、该老师不存在,请您重新输入! ");
//                }
//            }
            if (StringUtils.isNull(schoolTeacherWages.getBasePay())) {
                schoolTeacherWages.setBasePay(new BigDecimal(0));
            }
            if (StringUtils.isNull(schoolTeacherWages.getBonus())) {
                schoolTeacherWages.setBonus(new BigDecimal(0));
            }
            if (StringUtils.isNull(schoolTeacherWages.getPension())) {
                schoolTeacherWages.setPension(new BigDecimal(0));
            }
            if (StringUtils.isNull(schoolTeacherWages.getAccumulationFund())) {
                schoolTeacherWages.setAccumulationFund(new BigDecimal(0));
            }
            if (StringUtils.isNull(schoolTeacherWages.getMedicalInsurance())) {
                schoolTeacherWages.setMedicalInsurance(new BigDecimal(0));
            }
            if (StringUtils.isNull(schoolTeacherWages.getFareSubsidy())) {
                schoolTeacherWages.setFareSubsidy(new BigDecimal(0));
            }
            if (StringUtils.isNull(schoolTeacherWages.getTelephoneSubsidy())) {
                schoolTeacherWages.setTelephoneSubsidy(new BigDecimal(0));
            }
            if (StringUtils.isNull(schoolTeacherWages.getMealAllowance())) {
                schoolTeacherWages.setMealAllowance(new BigDecimal(0));
            }
            if (StringUtils.isNull(schoolTeacherWages.getIncomeTax())) {
                schoolTeacherWages.setIncomeTax(new BigDecimal(0));
            }
            if (StringUtils.isNull(schoolTeacherWages.getUnemploymentBenefits())) {
                schoolTeacherWages.setUnemploymentBenefits(new BigDecimal(0));
            }
            if (StringUtils.isNull(schoolTeacherWages.getOvertimePay())) {
                schoolTeacherWages.setOvertimePay(new BigDecimal(0));
            }
            if (StringUtils.isNull(schoolTeacherWages.getRemarks())) {
                schoolTeacherWages.setRemarks("");
            }
            LambdaQueryWrapper<SchoolTeacher> lqw = new LambdaQueryWrapper<>();
            lqw
                    .eq(SchoolTeacher::getTeacherTel, schoolTeacherWages.getTeacherTel());
            SchoolTeacher schoolTeacher = schoolTeacherMapper.selectOne(lqw);
            if (isNull(schoolTeacher)){
                failureNum++;
                failureMsg.append("<br/>" + failureNum + "、该老师不存在,请您重新输入! ");
            }else {
                schoolTeacherWages.setTeacherId(schoolTeacher.getId());
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共" + failureNum + "条数据格式不正确，错误如下：");
            throw new BaseException(failureMsg.toString());
        }
    }

    /**
     * 导入工资条数据
     * @param list
     * @return
     */
    @Override
    public String importData(List<SchoolTeacherWages> list) {
        // 准备记录日志数据
        int successNum = 0;
        StringBuilder successMsg = new StringBuilder();

        schoolTeacherWagesMapper.batchInsertTeacherWages(list);

//        for (SchoolTeacherWages schoolTeacherWages : list) {
//            try {
//            schoolTeacherWagesMapper.insert(schoolTeacherWages);
//            successNum++;
//            successMsg.append("<br/>" + successNum + "数据" + " 导入成功");
//            } catch (Exception e) {
//                throw new ServiceException("导入失败");
//            }
//        }
        successMsg.insert(0, "恭喜您，数据已导入成功！");
        return successMsg.toString();
    }


    public int judgIsExit(SchoolTeacherWages schoolTeacherWages) {
        SchoolTeacherWages schoolTeacherWages1 = new SchoolTeacherWages();
        if(StringUtils.isNotNull(schoolTeacherWages.getId())){
            schoolTeacherWages1.setId(schoolTeacherWages.getId());
        }
        schoolTeacherWages1.setTeacherName(schoolTeacherWages.getTeacherName());
        if (schoolTeacherWagesMapper.query(schoolTeacherWages1).size() > 0 && schoolTeacherWages1.getTeacherName() != null) {
            return 1;
        }
        schoolTeacherWages1.setTeacherName("");
        schoolTeacherWages1.setIdCard(schoolTeacherWages.getIdCard());
        if (schoolTeacherWagesMapper.query(schoolTeacherWages1).size() > 0 && schoolTeacherWages1.getIdCard() != null) {
            return 2;
        }
        return 0;
    }
}
