package com.yh.saas.plugin.yiliangyiyun.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.Lists;
import com.winsea.svc.base.security.util.AuthSecurityUtils;
import com.winsea.svc.base.workflow.entity.Workflow;
import com.yh.saas.common.support.util.IdGenerator;
import com.yh.saas.plugin.base.service.ICommonBillOperateHisService;
import com.yh.saas.plugin.yiliangyiyun.constant.NumberConstant;
import com.yh.saas.plugin.yiliangyiyun.constant.StatusEnum;
import com.yh.saas.plugin.yiliangyiyun.entity.NonContractExpenses;
import com.yh.saas.plugin.yiliangyiyun.entity.ReveExpeInfo;
import com.yh.saas.plugin.yiliangyiyun.exception.YException;
import com.yh.saas.plugin.yiliangyiyun.exception.YExceptionEnum;
import com.yh.saas.plugin.yiliangyiyun.mapper.NonContractExpensesMapper;
import com.yh.saas.plugin.yiliangyiyun.service.INewWorkflowService;
import com.yh.saas.plugin.yiliangyiyun.service.INonContractExpensesService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.yh.saas.plugin.yiliangyiyun.service.IReveExpeInfoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 合同外费用 服务实现类
 * </p>
 *
 * @author Gdc
 * @since 2022-03-03
 */
@Service
public class NonContractExpensesServiceImpl extends ServiceImpl<NonContractExpensesMapper, NonContractExpenses> implements INonContractExpensesService {
    @Autowired
    private INewWorkflowService workflowService;
    @Autowired
    private IReveExpeInfoService reveExpeInfoService;
    @Autowired
    private ICommonBillOperateHisService billOperateHisService;


    @Override
    public String addInfo(NonContractExpenses nonContractExpenses) {
        nonContractExpenses.setId(IdGenerator.generateUUID());
        //经营费用
        if("1".equals(nonContractExpenses.getExpenseType())){
            nonContractExpenses.setPurpose("经营费用");
        }
        //仓库费用
        else{
            nonContractExpenses.setPurpose(nonContractExpenses.getWarehouseName());
        }
        //收款
        if ("1".equals(nonContractExpenses.getReexTypeKey())){
            nonContractExpenses.setStatusFlag(StatusEnum.RECEIVED.getFlag());
            nonContractExpenses.setStatus(StatusEnum.RECEIVED.getName());
            this.insert(nonContractExpenses);
            //收款时生成收支明细
            ReveExpeInfo reveExpeInfo=new ReveExpeInfo();
            reveExpeInfo.setId(IdGenerator.generateUUID());
            reveExpeInfo.setCompId(nonContractExpenses.getCompId());
            //经营费用
            if("1".equals(nonContractExpenses.getExpenseType())){
                reveExpeInfo.setReexType("经营收入");
                reveExpeInfo.setReexTypeKey("5");
            }
            //仓库费用
            else{
                reveExpeInfo.setReexType("仓库收入");
                reveExpeInfo.setReexTypeKey("3");
            }
            reveExpeInfo.setAmountMoney(nonContractExpenses.getAmountMoney());
            reveExpeInfo.setExpenseName(nonContractExpenses.getExpenseName());
            reveExpeInfo.setExpenseRemarks(nonContractExpenses.getRemarks());
            reveExpeInfoService.insert(reveExpeInfo);
        }
        //付款
        else
        {
            nonContractExpenses.setStatusFlag(StatusEnum.PENDING_PAYMENT.getFlag());
            nonContractExpenses.setStatus(StatusEnum.PENDING_PAYMENT.getName());
            this.insert(nonContractExpenses);
            // 插入操作历史
            String staffName = this.billOperateHisService.getStaffAndName();
            // 插入操作历史
            this.billOperateHisService.saveBillOperateHis(nonContractExpenses.getId(), NumberConstant.CONSTANT_EXE_COST, staffName, null,
                    "请款"+"("+nonContractExpenses.getAmountMoney()+")", null, nonContractExpenses.getRemarks());
            boolean isStartWorkflow = StringUtils.isBlank(nonContractExpenses.getWorkflowId());
            // 不是退回的单子
            if (isStartWorkflow) {
                Workflow workflow = workflowService
                        .findLatestWorkflowByBusinessCodeByApp(nonContractExpenses.getCompId(), "EX-CONTRACT-APPROVE");
                // 没配置审核流程，直接结束并处理信息
                if (workflow == null) {
                    throw new YException(YExceptionEnum.PURCHASE_ORDER_ERROR);
                }
                // 开启审核流
                else {
                    // 设置状态 已提交审核
                    nonContractExpenses.setWorkflowId(workflow.getId());
                    this.updateById(nonContractExpenses);
                    workflowService.startInstance(workflow.getId(), nonContractExpenses.getId());
                }
            }
            // 退回的单子 再启用
            else {
                this.updateById(nonContractExpenses);
                workflowService.activateInstance(nonContractExpenses.getWorkflowId(), nonContractExpenses.getId());
            }
        }
        return "ok";
    }

