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.yh.saas.plugin.yiliangyiyun.constant.StatusEnum;
import com.yh.saas.plugin.yiliangyiyun.entity.*;
import com.yh.saas.plugin.yiliangyiyun.entity.view.BiViewInfo;
import com.yh.saas.plugin.yiliangyiyun.mapper.StockSaleReceiptReportMapper;
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.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 现货销售出库报表 服务实现类
 * </p>
 *
 * @author Gdc
 * @since 2021-09-22
 */
@Service
public class StockSaleReceiptReportServiceImpl extends ServiceImpl<StockSaleReceiptReportMapper, StockSaleReceiptReport> implements IStockSaleReceiptReportService {

    @Autowired
    private INewWorkflowService workflowService;
    @SofaReference
    private ICommonRoleResourceService roleResourceService;
    @Autowired
    private IContractManagementInfoService contractManagementInfoService;
    @Autowired
    private IWarehouseInOutInfoService warehouseInOutInfoService;
    @Autowired
    private IContractGoodsInfoService contractGoodsInfoService;
    @Autowired
    private ITranTaskInfoService tranTaskInfoService;
    @Autowired
    private ITranProcessInfoService tranProcessInfoService;
    @Autowired
    private ITranCarInfoService tranCarInfoService;
    /**
     * 销售出库统计
     *
     * @param stockSaleReceiptReport
     * @return
     */
    @Override
    public Page<StockSaleReceiptReport> selectSaleOrder(StockSaleReceiptReport stockSaleReceiptReport) {
        Map<String, Object> pageView = new HashMap<>();
        pageView.put("startRecord", (stockSaleReceiptReport.getCurrentPage() - 1)
                * stockSaleReceiptReport.getPageSize());
//        List<String> businessKeys = null;
//        if ("1".equals(stockSaleReceiptReport.getSearchType())) {
//            businessKeys = workflowService.getTaskBusinessKeysByCode("SALE-RECEIPT-REPORT");
//        }
//        List<String> statusSet = new ArrayList<>();
//        List<String> resourceIdList = this.getResourceIdList();
//        if (resourceIdList.contains("procurementStockInReport-Edit")) { // 填写，提交    权限做完以后替换
//            List<String> statusList = Lists.newArrayList(StatusEnum.PUR_RETURN.getFlag());
//            statusSet.addAll(statusList);
//        }
        //公司id
        pageView.put("compId", stockSaleReceiptReport.getCompId());
        pageView.put("searchKeyWord", stockSaleReceiptReport.getSearchKeyWord());
        pageView.put("searchType", stockSaleReceiptReport.getSearchType());
        pageView.put("pageSize", stockSaleReceiptReport.getPageSize());
        pageView.put("startDate", stockSaleReceiptReport.getStartDate());
        pageView.put("endDate", stockSaleReceiptReport.getEndDate());
        pageView.put("currentPage", stockSaleReceiptReport.getCurrentPage());
        pageView.put("contractNo", stockSaleReceiptReport.getContractNo());
        pageView.put("processNo", stockSaleReceiptReport.getProcessNo());
        pageView.put("statusFlag", stockSaleReceiptReport.getStatusFlag());
//        pageView.put("businessKeys", businessKeys);
//        pageView.put("statusSet", statusSet);
        // 查询销售出库总数
        Integer dataCount = baseMapper.getCountByCondition(pageView);
        List<StockSaleReceiptReport> dataList = baseMapper.getListByCondition(pageView);
        if (!CollectionUtils.isEmpty(dataList)) {
            for (StockSaleReceiptReport saleReceiptReport1:dataList){
                WarehouseInOutInfo warehouseInOutInfo=warehouseInOutInfoService.selectOne(new EntityWrapper<WarehouseInOutInfo>()
                        .eq("contract_no",saleReceiptReport1.getContractNo())
                        .eq("car_no",saleReceiptReport1.getCarNo())
                        .eq("warehouse_name",saleReceiptReport1.getWarehouseName()));
                if (warehouseInOutInfo!=null){
                    saleReceiptReport1.setPoundImg(warehouseInOutInfo.getAddressUrl());
                }
//                String taskId = "";
//                // 只有待审核状态才有taskId
//                if (StringUtils.isNotBlank(saleReceiptReport1.getWorkflowId())) {
//                    JSONObject jsonObject = workflowService.getActiveTask(Lists.newArrayList(saleReceiptReport1.getWorkflowId()), saleReceiptReport1.getId());
//                    taskId = jsonObject.getString("taskId");
//                    saleReceiptReport1.setTaskId(taskId);
//                }
            }
        }
        Page<StockSaleReceiptReport> page = new Page<>();
        page.setRecords(dataList == null ? Lists.newArrayList() : dataList);
        page.setTotal(dataCount == null ? 0 : dataCount);
        page.setCurrent(stockSaleReceiptReport.getCurrentPage());
        page.setSize(stockSaleReceiptReport.getPageSize());
        return page;
    }


