package com.srs.comprehensive.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.srs.common.core.domain.AjaxResult;
import com.srs.comprehensive.domain.CphBiyeApply;
import com.srs.comprehensive.domain.CphGoodCancelLog;
import com.srs.comprehensive.domain.CphNewGoodClassApply;
import com.srs.comprehensive.domain.Dto.CphCancel;
import com.srs.comprehensive.domain.Vo.ExcelGoodClass;
import com.srs.comprehensive.mapper.CphGoodCancelLogMapper;
import com.srs.comprehensive.mapper.CphNewGoodClassApplyMapper;
import com.srs.comprehensive.service.ICphNewGoodClassApplyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import static com.srs.common.utils.DateUtils.getNowDate;
import static com.srs.common.utils.SecurityUtils.getLoginUser;
import static com.srs.common.utils.SecurityUtils.getUsername;

/**
 * 先进班集体Service业务层处理
 *
 * @author srs
 * @date 2024-05-15
 */
@Service
public class CphNewGoodClassApplyServiceImpl extends ServiceImpl<CphNewGoodClassApplyMapper,CphNewGoodClassApply> implements ICphNewGoodClassApplyService {
    @Autowired
    private CphNewGoodClassApplyMapper cphNewGoodClassApplyMapper;

    @Autowired
    private CphGoodCancelLogMapper _logMapper;
    @Autowired
    public PlatformTransactionManager transactionManager;


    @Override
    public AjaxResult editStatus(CphNewGoodClassApply param){
        try{

            CphNewGoodClassApply find = cphNewGoodClassApplyMapper.selectById(param.id);
            if(find == null){
                throw new Exception("该记录不存在");
            }

            find.applyStatus = param.applyStatus;
            find.jwcCmt = param.jwcCmt;
            int res = cphNewGoodClassApplyMapper.updateById(find);
            if(res == 0){
                throw new Exception("更新状态失败");
            }

            return AjaxResult.success();
        }catch(Exception ex){
            return AjaxResult.error(ex.getMessage());
        }
    }



    @Override
    public AjaxResult addRemark(CphNewGoodClassApply param){
        try{
            CphNewGoodClassApply find = cphNewGoodClassApplyMapper.selectById(param.id);
            if(find == null){
                throw new Exception("该记录不存在");
            }
            find.remark = param.remark;
            int res = cphNewGoodClassApplyMapper.updateById(find);
            if(res == 0){
                throw new Exception("更新备注失败");
            }

            return AjaxResult.success();
        }catch (Exception ex){
            return AjaxResult.error(ex.getMessage());
        }
    }


    @Override
    public AjaxResult editManySendMoney(List<Long> ids){
        try{
            if(ids.size() == 0){
                throw new Exception("请选择");
            }

            QueryWrapper<CphNewGoodClassApply> query = new QueryWrapper<>();
            query.in("id",ids)
                    .eq("apply_status","6");
            List<CphNewGoodClassApply> list = cphNewGoodClassApplyMapper.selectList(query);
            if(list.size() == 0){
                throw new Exception("记录不存在");
            }
            list.forEach(x->{
                x.sendMoneyTime = getNowDate();
                x.isSendMoney = "是";
            });

            boolean res = this.updateBatchById(list);
            if(!res){
                throw new Exception("更新状态失败");
            }

            return AjaxResult.success();
        }catch(Exception ex){
            return AjaxResult.error(ex.getMessage());
        }
    }


    @Override
    public AjaxResult editAllSendMoney(){
        try{

            QueryWrapper<CphNewGoodClassApply> query = new QueryWrapper<>();
            query.ne("is_send_money","是")
                    .eq("apply_status","6");

            List<CphNewGoodClassApply> list = cphNewGoodClassApplyMapper.selectList(query);

            if(list.size() == 0){
                throw new Exception("暂无需要标记的项目");
            }

            List<CphNewGoodClassApply> needUpdateList = new ArrayList<>();

            for(CphNewGoodClassApply x : list){
                CphNewGoodClassApply temp = new CphNewGoodClassApply();
                temp.id = x.id;
                temp.isSendMoney = "是";
                temp.sendMoneyTime = getNowDate();
                needUpdateList.add(temp);
            }

            boolean res = this.updateBatchById(needUpdateList);
            if(!res){
                throw new Exception("更新状态失败");
            }

            return AjaxResult.success();
        }catch (Exception ex){
            return AjaxResult.error(ex.getMessage());
        }
    }



