package com.ruoyi.web.work.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.web.work.domain.Platform;
import com.ruoyi.web.work.domain.Statement;
import com.ruoyi.web.work.domain.StatementDetail;
import com.ruoyi.web.work.mapper.StatementDetailMapper;
import com.ruoyi.web.work.mapper.StatementMapper;
import com.ruoyi.web.work.service.IStatementDetailService;
import com.ruoyi.web.work.service.IStatementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.Validator;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @author lsw
 * @date 2024-04-20
 */
@Service
public class StatementServiceImpl extends ServiceImpl<StatementMapper, Statement> implements IStatementService {
    @Autowired
    private StatementMapper statementMapper;

    @Autowired
    private StatementDetailMapper statementDetailMapper;

    @Autowired
    private IStatementDetailService detailService;

    @Autowired
    protected Validator validator;

    @Autowired
    private RedisCache redisCache;

    @Override
    public List<Statement> selectList(Statement statement) {
        return statementMapper.selectList(statement);
    }

    @Override
    public List<Statement> selectAuditList(Statement statement) {
        return statementMapper.selectAuditList(statement);
    }

    @Transactional
    @Override
    public AjaxResult makeAdd(List<StatementDetail> list, Statement statement) {
        if (StringUtils.isNull(list) || list.size() == 0) {
            throw new ServiceException("上传结算单数据不能为空！");
        }
        Platform platform = redisCache.getCacheObject(CacheConstants.APP_PLATFORM);
        statement.setUserId(SecurityUtils.getLoginUser().getUser().getUserId());
        statement.setCompanyId(SecurityUtils.getLoginUser().getUser().getCompanyId());
        statement.setOpBy(SecurityUtils.getLoginUser().getUser().getNickName());
        statement.setState(0);
        statement.setGive(0);
        statement.setAudit(0);
        statement.setMoney(BigDecimal.ZERO);
        statement.setServiceCompany(platform.getServiceCompany());
        statement.setFileName(statement.getFile().getOriginalFilename());
        if (!save(statement)) {
            throw new ServiceException("创建结算单失败,请联系平台");
        }
        int successNum = 0;
        for (StatementDetail detail : list) {
            BeanValidators.validateWithException(validator, detail);
            detail.setStatementId(statement.getId());
            detail.setProjectId(statement.getProjectId());
            detail.setState(0);
            detail.setNum(StringUtils.generateNumber());
            detail.setServiceMoney(platform.getRate().divide(new BigDecimal("100")).multiply(detail.getMoney()));
            detail.setRealMoney(detail.getMoney().subtract(detail.getServiceMoney()));
            StatementDetail check = statementDetailMapper.check(detail);
            if (check != null) {
                throw new ServiceException("导入失败,身份证为：" + detail.getIdCard() + " 的数据已存在");
            }
            if (!detailService.save(detail)) {
                throw new ServiceException("导入失败,请联系平台");
            }
            successNum++;
        }
        return AjaxResult.success("创建成功！本次导入" + successNum + " 条数据");
    }

    @Override
    public AjaxResult makeGenerate(Long id) {
        Statement statement = getById(id);
        if (statement == null || !statement.getCompanyId().equals(SecurityUtils.getLoginUser().getUser().getCompanyId())) {
            return AjaxResult.error("结算单不存在或非法操作");
        }
        if (statement.getState() != 0) {
            return AjaxResult.error("不可操作");
        }
        statement.setState(1);
        statement.setNum(StringUtils.generateNumber());
        statement.setGenerateTime(new Date());
        if (!updateById(statement)) {
            throw new ServiceException("生成结算单失败,请联系平台");
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult manageSubmit(Long id) {
        Statement statement = getById(id);
        if (statement == null || !statement.getCompanyId().equals(SecurityUtils.getLoginUser().getUser().getCompanyId())) {
            return AjaxResult.error("结算单不存在或非法操作");
        }
        if (statement.getAudit() != 0) {
            return AjaxResult.error("不可操作");
        }
        statement.setAudit(1);
        statement.setSubmitTime(new Date());
        if (!updateById(statement)) {
            throw new ServiceException("提交结算单审核失败,请联系平台");
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult manageCancel(Long id) {
        Statement statement = getById(id);
        if (statement == null || !statement.getCompanyId().equals(SecurityUtils.getLoginUser().getUser().getCompanyId())) {
            return AjaxResult.error("结算单不存在或非法操作");
        }
        if (statement.getAudit() != 1) {
            return AjaxResult.error("当前结算单不能撤回");
        }
        statement.setAudit(0);
        if (!updateById(statement)) {
            throw new ServiceException("撤回结算单审核失败,请联系平台");
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult auditSuccess(Long id) {
        Statement statement = getById(id);
        if (statement == null || !statement.getCompanyId().equals(SecurityUtils.getLoginUser().getUser().getCompanyId())) {
            return AjaxResult.error("结算单不存在或非法操作");
        }
        if (statement.getAudit() != 1) {
            return AjaxResult.error("当前结算单不能被审核");
        }
        statement.setAudit(2);
        statement.setAuditTime(new Date());
        if (!updateById(statement)) {
            throw new ServiceException("结算单审核失败,请联系平台");
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult makeRemove(Long id) {
        Statement statement = getById(id);
        if (statement == null || !statement.getCompanyId().equals(SecurityUtils.getLoginUser().getUser().getCompanyId())) {
            return AjaxResult.error("结算单不存在或非法操作");
        }
        if (statement.getState() != 0) {
            return AjaxResult.error("当前结算单不能删除");
        }
        if (!removeById(id)) {
            throw new ServiceException("删除结算单失败,请联系平台");
        }
        return AjaxResult.success();
    }
}
