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

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
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.*;
import com.yh.saas.plugin.yiliangyiyun.exception.YException;
import com.yh.saas.plugin.yiliangyiyun.exception.YExceptionEnum;
import com.yh.saas.plugin.yiliangyiyun.mapper.ContractCostInfoMapper;
import com.yh.saas.plugin.yiliangyiyun.service.*;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
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-01
 */
@Service
public class ContractCostInfoServiceImpl extends ServiceImpl<ContractCostInfoMapper, ContractCostInfo> implements IContractCostInfoService {

    @Autowired
    private INewWorkflowService workflowService;
    @Autowired
    private IContractManagementInfoService contractManagementInfoService;
    @Autowired
    private IReveExpeInfoService reveExpeInfoService;
    @Autowired
    private ICommonBillOperateHisService billOperateHisService;


    /**
     * 添加
     * @param contractCostInfo
     * @return
     */
    @Override
    public String addInfo(ContractCostInfo contractCostInfo) {
        contractCostInfo.setId(IdGenerator.generateUUID());
        //收款
        if ("1".equals(contractCostInfo.getType())){
            contractCostInfo.setStatusFlag(StatusEnum.RECEIVED.getFlag());
            contractCostInfo.setStatus(StatusEnum.RECEIVED.getName());
            //收款时生成收支明细
            ReveExpeInfo reveExpeInfo=new ReveExpeInfo();
            reveExpeInfo.setId(IdGenerator.generateUUID());
            reveExpeInfo.setCompId(contractCostInfo.getCompId());
            reveExpeInfo.setReexType("合同收入");
            reveExpeInfo.setReexTypeKey("1");
            reveExpeInfo.setAmountMoney(contractCostInfo.getCostPrice());
            reveExpeInfo.setExpenseName(contractCostInfo.getCostName());
            String remark="";
            if ("1".equals(contractCostInfo.getCostType())){
                remark="粮款";
            }
            else {
                remark="非粮款";
            }
            ContractManagementInfo contractManagementInfo=contractManagementInfoService.selectOne(new EntityWrapper<ContractManagementInfo>()
                .eq("comp_id",contractCostInfo.getCompId())
                .eq("contract_no",contractCostInfo.getContractNo()));
            reveExpeInfo.setExpenseRemarks(remark+"  "+contractCostInfo.getContractNo()+"  "+contractManagementInfo.getBuyer());
            reveExpeInfoService.insert(reveExpeInfo);
            this.insert(contractCostInfo);
        }
        //付款
        else
        {
            contractCostInfo.setStatusFlag(StatusEnum.PENDING_PAYMENT.getFlag());
            contractCostInfo.setStatus(StatusEnum.PENDING_PAYMENT.getName());
            this.insert(contractCostInfo);
            // 插入操作历史
            String staffName = this.billOperateHisService.getStaffAndName();
            // 插入操作历史
            this.billOperateHisService.saveBillOperateHis(contractCostInfo.getId(), NumberConstant.CONSTANT_COST, staffName, null,
                    "请款"+"("+contractCostInfo.getCostPrice()+")", null, contractCostInfo.getRemark());
            boolean isStartWorkflow = StringUtils.isBlank(contractCostInfo.getWorkflowId());
            // 不是退回的单子
            if (isStartWorkflow) {
                Workflow workflow = workflowService
                        .findLatestWorkflowByBusinessCodeByApp(contractCostInfo.getCompId(), "NON-CONTRACT-APPROVE");
                // 没配置审核流程，直接结束并处理信息
                if (workflow == null) {
                    throw new YException(YExceptionEnum.PURCHASE_ORDER_ERROR);
                }
                // 开启审核流
                else {
                    // 设置状态 已提交审核
                    contractCostInfo.setWorkflowId(workflow.getId());
                    this.updateById(contractCostInfo);
                    workflowService.startInstance(workflow.getId(), contractCostInfo.getId());
                }
            }
            // 退回的单子 再启用
            else {
                this.updateById(contractCostInfo);
                workflowService.activateInstance(contractCostInfo.getWorkflowId(), contractCostInfo.getId());
            }
        }
        return "ok";
    }

    /**
     * 编辑
     * @param contractCostInfo
     * @return
     */
    @Override
    public String editInfo(ContractCostInfo contractCostInfo) {
        this.updateById(contractCostInfo);
        return "ok";
    }

    /**
     * 付款
     * @param contractCostInfo
     * @return
     */
    @Override
    public String payment(ContractCostInfo contractCostInfo) {
        contractCostInfo.setStatusFlag(StatusEnum.PAID.getFlag());
        contractCostInfo.setStatus(StatusEnum.PAID.getName());
        //付款时生成收支明细
        ReveExpeInfo reveExpeInfo=new ReveExpeInfo();
        reveExpeInfo.setId(IdGenerator.generateUUID());
        reveExpeInfo.setReexType("合同支出");
        reveExpeInfo.setReexTypeKey("2");
        reveExpeInfo.setCompId(contractCostInfo.getCompId());
        reveExpeInfo.setAmountMoney(contractCostInfo.getCostPrice());
        reveExpeInfo.setExpenseName(contractCostInfo.getCostName());
        String remark="";
        if ("1".equals(contractCostInfo.getCostType())){
            remark="粮款";
        }
        else {
            remark="非粮款";
        }
        ContractManagementInfo contractManagementInfo=contractManagementInfoService.selectOne(new EntityWrapper<ContractManagementInfo>()
                .eq("comp_id",contractCostInfo.getCompId())
                .eq("contract_no",contractCostInfo.getContractNo()));
        reveExpeInfo.setExpenseRemarks(remark+"  "+contractCostInfo.getContractNo()+"  "+contractManagementInfo.getSeller());
        reveExpeInfoService.insert(reveExpeInfo);
        this.updateById(contractCostInfo);
        // 插入操作历史
        String staffName = this.billOperateHisService.getStaffAndName();
        // 插入操作历史
        this.billOperateHisService.saveBillOperateHis(contractCostInfo.getId(), NumberConstant.CONSTANT_COST, staffName, null,
                "付款"+"("+contractCostInfo.getCostPrice()+")", null, "");
        return "ok";
    }

    /**
     * 查看
     * @param id
     * @return
     */
    @Override
    public ContractCostInfo getInfo(String id) {
        ContractCostInfo contractCostInfo=this.selectById(id);
        return contractCostInfo;
    }

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

    /**
     * 删除
     * @param id
     */
    @Override
    public void deleteInfo(String id) {
        ContractCostInfo contractCostInfo=this.selectById(id);
        this.deleteById(contractCostInfo.getId());

    }
}