    @Override
    public AjaxResult editSendMoney(CphNewGoodClassApply param){
        try{

            CphNewGoodClassApply find = cphNewGoodClassApplyMapper.selectById(param.id);
            if (find == null){
                throw new Exception("该记录不存在");
            }

            if(Objects.equals(param.isSendMoney, "是")){
                find.isSendMoney = "是";
                find.sendMoneyTime = getNowDate();
            }

            if(Objects.equals(param.isSendMoney, "否")){
                find.isSendMoney = "否";
                find.setSendMoneyTime(null);
            }

            LambdaUpdateWrapper<CphNewGoodClassApply> lambdaUpdate = Wrappers.lambdaUpdate();

            lambdaUpdate.eq(CphNewGoodClassApply::getId, find.getId());

            if(Objects.equals(param.isSendMoney, "否")){
                lambdaUpdate.set(CphNewGoodClassApply::getSendMoneyTime, null);
            }

            boolean res = this.update(find, lambdaUpdate);

            if(!res){
                throw new Exception("标记失败");
            }

            return AjaxResult.success();
        }catch (Exception ex){
            return AjaxResult.error(ex.getMessage());
        }
    }


    @Override
    public List<ExcelGoodClass> exportFdy(CphNewGoodClassApply param){
        return cphNewGoodClassApplyMapper.exportFdy(param);
    }

    @Override
    public List<ExcelGoodClass> exportView(CphNewGoodClassApply param){
        return cphNewGoodClassApplyMapper.exportView(param);
    }


    @Override
    public AjaxResult manyAudit(List<Long> ids){
        TransactionDefinition def = new DefaultTransactionDefinition();
        TransactionStatus status = transactionManager.getTransaction(def);
        try{
            if(ids.size() == 0){
                throw new Exception("请选择通过的记录");
            }
            QueryWrapper<CphNewGoodClassApply> query = new QueryWrapper<>();
            query.in("id",ids);
            List<CphNewGoodClassApply> list = cphNewGoodClassApplyMapper.selectList(query);
            if(list.isEmpty()){
                throw new Exception("记录不存在");
            }

            List<CphNewGoodClassApply> needUpdateList = new ArrayList<>();

            for (CphNewGoodClassApply x: list ) {
                CphNewGoodClassApply temp = new CphNewGoodClassApply();
                temp.id = x.id;
                if(Objects.equals(x.applyStatus, "2")){
                    temp.applyStatus = "3";
                    temp.xwCmt = "同意申请。";
                    temp.xwAuditNo = getUsername();
                    temp.setXwTime(getNowDate());
                }
                if(Objects.equals(x.applyStatus, "3")){
                    temp.applyStatus = "6";
                    temp.jwcCmt = "同意申请。";
                    temp.jwcAuditNo = getUsername();
                    temp.setXwTime(getNowDate());
                }
                needUpdateList.add(temp);
            }

            boolean res = this.updateBatchById(needUpdateList);
            if(!res){
                throw new Exception("更新记录失败");
            }

            transactionManager.commit(status);
            return AjaxResult.success();
        }catch(Exception ex){
            transactionManager.rollback(status);
            return AjaxResult.error(ex.getMessage());
        }
    }


