package com.sifang.modules.flowpath.service;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.account.dao.TraderAccountDao;
import com.sifang.modules.account.entity.CrmTraderAccount;
import com.sifang.modules.flowable.service.ProcessFlowableService;
import com.sifang.modules.flowable.utils.FormUtils;
import com.sifang.modules.flowpath.constant.BondApplyConstant;
import com.sifang.modules.flowpath.dao.SettlementAmountAdjustmentApplyDao;
import com.sifang.modules.flowpath.entity.SettlementAmountAdjustmentApply;
import com.sifang.modules.flowpath.vo.DistributionGoodsVo;
import com.sifang.modules.platform.utils.PlantformUtils;
import com.sifang.modules.supply.order.entity.CrmSupplyMaterialDeliverOrder;
import com.sifang.modules.supply.order.entity.CrmSupplyMaterialReturnOrder;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.common.service.BaseService;
import com.sifang.modules.sys.common.utils.DateUtils;
import com.sifang.modules.sys.common.utils.IdGen;
import com.sifang.modules.sys.common.utils.StringUtil;
import com.sifang.modules.sys.util.CrmUtils;
import com.sifang.modules.sys.util.LayuiPage;
import org.flowable.engine.TaskService;
import org.flowable.task.api.Task;
import org.hibernate.SQLQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

//结算额调整申请
@Service
public class SettlementAmountAdjustmentApplyService extends BaseService {

    @Autowired
    private SettlementAmountAdjustmentApplyDao settlementApplyDao;

    @Autowired
    private ProcessFlowableService flowableService;

    @Autowired
    TaskService taskService;

    @Autowired
    private TraderAccountDao accountDao;

    public void applyList(LayuiPage<Record> page, Map<String, String> map){
        User user = UserUtils.getUser();
        settlementApplyDao.applyList(page,map,user);
    }

    public Record getDetailById(String id){
        return settlementApplyDao.getDetailById(id);
    }

    @Transactional(rollbackFor = Exception.class)
    public void saveSettlementAmountApply(DistributionGoodsVo vo){
        logger.info(">>>>>>>>>>>>>>>saveSettlementAmountApply  vo:{}",vo);
        User user = UserUtils.getUser();
        String userName=user.getUserName();
        Date date=new Date();
        SettlementAmountAdjustmentApply apply;
        if(StringUtil.isBlank(vo.getId())){
            apply=new SettlementAmountAdjustmentApply();
            apply.setApplyNumber(PlantformUtils.getOrderNumber());
            apply.setDepartmentId(user.getDepartmentId());
            apply.setDepartmentName(user.getDepartmentName());
        }else{
            apply=settlementApplyDao.getByApplyId(vo.getId());
            if(com.sifang.modules.sunshine.SystemSetting.utils.StringUtil.equalsAny(apply.getStatus(), BondApplyConstant.APPLYSTATUS_ONE,BondApplyConstant.APPLYSTATUS_TWO,BondApplyConstant.APPLYSTATUS_THREE)){
                throw new RuntimeException("该申请状态不允许修改!");
            }
        }
        apply.setTraderId(vo.getTraderId());
        apply.setAdjustType(vo.getAdjustType());
        apply.setAmount(vo.getAmount());
        apply.setVoucher(vo.getVoucher());
        apply.setRemarks(vo.getRemarks());
        apply.setCreateBy(user.getId());
        apply.setCreateName(userName);
        apply.setCreateTime(date);
        if(StringUtil.isNotBlank(vo.getEntryId())){
            apply.setEntryId(vo.getEntryId());
        }

        if(StringUtil.isBlank(vo.getId())){
            apply.setId(IdGen.uuid());
            Record rd = FormUtils.getdefLatest(FormUtils.SETTLE_AMOUNT_ADJUST_APPLICATION);
            if(rd == null){
                throw  new RuntimeException("流程未定义，不可发布申请");
            }
            String processName="结算额调整申请-"+user.getUserName()+'-'+ DateUtils.formatDate(date,"yyyy-MM-dd HH:mm:ss");
            String processInstanceId=flowableService.startProcessFlowable(user,apply.getId(),rd,FormUtils.SETTLE_AMOUNT_ADJUST_APPLICATION,date,userName,vo.getRemarks(),processName,apply.getTraderId());
            apply.setProcessInstanceId(processInstanceId);
            apply.setProcessDefId(rd.getStr("id"));
            apply.setOperateUserIds(user.getId()+","+rd.getStr("oneAuditUseId"));

            String taskName=FormUtils.getOneStepTaskName(rd.getStr("id"));
            apply.setTaskName(taskName);
            logger.info(">>>>>>>>>>>>>>>>>>>>saveSettlementAmountApply processInstanceId:{},taskName:{}",processInstanceId,taskName);
        }else if(StringUtil.isNotBlank(apply.getProcessInstanceId())){
            Task task = taskService.createTaskQuery().processInstanceId(apply.getProcessInstanceId()).taskAssignee(user.getId()).singleResult();
            flowableService.approveTask2(task,"编辑后提交",apply.getId(),user, FormUtils.SETTLE_AMOUNT_ADJUST_APPLICATION);
        }
        apply.setStatus(BondApplyConstant.APPLYSTATUS_ONE);
        settlementApplyDao.save(apply);
    }

