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.SalesClosingReport;
import com.yh.saas.plugin.yiliangyiyun.entity.SalesDeliveryReport;
import com.yh.saas.plugin.yiliangyiyun.exception.YException;
import com.yh.saas.plugin.yiliangyiyun.exception.YExceptionEnum;
import com.yh.saas.plugin.yiliangyiyun.mapper.SalesClosingReportMapper;
import com.yh.saas.plugin.yiliangyiyun.service.IContractManagementInfoService;
import com.yh.saas.plugin.yiliangyiyun.service.INewWorkflowService;
import com.yh.saas.plugin.yiliangyiyun.service.ISalesClosingReportService;
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-05
 */
@Service
public class SalesClosingReportServiceImpl extends ServiceImpl<SalesClosingReportMapper, SalesClosingReport> implements ISalesClosingReportService {

    @Autowired
    private INewWorkflowService workflowService;
    @Autowired
    private IContractManagementInfoService contractManagementInfoService;

    @SofaReference
    private ICommonRoleResourceService roleResourceService;


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

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


        // 查询销售订单总数
        Integer dataCount = baseMapper.getCountByCondition(pageView);
        List<SalesClosingReport> dataList = baseMapper.getListByCondition(pageView);
        if (!CollectionUtils.isEmpty(dataList)) {
            dataList.forEach(salesClosingReport1 -> {

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

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

    /**
     * 最终结算价
     *
     * @param salesClosingReport
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String editSalesCloseReport(SalesClosingReport salesClosingReport) {
        boolean one = this.updateById(salesClosingReport);
        if (salesClosingReport.getStatusFlag().equals(StatusEnum.TASK_RETURN.getFlag())) {
            boolean isStartWorkflow = org.apache.commons.lang3.StringUtils.isBlank(salesClosingReport.getWorkflowId());
            // 不是退回的单子
            if (isStartWorkflow) {
                Workflow workflow = workflowService
                        .findLatestWorkflowByBusinessCodeByApp(salesClosingReport.getCompId(), "SALE-CLOSE-REPORT");
                // 没配置审核流程，直接结束并处理信息
                if (workflow == null) {
                    throw new YException(YExceptionEnum.PURCHASE_ORDER_ERROR);
                }
                // 开启审核流
                else {

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

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

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


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

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

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

    }

    /**
     * 审核
     *
     * @param salesClosingReport
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String examine(SalesClosingReport salesClosingReport) {
        List<SalesClosingReport> salesClosingReportList = salesClosingReport.getSalesClosingReportList();
        //批量
        if (!CollectionUtils.isEmpty(salesClosingReportList)) {
            for (SalesClosingReport salesClosingReport1 : salesClosingReportList) {
                //通过
                if (salesClosingReport.getFlag() == 1) {
                    //统计
                    if (salesClosingReport.getRoleFlag() == 1) {
                        salesClosingReport1.setStatusFlag(StatusEnum.STATISTICAL_AUDIT.getFlag());
                        salesClosingReport1.setStatus(StatusEnum.STATISTICAL_AUDIT.getName());
                    }
                    //财务
                    else if (salesClosingReport.getRoleFlag() == 2) {
                        salesClosingReport1.setStatusFlag(StatusEnum.FINANCIAL_AUDIT.getFlag());
                        salesClosingReport1.setStatus(StatusEnum.FINANCIAL_AUDIT.getName());
                    }
                    //决策人
                    else {
                        salesClosingReport1.setStatusFlag(StatusEnum.MAKER_AUDIT.getFlag());
                        salesClosingReport1.setStatus(StatusEnum.MAKER_AUDIT.getName());
                    }
                }
                //驳回
                else {
                    //财务
                    if (salesClosingReport.getRoleFlag() == 2) {
                        salesClosingReport1.setStatusFlag(StatusEnum.FINANCIAL_REJECTION.getFlag());
                        salesClosingReport1.setStatus(StatusEnum.FINANCIAL_REJECTION.getName());
                    }
                    //决策人
                    else {
                        salesClosingReport1.setStatusFlag(StatusEnum.MAKER_REJECTION.getFlag());
                        salesClosingReport1.setStatus(StatusEnum.MAKER_REJECTION.getName());
                    }
                }
                //更改信息
                this.updateById(salesClosingReport1);
            }
        }
        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", "1")
                .eq("delete_flag", "0")
                .orderBy("update_date", false));
        for (ContractManagementInfo contractManagementInfo : contractManagementInfoList) {
            Float money = 0.0f;
            Float collectMoney = 0.0f;
            //查销售平仓报表
            List<SalesClosingReport> salesClosingReportList = this.selectList(new EntityWrapper<SalesClosingReport>()
                    .eq("contract_no", contractManagementInfo.getContractNo())
                    .eq("delete_flag", "0"));
            if (!CollectionUtils.isEmpty(salesClosingReportList)) {
                for (SalesClosingReport salesClosingReport : salesClosingReportList) {
                    money = money + salesClosingReport.getAmountNotPayable();
                    collectMoney = collectMoney + salesClosingReport.getCollectionNotPayable();
                }
                //有未付/未收金额
                if (money > 0 || collectMoney > 0) {
                    contractManagementInfo.setReportStatus("待结算");
                } else {
                    contractManagementInfo.setReportStatus("已结算");
                }
            }
        }
        return contractManagementInfoList;
    }
}
