package com.zehong.system.service.impl;

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

import com.zehong.common.core.domain.entity.SysUser;
import com.zehong.common.core.exception.BusinessException;
import com.zehong.common.utils.DateUtils;
import com.zehong.common.utils.SecurityUtils;
import com.zehong.system.domain.TAccount;
import com.zehong.system.domain.TCashOperate;
import com.zehong.system.mapper.TAccountMapper;
import com.zehong.system.mapper.TCashOperateMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zehong.system.mapper.TPurchaseMapper;
import com.zehong.system.domain.TPurchase;
import com.zehong.system.service.ITPurchaseService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;

/**
 * 外部采购（报销）申请Service业务层处理
 * 
 * @author zehong
 * @date 2023-06-16
 */
@Service
public class TPurchaseServiceImpl implements ITPurchaseService 
{
    @Autowired
    private TPurchaseMapper tPurchaseMapper;

    @Resource
    private TAccountMapper tAccountMapper;

    @Resource
    private TCashOperateMapper tCashOperateMapper;

    /**
     * 查询外部采购（报销）申请
     * 
     * @param purchaseId 外部采购（报销）申请ID
     * @return 外部采购（报销）申请
     */
    @Override
    public TPurchase selectTPurchaseById(Long purchaseId)
    {
        return tPurchaseMapper.selectTPurchaseById(purchaseId);
    }

    /**
     * 查询外部采购（报销）申请列表
     * 
     * @param tPurchase 外部采购（报销）申请
     * @return 外部采购（报销）申请
     */
    @Override
    public List<TPurchase> selectTPurchaseList(TPurchase tPurchase)
    {
        return tPurchaseMapper.selectTPurchaseList(tPurchase);
    }

    /**
     * 新增外部采购（报销）申请
     * 
     * @param tPurchase 外部采购（报销）申请
     * @return 结果
     */
    @Override
    public int insertTPurchase(TPurchase tPurchase)
    {
        tPurchase.setCreateTime(DateUtils.getNowDate());
        SysUser user = SecurityUtils.getLoginUser().getUser();
        tPurchase.setPurchaseDeptId(user.getDeptId());
        tPurchase.setHandledByUserId(user.getUserId());//经办人
        return tPurchaseMapper.insertTPurchase(tPurchase);
    }

    /**
     * 修改外部采购（报销）申请
     * 
     * @param tPurchase 外部采购（报销）申请
     * @return 结果
     */
    @Override
    public int updateTPurchase(TPurchase tPurchase)
    {
        tPurchase.setUpdateTime(DateUtils.getNowDate());
        return tPurchaseMapper.updateTPurchase(tPurchase);
    }

    /**
     * 批量删除外部采购（报销）申请
     * 
     * @param purchaseIds 需要删除的外部采购（报销）申请ID
     * @return 结果
     */
    @Override
    public int deleteTPurchaseByIds(Long[] purchaseIds)
    {
        return tPurchaseMapper.deleteTPurchaseByIds(purchaseIds);
    }

    /**
     * 删除外部采购（报销）申请信息
     * 
     * @param purchaseId 外部采购（报销）申请ID
     * @return 结果
     */
    @Override
    public int deleteTPurchaseById(Long purchaseId)
    {
        return tPurchaseMapper.deleteTPurchaseById(purchaseId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int approvalPurchase(TPurchase tPurchase){
        if ("2".equals(tPurchase.getPurchaseStatus())){
            //校验及更新可用金额
            checkAccount(tPurchase);
            //更新操作记录
            insertOperateLog(tPurchase);
        }
        tPurchase.setUpdateTime(DateUtils.getNowDate());
        return tPurchaseMapper.updateTPurchase(tPurchase);
    }

    /**
     * 校验部门可用金额
     * @param tPurchase 采购信息
     * @return
     */
    private boolean checkAccount(TPurchase tPurchase){
        //更新账户可用金额
        TAccount tAccount=new TAccount();
        tAccount.setDeptId(tPurchase.getPurchaseDeptId());
        List<TAccount> rst= tAccountMapper.selectTAccountList(tAccount);
        if(!CollectionUtils.isEmpty(rst)){
            TAccount accountInfo = rst.get(0);
            if(accountInfo.getAbleAmount().compareTo(tPurchase.getTotal()) == -1){
                throw new BusinessException("账户可用金额不足!");
            }
            accountInfo.setAbleAmount(accountInfo.getAbleAmount().subtract(tPurchase.getTotal()));
            tAccountMapper.updateTAccount(accountInfo);
        }
        return true;
    }

    /**
     * 记录资金变动
     * @param tPurchase 采购信息
     */
    private void insertOperateLog(TPurchase tPurchase){
        TCashOperate operate = new TCashOperate();
        operate.setOperateDeptId(tPurchase.getPurchaseDeptId());
        operate.setOperateAmount(tPurchase.getTotal());
        operate.setOperateTime(new Date());
        operate.setRelationDoc(String.valueOf(tPurchase.getPurchaseId()));
        operate.setOperateType("4");
        operate.setDocumentType("3");//1.交易单 2.借支单 3.外部采购单 4.借贷单
        tCashOperateMapper.insertTCashOperate(operate);
    }
}