    //删除申请
    @Transactional(rollbackFor = Exception.class)
    public void deleteSettlementAmountApply(String id){
        logger.info(">>>>>>>>>>>>>deleteSettlementAmountApply  id:{}",id);
        User user = UserUtils.getUser();
        String userName= user.getUserName();
        //修改申请状态
        SettlementAmountAdjustmentApply apply=settlementApplyDao.getByApplyId(id);
        if(com.sifang.modules.sunshine.SystemSetting.utils.StringUtil.equalsAny(apply.getStatus(), BondApplyConstant.APPLYSTATUS_ONE,BondApplyConstant.APPLYSTATUS_TWO,BondApplyConstant.APPLYSTATUS_THREE)){
            throw new RuntimeException("申请状态不允许删除!");
        }
        apply.setStatus(BondApplyConstant.APPLYSTATUS_FOUR);
        settlementApplyDao.save(apply);
        //删除流程
        flowableService.deleteApplication(apply.getId(),apply.getProcessInstanceId(),userName,apply.getStatus(),FormUtils.SETTLE_AMOUNT_ADJUST_APPLICATION);
    }

    //审核通过
    @Transactional(rollbackFor = Exception.class)
    public void examineSettlementAmountApplyApprove(String id,String taskId,String content){
        logger.info(">>>>>>>>>>>>>examineSettlementAmountApplyApprove  id:{},task:{}",id,taskId);
        User user = UserUtils.getUser();
        SettlementAmountAdjustmentApply apply=settlementApplyDao.getByApplyId(id);
        Task task = taskService.createTaskQuery().processInstanceId(apply.getProcessInstanceId()).taskAssignee(user.getId()).singleResult();
        flowableService.approveTask2(task,content,apply.getId(),user, FormUtils.SETTLE_AMOUNT_ADJUST_APPLICATION);
    }

    //驳回
    @Transactional(rollbackFor = Exception.class)
    public void rejectSettlementAmountTask(String id,String taskId,String content){
        logger.info(">>>>>>>>>>>>>rejectSettlementAmountTask  id:{},task:{}",id,taskId);
        User user = UserUtils.getUser();
        SettlementAmountAdjustmentApply apply=settlementApplyDao.getByApplyId(id);
        apply.setContent(content);
        apply.setExamineOpinion(content);
        settlementApplyDao.save(apply);

        Task task = taskService.createTaskQuery().processInstanceId(apply.getProcessInstanceId()).taskAssignee(user.getId()).singleResult();
        flowableService.rejectTask2(task,content,id,user,FormUtils.SETTLE_AMOUNT_ADJUST_APPLICATION,apply.getCreateBy());

    }

