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.*;
import com.yh.saas.plugin.yiliangyiyun.exception.YException;
import com.yh.saas.plugin.yiliangyiyun.exception.YExceptionEnum;
import com.yh.saas.plugin.yiliangyiyun.mapper.SalesDeliveryReportMapper;
import com.yh.saas.plugin.yiliangyiyun.service.*;
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 SalesDeliveryReportServiceImpl extends ServiceImpl<SalesDeliveryReportMapper, SalesDeliveryReport> implements ISalesDeliveryReportService {
    @Autowired
    private INewWorkflowService workflowService;
    @SofaReference
    private ICommonRoleResourceService roleResourceService;
    @Autowired
    private IContractManagementInfoService contractManagementInfoService;
    @Autowired
    private ISaleOrderService saleOrderService;
    @Autowired
    private IWarehouseInOutInfoService warehouseInOutInfoService;

    /**
     * 销售出库统计列表
     *
     * @param salesDeliveryReport
     */
    @Override
    public Page<SalesDeliveryReport> selectSalesDeliveryReport(SalesDeliveryReport salesDeliveryReport) {
        Map<String, Object> pageView = new HashMap<>();
        pageView.put("startRecord", (salesDeliveryReport.getCurrentPage() - 1)
                * salesDeliveryReport.getPageSize());
        List<String> businessKeys = null;
        if ("1".equals(salesDeliveryReport.getSearchType())) {
            businessKeys = workflowService.getTaskBusinessKeysByCode("SALE-RECEIPT-REPORT");
        }
        List<String> statusSet = new ArrayList<>();
        List<String> resourceIdList = this.getResourceIdList();
        if (resourceIdList.contains("saleOutReport-Edit")) { // 填写，提交    权限做完以后替换
            List<String> statusList = Lists.newArrayList(StatusEnum.PUR_RETURN.getFlag());
            statusSet.addAll(statusList);
        }
        //公司id
        pageView.put("compId", salesDeliveryReport.getCompId());
        pageView.put("searchKeyWord", salesDeliveryReport.getSearchKeyWord());
        pageView.put("searchType", salesDeliveryReport.getSearchType());
        pageView.put("pageSize", salesDeliveryReport.getPageSize());
        pageView.put("currentPage", salesDeliveryReport.getCurrentPage());
        pageView.put("contractNo", salesDeliveryReport.getContractNo());
        pageView.put("roleFlag", salesDeliveryReport.getRoleFlag());
        pageView.put("businessKeys", businessKeys);
        pageView.put("statusSet", statusSet);
        // 查询销售出库总数
        Integer dataCount = baseMapper.getCountByCondition(pageView);
        List<SalesDeliveryReport> dataList = baseMapper.getListByCondition(pageView);
        if (!CollectionUtils.isEmpty(dataList)) {
            dataList.forEach(salesDeliveryReport1 -> {

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

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

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

    /**
     * 开发票
     *
     * @param salesDeliveryReport
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String openInvoice(SalesDeliveryReport salesDeliveryReport) {
        //查询销售出库报表
        SalesDeliveryReport salesDeliveryReport1 = this.selectById(salesDeliveryReport.getId());
        if (salesDeliveryReport1 != null) {
            //更改已开发票
            salesDeliveryReport1.setAlreadyInvoice(salesDeliveryReport1.getAlreadyInvoice() + salesDeliveryReport1.getAlreadyInvoice());
            //更改销售出库报表信息
            this.updateById(salesDeliveryReport1);
            return "OK";
        }
        return "NG";
    }

    /**
     * 批量开发票
     *
     * @param salesDeliveryReport
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String openInvoiceList(SalesDeliveryReport salesDeliveryReport) {
        List<SalesDeliveryReport> salesDeliveryReportList = salesDeliveryReport.getSalesDeliveryReportList();
        //批量
        if (!CollectionUtils.isEmpty(salesDeliveryReportList)) {
            for (SalesDeliveryReport salesDeliveryReport1 : salesDeliveryReportList) {
                //已开发票金额等于已收金额
                salesDeliveryReport1.setAlreadyInvoice(salesDeliveryReport1.getCollectionEdPayable());
                this.updateById(salesDeliveryReport1);
            }
        }
        return "ok";
    }

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

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

                this.updateById(salesDeliveryReport);
                workflowService.activateInstance(salesDeliveryReport.getWorkflowId(), salesDeliveryReport.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 salesDeliveryReport
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String examineSalesDeliveryReport(SalesDeliveryReport salesDeliveryReport) {
        List<SalesDeliveryReport> salesDeliveryReportList = salesDeliveryReport.getSalesDeliveryReportList();
        //批量
        if (!CollectionUtils.isEmpty(salesDeliveryReportList)) {
            for (SalesDeliveryReport salesDeliveryReport1 : salesDeliveryReportList) {
                //统计审核
                if ("1".equals(salesDeliveryReport.getRoleFlag())) {
                    salesDeliveryReport1.setStatus(StatusEnum.STATISTICAL_AUDIT.getName());
                    salesDeliveryReport1.setStatusFlag(StatusEnum.STATISTICAL_AUDIT.getFlag());
                }
                //财务通过
                else if ("2".equals(salesDeliveryReport.getRoleFlag()) && "1".equals(salesDeliveryReport.getFlag())) {
                    salesDeliveryReport1.setStatus(StatusEnum.FINANCIAL_AUDIT.getName());
                    salesDeliveryReport1.setStatusFlag(StatusEnum.FINANCIAL_AUDIT.getFlag());
                }
                //财务驳回
                else if ("2".equals(salesDeliveryReport.getRoleFlag()) && "2".equals(salesDeliveryReport.getFlag())) {
                    salesDeliveryReport1.setStatus(StatusEnum.FINANCIAL_REJECTION.getName());
                    salesDeliveryReport1.setStatusFlag(StatusEnum.FINANCIAL_REJECTION.getFlag());
                }
                //决策人同意
                else if ("3".equals(salesDeliveryReport.getRoleFlag()) && "1".equals(salesDeliveryReport.getFlag())) {
                    salesDeliveryReport1.setStatus(StatusEnum.MAKER_AUDIT.getName());
                    salesDeliveryReport1.setStatusFlag(StatusEnum.MAKER_AUDIT.getFlag());
                }
                //决策人驳回
                else {
                    salesDeliveryReport1.setStatus(StatusEnum.MAKER_REJECTION.getName());
                    salesDeliveryReport1.setStatusFlag(StatusEnum.MAKER_REJECTION.getFlag());
                }
                this.updateById(salesDeliveryReport1);
            }
        }
        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;
            //查销售出库报表
            List<SalesDeliveryReport> salesDeliveryReportList = this.selectList(new EntityWrapper<SalesDeliveryReport>()
                    .eq("contract_no", contractManagementInfo.getContractNo())
                    .eq("delete_flag", "0"));
            if (!CollectionUtils.isEmpty(salesDeliveryReportList)) {
                for (SalesDeliveryReport salesDeliveryReport : salesDeliveryReportList) {
                    money = money + salesDeliveryReport.getCollectionNotPayable();
                }
                //有未收金额
                if (money > 0) {
                    contractManagementInfo.setReportStatus("待结算");
                } else {
                    contractManagementInfo.setReportStatus("已结算");
                }
            }
        }
        return contractManagementInfoList;
    }

    /**
     * 查销售订单表
     *
     * @param salesDeliveryReport
     */
    @Override
    public SaleOrder selectOrder(SalesDeliveryReport salesDeliveryReport) {
        SaleOrder saleOrder = saleOrderService.selectOne(new EntityWrapper<SaleOrder>()
                .eq("contract_no", salesDeliveryReport.getContractNo())
                .eq("delete_flag", "0"));
        if (saleOrder != null) {
            //定义已入库量
            Float stockOutQuantity = 0.0f;
            //查询入库量
            List<WarehouseInOutInfo> warehouseInOutInfoList = warehouseInOutInfoService.selectList(new EntityWrapper<WarehouseInOutInfo>()
                    .eq("contract_no", saleOrder.getContractNo())
                    .eq("task_type", "出库任务")
                    .eq("status_flag", "3")
                    .eq("delete_flag", "0"));
            if (!CollectionUtils.isEmpty(warehouseInOutInfoList)) {
                for (WarehouseInOutInfo warehouseInOutInfo : warehouseInOutInfoList) {
                    stockOutQuantity = stockOutQuantity + Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight()));
                }
            }
            saleOrder.setStockOutQuantity(stockOutQuantity);
        }
        return saleOrder;
    }

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