    @Override
    public AjaxResult doAudit( CphNewGoodClassApply param){
        try{
            CphNewGoodClassApply find = cphNewGoodClassApplyMapper.selectById(param.id);
            if(find == null){
                throw new Exception("该记录不存在");
            }
            if(Objects.equals(find.applyStatus, "1")){
                find.fdyCmt = param.fdyCmt;
                find.fdyAuditNo = getUsername();
                find.setFdyTime(getNowDate());
            }
            if(Objects.equals(find.applyStatus, "2")){
                find.xwCmt = param.xwCmt;
                find.xwAuditNo = getUsername();
                find.setXwTime(getNowDate());
            }
            if(Objects.equals(find.applyStatus, "3")){
                find.jwcCmt = param.jwcCmt;
                find.jwcAuditNo = getUsername();
                find.setXgTime(getNowDate());
            }
            find.applyStatus = param.applyStatus;
            int res = cphNewGoodClassApplyMapper.updateById(find);
            if(res == 0){
                throw new Exception("更新审核状态失败");
            }

            return AjaxResult.success();
        }catch(Exception ex){
            return AjaxResult.error(ex.getMessage());
        }
    }
    @Override
    public AjaxResult reApply(@RequestBody CphNewGoodClassApply param){
        try{
            CphNewGoodClassApply old = cphNewGoodClassApplyMapper.selectById(param.id);
            String nowUser = getUsername();
            if(old == null){
                throw new Exception("该记录不存在");
            }
            if(!Objects.equals(old.getApplyStatus(), "10")){
                throw new Exception("这条记录不是驳回项，不可以重新提交");
            }
            if(!Objects.equals(nowUser, old.getStuNo())){
                throw new Exception("不是本人");
            }
            CphNewGoodClassApply searchQuery2 = new CphNewGoodClassApply();
            searchQuery2.setStuYearId(param.getStuYearId());
            searchQuery2.setStuNo(getUsername());
            List<CphNewGoodClassApply> isExist2 = cphNewGoodClassApplyMapper.listView(searchQuery2);
            List<CphNewGoodClassApply> isExist3 = isExist2.stream()
                    .filter(x-> (!Objects.equals(x.getApplyStatus(), "14") )
                            &&( !Objects.equals(x.getApplyStatus(), "12"))
                            &&(!Objects.equals(x.getApplyStatus(), "10")) )
                    .collect(Collectors.toList());

            if(isExist3.size() >0){
                throw new Exception("您已经申请过了。");
            }
            old.setApplyStatus("14");
            old.setApplyTime(getNowDate());

            int res = cphNewGoodClassApplyMapper.updateById(old);
            if(res == 0){
                throw new Exception("更新旧失败");
            }
            CphNewGoodClassApply needInsert = new CphNewGoodClassApply();
            needInsert.setStuNo(old.getStuNo());
            needInsert.setClassId(param.getClassId());
            needInsert.setClassCode(param.getClassCode());
            needInsert.setStuYearId(param.getStuYearId());
            needInsert.setFdyName(param.getFdyName());
            needInsert.setIdCard(param.getIdCard());
            needInsert.setBankCard(param.getBankCard());
            needInsert.setBankAddr(param.getBankAddr());
            needInsert.setClassCount(param.getClassCount());
            needInsert.setApplyStatus("1");
            needInsert.setGoodHis(param.getGoodHis());
            needInsert.setMainHis(param.getMainHis());
            needInsert.setTestimonyMaterials(param.getTestimonyMaterials());
            needInsert.setApplyTime(getNowDate());
            int res2 = cphNewGoodClassApplyMapper.insertCphNewGoodClassApply(needInsert);
            if(res2 == 0){
                throw new Exception("插入新记录失败");
            }

            return AjaxResult.success("操作成功");
        }catch(Exception ex){
            return AjaxResult.error(ex.getMessage());
        }
    }

    @Override
    public AjaxResult cancelApply( CphCancel param){
        TransactionDefinition def = new DefaultTransactionDefinition();
        TransactionStatus status = transactionManager.getTransaction(def);
        try{
            if(param.reason == null || param.reason.equals("")){
                throw new Exception("请填写原因");
            }
            Long id = param.id;
            String stuNo = getUsername();
            CphNewGoodClassApply f = cphNewGoodClassApplyMapper.selectById(id);
            if(!Objects.equals(f.getStuNo(), stuNo)){
                throw new Exception("what do u want to do?");
            }

            if(!Objects.equals(f.getApplyStatus(), "1")){
                throw new Exception("该记录已经过审核，不可以取消申请，刷新试试");
            }

            CphGoodCancelLog log = new CphGoodCancelLog();
            log.setReason(param.reason);
            log.setIp(getLoginUser().getIpaddr());
            log.setStuNo(f.getStuNo());
            log.setTypeCode("XJBJT");
            log.setCreateBy(getUsername());
            log.setCreateTime(getNowDate());
            int res3 = _logMapper.insertCphGoodCancelLog(log);
            if(res3 == 0){
                throw new Exception("插入取消记录失败，请联系管理员。");
            }

            int res = cphNewGoodClassApplyMapper.deleteById(id);
            if(res != 1){
                throw new Exception("操作失败，刷新试试");
            }

            transactionManager.commit(status);
            return AjaxResult.success();
        }catch(Exception ex){
            transactionManager.rollback(status);
            return AjaxResult.error(ex.getMessage());
        }

    }