    @Transactional(rollbackFor = Exception.class)
    public void saveSettlementAmountApplyFromReturn(CrmSupplyMaterialReturnOrder returnOrder, BigDecimal amount){
        logger.info(">>>>>>>>>>>>>>>saveSettlementAmountApplyFromReturn  returnOrder:{}",returnOrder);
        SettlementAmountAdjustmentApply apply = new SettlementAmountAdjustmentApply();
        apply.setApplyNumber(returnOrder.getNumber());
        apply.setTraderId(returnOrder.getTraderId());
        apply.setAdjustType(BondApplyConstant.ZXTH);
        apply.setAmount(amount);
        apply.setRemarks(returnOrder.getReturnRemark());
        apply.setCreateTime(returnOrder.getConfirmTime());
        apply.setFinishTime(apply.getCreateTime());
        apply.setId(IdGen.uuid());
        apply.setStatus(BondApplyConstant.APPLYSTATUS_THREE);
        settlementApplyDao.save(apply);

        //增加结算额
        CrmTraderAccount account= accountDao.getAccountByTraderId(apply.getTraderId());
        logger.info(">>>>>>>>>>saveSettlementAmountApplyFromReturn---->>>>adjustAmount:{},account:{}",amount,account.getSettleAmount());
       // account.setSettleAmount(account.getSettleAmount().add(amount));
        logger.info(">>>>>>>>>>saveSettlementAmountApplyFromReturn---->>>>account:{}",account.getSettleAmount());
       // accountDao.save(account);
        SQLQuery sql = accountDao.getSession()
                .createSQLQuery("UPDATE crm_trader_account SET settle_amount = settle_amount+:amount   WHERE trader_id =:id  AND settle_amount =:availa ");
        sql.setParameter("amount", amount);
        sql.setParameter("id", apply.getTraderId());
        sql.setParameter("availa", account.getSettleAmount());
        int count = sql.executeUpdate();
        if(count<1){
            throw  new IllegalArgumentException("账户信息已变动，请重新操作");
        }

    }

    @Transactional(rollbackFor = Exception.class)
    public void saveSettlementAmountApplyFromDeliver(CrmSupplyMaterialDeliverOrder order, BigDecimal amount){
        logger.info(">>>>>>>>>>>>>>>saveSettlementAmountApplyFromDeliver  returnOrder:{}",order);
        SettlementAmountAdjustmentApply apply = new SettlementAmountAdjustmentApply();
        apply.setApplyNumber(order.getNumber());
        apply.setTraderId(order.getTraderId());
        apply.setAdjustType(BondApplyConstant.ZXPH);
        apply.setAmount(amount);
        apply.setRemarks(order.getRemarks());
        apply.setCreateTime(order.getDeliverTime());
        apply.setFinishTime(apply.getCreateTime());

        apply.setId(IdGen.uuid());
        apply.setStatus(BondApplyConstant.APPLYSTATUS_THREE);
        settlementApplyDao.save(apply);

        //扣减结算额
        CrmTraderAccount account= accountDao.getAccountByTraderId(apply.getTraderId());
      /*  logger.info(">>>>>>>>>>saveSettlementAmountApplyFromDeliver---->>>>adjustAmount:{}",amount);
        CrmTraderAccount account= accountDao.getAccountByTraderId(apply.getTraderId());
        account.setSettleAmount(account.getSettleAmount().subtract(amount));
        accountDao.save(account);*/
        logger.info(">>>>>>>>>>saveSettlementAmountApplyFromDeliver---->>>>account:{}",account.getSettleAmount());

        SQLQuery sql = accountDao.getSession()
                .createSQLQuery("UPDATE crm_trader_account SET settle_amount = settle_amount-:amount   WHERE trader_id =:id  AND settle_amount =:availa ");
        sql.setParameter("amount", amount);
        sql.setParameter("id", apply.getTraderId());
        sql.setParameter("availa", account.getSettleAmount());
        int count = sql.executeUpdate();
        if(count<1){
            throw  new IllegalArgumentException("账户信息已变动，请重新操作");
        }
    }

    public List<Record> getEntryList(String traderId){
        List<Record> list= settlementApplyDao.getEntryList(traderId);
        return list;
    }
}