    /**
     * 定金/备注
     *
     * @param contractManagementInfo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String disAndRemark(ContractManagementInfo contractManagementInfo) {
        //查询合同
        ContractManagementInfo contractManagementInfo1 = contractManagementInfoService.selectById(contractManagementInfo.getId());
        if (contractManagementInfo1 != null) {
            if(StringUtils.isNotBlank(contractManagementInfo.getDeposit())){
                contractManagementInfo1.setDeposit(contractManagementInfo.getDeposit());
                contractManagementInfo1.setDepositUrl(contractManagementInfo.getDepositUrl());
            }
            if(StringUtils.isNotBlank(contractManagementInfo.getRemark())){
                contractManagementInfo1.setRemark(contractManagementInfo.getRemark());
            }
            //更改销售出库报表信息
            contractManagementInfoService.updateById(contractManagementInfo1);
            return "OK";
        }
        return "NG";
    }


    /**
     * 修改结算重量
     *
     * @param stockSaleReceiptReport
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String editSettlementWeight(StockSaleReceiptReport stockSaleReceiptReport) {
        //查询销售出库报表
        StockSaleReceiptReport stockSaleReceiptReport1 = this.selectById(stockSaleReceiptReport.getId());
        if (stockSaleReceiptReport1 != null) {
            //修改重量
            if ("1".equals(stockSaleReceiptReport.getFlag())) {
                stockSaleReceiptReport1.setSettlementWeight(stockSaleReceiptReport.getSettlementWeight());
//            ContractManagementInfo contractManagementInfo = contractManagementInfoService.selectOne(new EntityWrapper<ContractManagementInfo>()
//                    .eq("contract_no", stockSaleReceiptReport1.getContractNo()).eq("delete_flag", "0"));
//            stockSaleReceiptReport1.setAmountIngReceivable(stockSaleReceiptReport.getSettlementWeight()* Float.valueOf(String.valueOf(contractManagementInfo.getUnitContractPrice())));
                stockSaleReceiptReport1.setAmountIngReceivable(stockSaleReceiptReport.getSettlementWeight() * stockSaleReceiptReport1.getSettlementPrice());
                stockSaleReceiptReport1.setAmountNotReceivable(stockSaleReceiptReport1.getAmountIngReceivable() - stockSaleReceiptReport1.getAmountEdReceivable());
                //更改销售出库报表信息
                this.updateById(stockSaleReceiptReport1);
                return "OK";
            }
            //修改单价
            else if("2".equals(stockSaleReceiptReport.getFlag())){
                stockSaleReceiptReport1.setSettlementPrice(stockSaleReceiptReport.getSettlementPrice());
                stockSaleReceiptReport1.setAmountIngReceivable(stockSaleReceiptReport1.getSettlementWeight() * stockSaleReceiptReport.getSettlementPrice());
                stockSaleReceiptReport1.setAmountNotReceivable(stockSaleReceiptReport1.getAmountIngReceivable() - stockSaleReceiptReport1.getAmountEdReceivable());
                //更改销售出库报表信息
                this.updateById(stockSaleReceiptReport1);
                return "OK";
            }
            //单独开发票
            else if("3".equals(stockSaleReceiptReport.getFlag())){
                stockSaleReceiptReport1.setAlreadyInvoice(stockSaleReceiptReport1.getAlreadyInvoice()+stockSaleReceiptReport.getAlreadyInvoice());
                //更改销售出库报表信息
                this.updateById(stockSaleReceiptReport1);
                return "OK";
            }
            //修改应收
            else if("5".equals(stockSaleReceiptReport.getFlag())){
                stockSaleReceiptReport1.setAmountIngReceivable(stockSaleReceiptReport.getAmountIngReceivable());
                stockSaleReceiptReport1.setAmountNotReceivable(stockSaleReceiptReport.getAmountIngReceivable() - stockSaleReceiptReport1.getAmountEdReceivable());
                //更改销售出库报表信息
                this.updateById(stockSaleReceiptReport1);
                return "OK";
            }
            //修改反馈重量
            else {
                stockSaleReceiptReport1.setFeedbackWeight(stockSaleReceiptReport.getFeedbackWeight());
                //更改销售出库报表信息
                this.updateById(stockSaleReceiptReport1);
                return "OK";
            }
        }
        return "NG";
    }

    /**
     * 出纳收款
     *
     * @param stockSaleReceiptReport
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String collectMoney(StockSaleReceiptReport stockSaleReceiptReport) {
        List<StockSaleReceiptReport> stockSaleReceiptReportList = stockSaleReceiptReport.getStockSaleReceiptReportList();
        Double money = stockSaleReceiptReport.getMoney();
        if (!CollectionUtils.isEmpty(stockSaleReceiptReportList)) {
            for (StockSaleReceiptReport stockSaleReceiptReport1 : stockSaleReceiptReportList) {
                StockSaleReceiptReport stockSaleReceiptReport2 = this.selectById(stockSaleReceiptReport1.getId());
                //收款金额大于本次循环未收金额
                if (money >= stockSaleReceiptReport1.getAmountNotReceivable()) {
                    money = money - stockSaleReceiptReport1.getAmountNotReceivable();
                    //全部收款
                    stockSaleReceiptReport1.setStatus(StatusEnum.PUR_COLLECTaLL.getName());
                    stockSaleReceiptReport1.setStatusFlag(StatusEnum.PUR_COLLECTaLL.getFlag());
                    stockSaleReceiptReport1.setCollectionDate(stockSaleReceiptReport.getCollectionDate());
                    stockSaleReceiptReport1.setCollectionScreenshot(stockSaleReceiptReport2.getCollectionScreenshot() != null ? stockSaleReceiptReport2.getCollectionScreenshot() + '$' + stockSaleReceiptReport.getCollectionScreenshot() : stockSaleReceiptReport.getCollectionScreenshot());
                    stockSaleReceiptReport1.setAmountEdReceivable(stockSaleReceiptReport1.getAmountEdReceivable() + stockSaleReceiptReport1.getAmountNotReceivable());
                    stockSaleReceiptReport1.setAmountNotReceivable(0.0d);
                    this.updateById(stockSaleReceiptReport1);
                } else if (money > 0) {
                    Double moneyTmp = money - stockSaleReceiptReport1.getAmountNotReceivable();
                    //部分收款
                    stockSaleReceiptReport1.setStatus(StatusEnum.PUR_COLLECT.getName());
                    stockSaleReceiptReport1.setStatusFlag(StatusEnum.PUR_COLLECT.getFlag());
                    stockSaleReceiptReport1.setCollectionDate(stockSaleReceiptReport.getCollectionDate());
                    stockSaleReceiptReport1.setCollectionScreenshot(stockSaleReceiptReport2.getCollectionScreenshot() != null ? stockSaleReceiptReport2.getCollectionScreenshot() + '$' + stockSaleReceiptReport.getCollectionScreenshot() : stockSaleReceiptReport.getCollectionScreenshot());
                    stockSaleReceiptReport1.setAmountEdReceivable(stockSaleReceiptReport1.getAmountEdReceivable() + money);
                    stockSaleReceiptReport1.setAmountNotReceivable(stockSaleReceiptReport1.getAmountNotReceivable() - money);
                    this.updateById(stockSaleReceiptReport1);
                    money = moneyTmp;
                } else {
                    break;
                }
            }
        }
//            StockSaleReceiptReport stockSaleReceiptReport1=stockSaleReceiptReportList.get(0);
//            StockSaleReceiptReport stockSaleReceiptReport2 = this.selectById(stockSaleReceiptReport1.getId());
//            stockSaleReceiptReport1.setCollectionDate(stockSaleReceiptReport.getCollectionDate());
//            stockSaleReceiptReport1.setCollectionScreenshot(stockSaleReceiptReport2.getCollectionScreenshot() != null ? stockSaleReceiptReport2.getCollectionScreenshot() + '$' + stockSaleReceiptReport.getCollectionScreenshot() : stockSaleReceiptReport.getCollectionScreenshot());
//            stockSaleReceiptReport1.setAmountEdReceivable(stockSaleReceiptReport2.getAmountEdReceivable() + stockSaleReceiptReport.getMoney());
//            if (stockSaleReceiptReport1.getAmountNotReceivable()>=stockSaleReceiptReport.getMoney()) {
//                stockSaleReceiptReport1.setAmountNotReceivable(stockSaleReceiptReport2.getAmountIngReceivable() - stockSaleReceiptReport1.getAmountEdReceivable());
//                stockSaleReceiptReport1.setStatusFlag(StatusEnum.PUR_COLLECT.getFlag());
//                stockSaleReceiptReport1.setStatus(StatusEnum.PUR_COLLECT.getName());
//            }
//            else{
//                Float money=stockSaleReceiptReport.getMoney()-stockSaleReceiptReport1.getAmountNotReceivable();
//                stockSaleReceiptReport1.setAmountNotReceivable(0.0f);
//                stockSaleReceiptReport1.setStatusFlag(StatusEnum.PUR_COLLECTaLL.getFlag());
//                stockSaleReceiptReport1.setStatus(StatusEnum.PUR_COLLECTaLL.getName());
//                for (StockSaleReceiptReport stockSaleReceiptReport3 : stockSaleReceiptReportList) {
//                    if (stockSaleReceiptReport3.getAmountNotReceivable()>=money){
//                        stockSaleReceiptReport3.setAmountNotReceivable(stockSaleReceiptReport3.getAmountNotReceivable() - money);
//                        stockSaleReceiptReport3.setStatusFlag(StatusEnum.PUR_COLLECT.getFlag());
//                        stockSaleReceiptReport3.setStatus(StatusEnum.PUR_COLLECT.getName());
//                    }
//                    else {
//                        money=money-stockSaleReceiptReport3.getAmountNotReceivable();
//                        stockSaleReceiptReport3.setAmountNotReceivable(0.0f);
//                        stockSaleReceiptReport3.setStatusFlag(StatusEnum.PUR_COLLECTaLL.getFlag());
//                        stockSaleReceiptReport3.setStatus(StatusEnum.PUR_COLLECTaLL.getName());
//                    }
//                    this.updateById(stockSaleReceiptReport3);
//                }
//            }
//            this.updateById(stockSaleReceiptReport1);
//        }
        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")
                .eq("goods_type","1")
                .orderBy("update_date", false));
        for (ContractManagementInfo contractManagementInfo : contractManagementInfoList) {
            List<TranTaskInfo> tranTaskInfoList=tranTaskInfoService.selectList(new EntityWrapper<TranTaskInfo>()
                .eq("comp_id",contractManagementInfo.getCompId())
                .eq("contract_no",contractManagementInfo.getContractNo()));
            if (!CollectionUtils.isEmpty(tranTaskInfoList)){
                for(TranTaskInfo tranTaskInfo:tranTaskInfoList){
                    TranProcessInfo tranProcessInfo=tranProcessInfoService.selectOne(new EntityWrapper<TranProcessInfo>()
                            .eq("info_id",tranTaskInfo.getId())
                            .eq("end_flag","1"));
                    if (tranProcessInfo!=null){
                        if ("船运".equals(tranProcessInfo.getTranType())) {
                            TranCarInfo tranCarInfo = tranCarInfoService.selectOne(new EntityWrapper<TranCarInfo>()
                                    .eq("process_id", tranProcessInfo.getId())
                                    .eq("ship_type", "集装箱"));
                            if (tranCarInfo != null) {
                                tranProcessInfo.setTranType("箱船");
                                tranTaskInfo.setTranProcessInfo(tranProcessInfo);
                            }
                            TranCarInfo tranCarInfo1 = tranCarInfoService.selectOne(new EntityWrapper<TranCarInfo>()
                                    .eq("process_id", tranProcessInfo.getId())
                                    .eq("ship_type", "散船"));
                            if (tranCarInfo1 != null) {
                                tranProcessInfo.setTranType("散船");
                                tranTaskInfo.setTranProcessInfo(tranProcessInfo);
                            }
                        }
                        else
                        {
                            tranTaskInfo.setTranProcessInfo(tranProcessInfo);
                        }
                    }
                }
                contractManagementInfo.setTranTaskInfoList(tranTaskInfoList);
            }
            ContractGoodsInfo contractGoodsInfo = contractGoodsInfoService.selectOne(new EntityWrapper<ContractGoodsInfo>()
                    .eq("contract_id",contractManagementInfo.getId()));
            contractManagementInfo.setGoodsName(contractGoodsInfo.getGoodsName());
            Double money = 0.00;
            //查现货销售出库报表
            List<StockSaleReceiptReport> stockSaleReceiptReportList = this.selectList(new EntityWrapper<StockSaleReceiptReport>()
                    .eq("contract_no", contractManagementInfo.getContractNo())
                    .eq("delete_flag", "0"));
            if (!CollectionUtils.isEmpty(stockSaleReceiptReportList)) {
                for (StockSaleReceiptReport stockSaleReceiptReport : stockSaleReceiptReportList) {
                    money = money + (stockSaleReceiptReport.getAmountNotReceivable()!=null?stockSaleReceiptReport.getAmountNotReceivable():0.0);
                }
                //有未收金额
                if (money > 0) {
                    contractManagementInfo.setReportStatus("待结算");
                } else {
                    contractManagementInfo.setReportStatus("已结算");
                }
            }
        }
        return contractManagementInfoList;
    }

    @Override
    public String openInvoiceList(StockSaleReceiptReport stockSaleReceiptReport) {
        List<StockSaleReceiptReport> stockSaleReceiptReportList = stockSaleReceiptReport.getStockSaleReceiptReportList();
        //批量
        if (!CollectionUtils.isEmpty(stockSaleReceiptReportList)) {
            for (StockSaleReceiptReport stockSaleReceiptReport1 : stockSaleReceiptReportList) {
                //已开发票金额等于已收金额
                stockSaleReceiptReport1.setAlreadyInvoice(stockSaleReceiptReport1.getAmountEdReceivable());
                this.updateById(stockSaleReceiptReport1);
            }
        }
        return "ok";
    }


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





    /**
     * 获取收入、支出、毛利润
     *
     * @return
     */
    @Override
    public List<BiViewInfo> getMoney(List<BiViewInfo> biViewInfos, String seachMoth) {
        Map<String, Object> pageView = new HashMap<>();
        pageView.put("seachMoth",seachMoth);
        pageView.put("compId", AuthSecurityUtils.getCurrentUserInfo().getCompId());
        String  amonutIn = baseMapper.getAmonutIn(pageView);
        String  amonutout = baseMapper.getAmonutOut(pageView);
        String  amonutMao = baseMapper.getAmonutMao(pageView);
        if(amonutIn == null){
            amonutIn = "0";
        }
        if(amonutout == null){
            amonutout = "0";
        }
        if(amonutMao == null){
            amonutMao = "0";
        }
        NumberFormat nf = NumberFormat.getNumberInstance();
        nf.setMaximumFractionDigits(2);
        BiViewInfo biViewInfo = new BiViewInfo();
        BiViewInfo biViewInfo1 = new BiViewInfo();
        BiViewInfo biViewInfo2 = new BiViewInfo();
        BiViewInfo biViewInfo3 = new BiViewInfo();
        biViewInfo1.setName("毛利润");
        biViewInfo1.setCount(nf.format(Double.valueOf(amonutMao)));
        biViewInfo2.setName("收入");
        biViewInfo2.setCount(nf.format(Double.valueOf(amonutIn)));
        biViewInfo3.setName("支出");
        biViewInfo3.setCount(nf.format(Double.valueOf(amonutout)));
        List<BiViewInfo> biViewInfoList = new ArrayList<>();
        biViewInfoList.add(biViewInfo1);
        biViewInfoList.add(biViewInfo2);
        biViewInfoList.add(biViewInfo3);
        biViewInfo.setBiType("利润");
        biViewInfo.setBiViewInfoList(biViewInfoList);
        biViewInfos.add(biViewInfo);


        return biViewInfos;
    }

}