    @Override
    public AjaxResult doApply(CphNewGoodClassApply param){
        try{
            CphNewGoodClassApply classApply = this.getStuClass(param.stuNo);

            if(classApply == null){
                throw new Exception("未查询到您的班级信息");
            }

            List<String> notExistStatus = new ArrayList<>();
            notExistStatus.add("1");
            notExistStatus.add("2");
            notExistStatus.add("3");
            notExistStatus.add("6");

            QueryWrapper<CphNewGoodClassApply> query = new QueryWrapper<>();
            query.eq("class_id",classApply.classId)
                    .in("apply_status",notExistStatus);
            List<CphNewGoodClassApply> findList = cphNewGoodClassApplyMapper.selectList(query);
            if(findList.size() != 0){
                throw new Exception("您的班级已提交过一次申请");
            }

            CphNewGoodClassApply needInsert = new CphNewGoodClassApply();
            needInsert.stuNo = param.stuNo;
            needInsert.bankCard = param.bankCard;
            needInsert.bankAddr = param.bankAddr;
            needInsert.stuYearId = param.stuYearId;
            needInsert.goodHis = param.goodHis;
            needInsert.mainHis = param.mainHis;
            needInsert.idCard = param.idCard;
            needInsert.setTestimonyMaterials(param.testimonyMaterials);

            needInsert.classId = classApply.classId;
            needInsert.classCode = classApply.classCode;
            needInsert.fdyNo = classApply.fdyNo;
            needInsert.fdyName = classApply.fdyName;
            needInsert.classCount = classApply.classCount;

            needInsert.applyTime = getNowDate();

            needInsert.applyStatus = "1";

            int res = cphNewGoodClassApplyMapper.insert(needInsert);
            if(res == 0){
                throw new Exception("插入记录失败");
            }

            return AjaxResult.success();
        }catch (Exception ex){
            return AjaxResult.error(ex.getMessage());
        }
    }


    @Override
    public CphNewGoodClassApply getStuClass(String stuNo){
        return cphNewGoodClassApplyMapper.getStuClass(stuNo);
    }

    @Override
    public List<CphNewGoodClassApply> listView(CphNewGoodClassApply param){
        return cphNewGoodClassApplyMapper.listView(param);
    }

    @Override
    public List<CphNewGoodClassApply> listFdy(CphNewGoodClassApply param){
        return cphNewGoodClassApplyMapper.listFdy(param);
    }



    /**
     * 查询先进班集体
     *
     * @param id 先进班集体主键
     * @return 先进班集体
     */
    @Override
    public CphNewGoodClassApply selectCphNewGoodClassApplyById(Long id) {
        return cphNewGoodClassApplyMapper.selectCphNewGoodClassApplyById(id);
    }

    /**
     * 查询先进班集体列表
     *
     * @param cphNewGoodClassApply 先进班集体
     * @return 先进班集体
     */
    @Override
    public List<CphNewGoodClassApply> selectCphNewGoodClassApplyList(CphNewGoodClassApply cphNewGoodClassApply) {
        return cphNewGoodClassApplyMapper.selectCphNewGoodClassApplyList(cphNewGoodClassApply);
    }

    /**
     * 新增先进班集体
     *
     * @param cphNewGoodClassApply 先进班集体
     * @return 结果
     */
    @Override
    public int insertCphNewGoodClassApply(CphNewGoodClassApply cphNewGoodClassApply) {
            return cphNewGoodClassApplyMapper.insertCphNewGoodClassApply(cphNewGoodClassApply);
    }

    /**
     * 修改先进班集体
     *
     * @param cphNewGoodClassApply 先进班集体
     * @return 结果
     */
    @Override
    public int updateCphNewGoodClassApply(CphNewGoodClassApply cphNewGoodClassApply) {
        return cphNewGoodClassApplyMapper.updateCphNewGoodClassApply(cphNewGoodClassApply);
    }

    /**
     * 批量删除先进班集体
     *
     * @param ids 需要删除的先进班集体主键
     * @return 结果
     */
    @Override
    public int deleteCphNewGoodClassApplyByIds(Long[] ids) {
        return cphNewGoodClassApplyMapper.deleteCphNewGoodClassApplyByIds(ids);
    }

    /**
     * 删除先进班集体信息
     *
     * @param id 先进班集体主键
     * @return 结果
     */
    @Override
    public int deleteCphNewGoodClassApplyById(Long id) {
        return cphNewGoodClassApplyMapper.deleteCphNewGoodClassApplyById(id);
    }
}