    @Override
    public String editInfo(NonContractExpenses nonContractExpenses) {
        this.updateById(nonContractExpenses);
        return "ok";
    }

    @Override
    public String payment(NonContractExpenses nonContractExpenses) {
        nonContractExpenses.setStatusFlag(StatusEnum.PAID.getFlag());
        nonContractExpenses.setStatus(StatusEnum.PAID.getName());
        //付款时生成收支明细
        ReveExpeInfo reveExpeInfo=new ReveExpeInfo();
        reveExpeInfo.setId(IdGenerator.generateUUID());
        reveExpeInfo.setCompId(nonContractExpenses.getCompId());
        //经营费用
        if("1".equals(nonContractExpenses.getExpenseType())){
            reveExpeInfo.setReexType("经营支出");
            reveExpeInfo.setReexTypeKey("6");
        }
        //仓库费用
        else{
            reveExpeInfo.setReexType("仓库支出");
            reveExpeInfo.setReexTypeKey("4");
        }
        reveExpeInfo.setAmountMoney(nonContractExpenses.getAmountMoney());
        reveExpeInfo.setExpenseName(nonContractExpenses.getExpenseName());
        reveExpeInfo.setExpenseRemarks(nonContractExpenses.getRemarks());
        reveExpeInfoService.insert(reveExpeInfo);
        this.updateById(nonContractExpenses);
        // 插入操作历史
        String staffName = this.billOperateHisService.getStaffAndName();
        // 插入操作历史
        this.billOperateHisService.saveBillOperateHis(nonContractExpenses.getId(), NumberConstant.CONSTANT_EXE_COST, staffName, null,
                "付款"+"("+nonContractExpenses.getAmountMoney()+")", null, "");
        return "ok";
    }

    @Override
    public NonContractExpenses getInfo(String id) {
        NonContractExpenses nonContractExpenses=this.selectById(id);
        return nonContractExpenses;
    }

    @Override
    public Page<NonContractExpenses> selectInfo(NonContractExpenses nonContractExpenses) {
        Map<String, Object> pageView = new HashMap<>();
        pageView.put("startRecord", (nonContractExpenses.getCurrentPage() - 1)
                * nonContractExpenses.getPageSize());
        //  公司ID
        pageView.put("compId", AuthSecurityUtils.getCurrentUserInfo().getCompId());
        pageView.put("searchType", nonContractExpenses.getSearchType());
        pageView.put("searchKeyWord", nonContractExpenses.getSearchKeyWord());
        pageView.put("startDate", nonContractExpenses.getStartDate());
        pageView.put("endDate", nonContractExpenses.getEndDate());
        pageView.put("pageSize", nonContractExpenses.getPageSize());
        pageView.put("currentPage", nonContractExpenses.getCurrentPage());
        // 查询服务商总数
        Integer dataCount = baseMapper.getCountByCondition(pageView);
        List<NonContractExpenses> dataList = baseMapper.getListByCondition(pageView);
        if (!CollectionUtils.isEmpty(dataList)) {
            for (NonContractExpenses nonContractExpenses1:dataList){
                String taskId = "";
                // 只有待审核状态才有taskId
                if (StringUtils.isNotBlank(nonContractExpenses1.getWorkflowId())) {
                    JSONObject jsonObject = workflowService.getActiveTask(Lists.newArrayList(nonContractExpenses1.getWorkflowId()), nonContractExpenses1.getId());
                    taskId = jsonObject.getString("taskId");
                    nonContractExpenses1.setTaskId(taskId);
                }
            }
        }
        Page<NonContractExpenses> page = new Page<>();
        page.setRecords(dataList == null ? Lists.newArrayList() : dataList);
        page.setTotal(dataCount == null ? 0 : dataCount);
        page.setCurrent(nonContractExpenses.getCurrentPage());
        page.setSize(nonContractExpenses.getPageSize());
        return page;
    }

    @Override
    public void deleteInfo(String id) {
        NonContractExpenses nonContractExpenses=this.selectById(id);
        this.deleteById(nonContractExpenses.getId());
    }
}
