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

import com.alibaba.fastjson.JSONObject;
import com.alipay.sofa.runtime.api.annotation.SofaReference;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.Lists;
import com.winsea.svc.base.base.entity.CommonRoleResource;
import com.winsea.svc.base.base.service.ICommonRoleResourceService;
import com.winsea.svc.base.security.entity.User;
import com.winsea.svc.base.security.util.AuthSecurityUtils;
import com.winsea.svc.base.workflow.entity.Workflow;
import com.yh.saas.plugin.yiliangyiyun.constant.StatusEnum;
import com.yh.saas.plugin.yiliangyiyun.entity.ContractManagementInfo;
import com.yh.saas.plugin.yiliangyiyun.entity.PurchaseClosingReport;
import com.yh.saas.plugin.yiliangyiyun.exception.YException;
import com.yh.saas.plugin.yiliangyiyun.exception.YExceptionEnum;
import com.yh.saas.plugin.yiliangyiyun.mapper.PurchaseClosingReportMapper;
import com.yh.saas.plugin.yiliangyiyun.service.IContractManagementInfoService;
import com.yh.saas.plugin.yiliangyiyun.service.INewWorkflowService;
import com.yh.saas.plugin.yiliangyiyun.service.IPurchaseClosingReportService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.yh.saas.toolkit.workflow.service.IWorkflowService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 采购平仓报表 服务实现类
 * </p>
 *
 * @author Gongdc
 * @since 2021-08-03
 */
@Service
public class PurchaseClosingReportServiceImpl extends ServiceImpl<PurchaseClosingReportMapper, PurchaseClosingReport> implements IPurchaseClosingReportService {

    @Autowired
    private INewWorkflowService workflowService;

    @SofaReference
    private ICommonRoleResourceService roleResourceService;
    @Autowired
    private IContractManagementInfoService contractManagementInfoService;

    /**
     * 采购平仓统计列表
     *
     * @param purchaseClosingReport
     * @return
     */
    @Override
    public Page<PurchaseClosingReport> selectPurchaseOrder(PurchaseClosingReport purchaseClosingReport) {
        Map<String, Object> pageView = new HashMap<>();
        pageView.put("startRecord", (purchaseClosingReport.getCurrentPage() - 1)
                * purchaseClosingReport.getPageSize());
        List<String> businessKeys = null;
        if ("1".equals(purchaseClosingReport.getSearchType())) {
            businessKeys = workflowService.getTaskBusinessKeysByCode("PROCUREMENT-CLOSE-REPORT");
        }
        List<String> statusSet = new ArrayList<>();
        List<String> resourceIdList = this.getResourceIdList();
        if (resourceIdList.contains("procurementCloseReport-Edit")) { // 填写，提交    权限做完以后替换
            List<String> statusList = Lists.newArrayList(StatusEnum.PUR_RETURN.getFlag());
            statusSet.addAll(statusList);
        }

        //公司id
        pageView.put("compId", purchaseClosingReport.getCompId());
        pageView.put("searchKeyWord", purchaseClosingReport.getSearchKeyWord());
        pageView.put("searchType", purchaseClosingReport.getSearchType());
        pageView.put("pageSize", purchaseClosingReport.getPageSize());
        pageView.put("currentPage", purchaseClosingReport.getCurrentPage());
        pageView.put("contractNo", purchaseClosingReport.getContractNo());
        pageView.put("roleFlag", purchaseClosingReport.getRoleFlag());
        pageView.put("statusFlag", purchaseClosingReport.getStatusFlag());
        pageView.put("businessKeys", businessKeys);
        pageView.put("statusSet", statusSet);


        // 查询采购订单总数
        Integer dataCount = baseMapper.getCountByCondition(pageView);
        List<PurchaseClosingReport> dataList = baseMapper.getListByCondition(pageView);

        if (!CollectionUtils.isEmpty(dataList)) {
            dataList.forEach(PurchaseClosingReport1 -> {

                String taskId = "";
                // 只有待审核状态才有taskId
                if (StringUtils.isNotBlank(PurchaseClosingReport1.getWorkflowId())) {
                    JSONObject jsonObject = workflowService.getActiveTask(Lists.newArrayList(PurchaseClosingReport1.getWorkflowId()), PurchaseClosingReport1.getId());
                    taskId = jsonObject.getString("taskId");
                    PurchaseClosingReport1.setTaskId(taskId);
                }
            });

        }
        Page<PurchaseClosingReport> page = new Page<>();
        page.setRecords(dataList == null ? Lists.newArrayList() : dataList);
        page.setTotal(dataCount == null ? 0 : dataCount);
        page.setCurrent(purchaseClosingReport.getCurrentPage());
        page.setSize(purchaseClosingReport.getPageSize());
        return page;
    }

    /**
     * 出纳付款
     *
     * @param purchaseClosingReport
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String payMoney(PurchaseClosingReport purchaseClosingReport) {
        List<PurchaseClosingReport> purchaseClosingReportList = purchaseClosingReport.getPurchaseClosingReportList();
        Float money = purchaseClosingReport.getMoney();
        //付款多条
        if (!CollectionUtils.isEmpty(purchaseClosingReportList)) {
            for (PurchaseClosingReport purchaseClosingReport1 : purchaseClosingReportList) {
                PurchaseClosingReport purchaseClosingReport2 = this.selectById(purchaseClosingReport1.getId());
                //付款金额大于本次循环未付金额
                if (money >= purchaseClosingReport1.getAmountNotPayable()) {
                    money = money - purchaseClosingReport1.getAmountNotPayable();
                    //全部付款
                    purchaseClosingReport1.setStatus(StatusEnum.PUR_PAYaLL.getName());
                    purchaseClosingReport1.setStatusFlag(StatusEnum.PUR_PAYaLL.getFlag());
                    purchaseClosingReport1.setPaymentDate(purchaseClosingReport.getPaymentDate());
                    purchaseClosingReport1.setPaymentScreenshot(purchaseClosingReport2.getPaymentScreenshot() != null ? purchaseClosingReport2.getPaymentScreenshot() + '$' + purchaseClosingReport.getPaymentScreenshot() : purchaseClosingReport.getPaymentScreenshot());
                    purchaseClosingReport1.setAmountEdPayable(purchaseClosingReport1.getAmountEdPayable() + purchaseClosingReport1.getAmountNotPayable());
                    purchaseClosingReport1.setAmountNotPayable(0.0f);
                    this.updateById(purchaseClosingReport1);
                } else if (money > 0) {
                    Float moneyTmp = money - purchaseClosingReport1.getAmountNotPayable();
                    //部分付款
                    purchaseClosingReport1.setStatus(StatusEnum.PUR_PAY.getName());
                    purchaseClosingReport1.setStatusFlag(StatusEnum.PUR_PAY.getFlag());
                    purchaseClosingReport1.setPaymentDate(purchaseClosingReport.getPaymentDate());
                    purchaseClosingReport1.setPaymentScreenshot(purchaseClosingReport2.getPaymentScreenshot() != null ? purchaseClosingReport2.getPaymentScreenshot() + '$' + purchaseClosingReport.getPaymentScreenshot() : purchaseClosingReport.getPaymentScreenshot());
                    purchaseClosingReport1.setAmountEdPayable(purchaseClosingReport1.getAmountEdPayable() + money);
                    purchaseClosingReport1.setAmountNotPayable(purchaseClosingReport1.getAmountNotPayable() - money);
                    this.updateById(purchaseClosingReport1);
                    money = moneyTmp;
                } else {
                    break;
                }
            }
        }
        return "OK";
    }

    /**
     * 出纳收款
     *
     * @param purchaseClosingReport
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String collectMoney(PurchaseClosingReport purchaseClosingReport) {
        List<PurchaseClosingReport> purchaseClosingReportList = purchaseClosingReport.getPurchaseClosingReportList();
        Float money = purchaseClosingReport.getMoney();
        //收款多条
        if (!CollectionUtils.isEmpty(purchaseClosingReportList)) {
            for (PurchaseClosingReport purchaseClosingReport1 : purchaseClosingReportList) {
                PurchaseClosingReport purchaseClosingReport2 = this.selectById(purchaseClosingReport1.getId());
                //收款金额大于本次循环未收金额
                if (money >= purchaseClosingReport1.getCollectionNotPayable()) {
                    money = money - purchaseClosingReport1.getCollectionNotPayable();
                    //全部收款
                    purchaseClosingReport1.setStatus(StatusEnum.PUR_COLLECTaLL.getName());
                    purchaseClosingReport1.setStatusFlag(StatusEnum.PUR_COLLECTaLL.getFlag());
                    purchaseClosingReport1.setCollectionDate(purchaseClosingReport.getCollectionDate());
                    purchaseClosingReport1.setCollectionScreenshot(purchaseClosingReport2.getCollectionScreenshot() != null ? purchaseClosingReport2.getCollectionScreenshot() + '$' + purchaseClosingReport.getCollectionScreenshot() : purchaseClosingReport.getCollectionScreenshot());
                    purchaseClosingReport1.setCollectionEdPayable(purchaseClosingReport1.getCollectionEdPayable() + purchaseClosingReport1.getCollectionNotPayable());
                    purchaseClosingReport1.setCollectionNotPayable(0.0f);
                    this.updateById(purchaseClosingReport1);
                } else if (money > 0) {
                    Float moneyTmp = money - purchaseClosingReport1.getCollectionNotPayable();
                    //部分收款
                    purchaseClosingReport1.setStatus(StatusEnum.PUR_COLLECT.getName());
                    purchaseClosingReport1.setStatusFlag(StatusEnum.PUR_COLLECT.getFlag());
                    purchaseClosingReport1.setCollectionDate(purchaseClosingReport.getCollectionDate());
                    purchaseClosingReport1.setCollectionScreenshot(purchaseClosingReport2.getCollectionScreenshot() != null ? purchaseClosingReport2.getCollectionScreenshot() + '$' + purchaseClosingReport.getCollectionScreenshot() : purchaseClosingReport.getCollectionScreenshot());
                    purchaseClosingReport1.setCollectionEdPayable(purchaseClosingReport1.getCollectionEdPayable() + money);
                    purchaseClosingReport1.setCollectionNotPayable(purchaseClosingReport1.getCollectionNotPayable() - money);
                    this.updateById(purchaseClosingReport1);
                    money = moneyTmp;
                } else {
                    break;
                }
            }
        }
        return "OK";
    }


    /**
     * 编辑采购平仓统计
     *
     * @param purchaseClosingReport
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String editProcurementReceiptReport(PurchaseClosingReport purchaseClosingReport) {
        boolean one = this.updateById(purchaseClosingReport);

        if (purchaseClosingReport.getStatusFlag().equals(StatusEnum.TASK_RETURN.getFlag())) {
            boolean isStartWorkflow = org.apache.commons.lang3.StringUtils.isBlank(purchaseClosingReport.getWorkflowId());
            // 不是退回的单子
            if (isStartWorkflow) {
                Workflow workflow = workflowService
                        .findLatestWorkflowByBusinessCodeByApp(purchaseClosingReport.getCompId(), "PROCUREMENT-CLOSE-REPORT");
                // 没配置审核流程，直接结束并处理信息
                if (workflow == null) {
                    throw new YException(YExceptionEnum.PURCHASE_ORDER_ERROR);
                }
                // 开启审核流
                else {

                    // 设置状态 已提交审核
                    purchaseClosingReport.setWorkflowId(workflow.getId());
                    this.updateById(purchaseClosingReport);
                    workflowService.startInstance(workflow.getId(), purchaseClosingReport.getId());
                }
            }
            // 退回的单子 再启用
            else {

                this.updateById(purchaseClosingReport);
                workflowService.activateInstance(purchaseClosingReport.getWorkflowId(), purchaseClosingReport.getId());
            }
        }
        if (one) {
            return "OK";
        } else {
            return "NG";
        }
    }


    private List<String> getResourceIdList() {
        User currentUser = AuthSecurityUtils.getCurrentUserInfo();
        // 当前登录人主要角色
        return roleResourceService.getBindResourcesByUserId(currentUser.getUserId()).stream()
                .map(CommonRoleResource::getResourceId).collect(Collectors.toList());

    }

    /**
     * 审核
     *
     * @param purchaseClosingReport
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String examine(PurchaseClosingReport purchaseClosingReport) {
        List<PurchaseClosingReport> purchaseClosingReportList = purchaseClosingReport.getPurchaseClosingReportList();
        //批量
        if (!CollectionUtils.isEmpty(purchaseClosingReportList)) {
            for (PurchaseClosingReport purchaseClosingReport1 : purchaseClosingReportList) {
                //通过
                if (purchaseClosingReport.getFlag() == 1) {
                    //统计
                    if (purchaseClosingReport.getRoleFlag() == 1) {
                        purchaseClosingReport1.setStatusFlag(StatusEnum.STATISTICAL_AUDIT.getFlag());
                        purchaseClosingReport1.setStatus(StatusEnum.STATISTICAL_AUDIT.getName());
                    }
                    //财务
                    else if (purchaseClosingReport.getRoleFlag() == 2) {
                        purchaseClosingReport1.setStatusFlag(StatusEnum.FINANCIAL_AUDIT.getFlag());
                        purchaseClosingReport1.setStatus(StatusEnum.FINANCIAL_AUDIT.getName());
                    }
                    //决策人
                    else {
                        purchaseClosingReport1.setStatusFlag(StatusEnum.MAKER_AUDIT.getFlag());
                        purchaseClosingReport1.setStatus(StatusEnum.MAKER_AUDIT.getName());
                    }
                }
                //驳回
                else {
                    //财务
                    if (purchaseClosingReport.getRoleFlag() == 2) {
                        purchaseClosingReport1.setStatusFlag(StatusEnum.FINANCIAL_REJECTION.getFlag());
                        purchaseClosingReport1.setStatus(StatusEnum.FINANCIAL_REJECTION.getName());
                    }
                    //决策人
                    else {
                        purchaseClosingReport1.setStatusFlag(StatusEnum.MAKER_REJECTION.getFlag());
                        purchaseClosingReport1.setStatus(StatusEnum.MAKER_REJECTION.getName());
                    }
                }
                //更改信息
                this.updateById(purchaseClosingReport1);
            }
        }
        return "OK";
    }

    /**
     * 合同编号下拉列表
     *
     * @param compId
     */
    @Override
    public List<ContractManagementInfo> selectContractNoList(String compId) {
        //查采购合同
        List<ContractManagementInfo> contractManagementInfoList = contractManagementInfoService.selectList(new EntityWrapper<ContractManagementInfo>()
                .eq("comp_id", compId)
                .eq("contract_type", "2")
                .eq("delete_flag", "0")
                .orderBy("update_date", false));
        for (ContractManagementInfo contractManagementInfo : contractManagementInfoList) {
            Float money = 0.0f;
            Float collectMoney = 0.0f;
            //查采购平仓报表
            List<PurchaseClosingReport> purchaseClosingReportList = this.selectList(new EntityWrapper<PurchaseClosingReport>()
                    .eq("contract_no", contractManagementInfo.getContractNo())
                    .eq("delete_flag", "0"));
            if (!CollectionUtils.isEmpty(purchaseClosingReportList)) {
                for (PurchaseClosingReport purchaseClosingReport : purchaseClosingReportList) {
                    money = money + purchaseClosingReport.getAmountNotPayable();
                    collectMoney = collectMoney + purchaseClosingReport.getCollectionNotPayable();
                }
                //有未付/未收金额
                if (money > 0 || collectMoney > 0) {
                    contractManagementInfo.setReportStatus("待结算");
                } else {
                    contractManagementInfo.setReportStatus("已结算");
                }
            }
        }
        return contractManagementInfoList;
    }

    /**
     * 查看
     *
     * @param id
     * @return
     */
    @Override
    public PurchaseClosingReport getInfo(String id) {
        PurchaseClosingReport purchaseClosingReport = this.selectById(id);
        String taskId = "";
        // 只有待审核状态才有taskId
        if (StringUtils.isNotBlank(purchaseClosingReport.getWorkflowId())) {
            JSONObject jsonObject = workflowService.getActiveTask(Lists.newArrayList(purchaseClosingReport.getWorkflowId()), purchaseClosingReport.getId());
            taskId = jsonObject.getString("taskId");
            purchaseClosingReport.setTaskId(taskId);
        }
        return purchaseClosingReport;
    }
}
