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

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
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.*;
import com.yh.saas.plugin.yiliangyiyun.mapper.SaleOrderMapper;
import com.yh.saas.plugin.yiliangyiyun.service.*;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.yh.saas.plugin.yiliangyiyun.util.CalculationUtil;
import com.yh.saas.plugin.yiliangyiyun.util.GeTuiUtils;
import com.yh.saas.plugin.yiliangyiyun.util.WebSocket;
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.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 销售订单 服务实现类
 * </p>
 *
 * @author Gongdc
 * @since 2021-08-04
 */
@Service
public class SaleOrderServiceImpl extends ServiceImpl<SaleOrderMapper, SaleOrder> implements ISaleOrderService {
    @Autowired
    private ITransactionRecordService transactionRecordService;
    @Autowired
    private ICommonBillOperateHisService billOperateHisService;
    @Autowired
    private IPriceChangeRecordService priceChangeRecordService;
    @Autowired
    private IWarehouseInOutInfoService warehouseInOutInfoService;
    @Autowired
    private ISalePlanInfoService salePlanInfoService;
    @Autowired
    private ISalesClosingReportService salesClosingReportService;
    @Autowired
    private ISalesDeliveryReportService salesDeliveryReportService;
    @Autowired
    private INewWorkflowService workflowService;
    @Autowired
    private GeTuiUtils geTuiUtils;
    @Autowired
    private ICustomerInfoService customerInfoService;
    @Autowired
    private ICollectionManagementService collectionManagementService;
    @Autowired
    private IContractManagementInfoService contractManagementInfoService;
    @Autowired
    private IIdentityAuthenticationInfoService iIdentityAuthenticationInfoService;
    @Autowired
    private WebSocket webSocket;

    /**
     * 成交
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String deal(SaleOrder saleOrder) {
        //状态改为已成交
        saleOrder.setStatusFlag(StatusEnum.ORDER_DEALED.getFlag());
        saleOrder.setStatus(StatusEnum.ORDER_DEALED.getName());
        //向成交记录表插入数据
        TransactionRecord transactionRecord = saleOrder.getTransactionRecord();
        transactionRecord.setId(IdGenerator.generateUUID());
        transactionRecord.setOrderId(saleOrder.getId());
        transactionRecord.setCompId(saleOrder.getCompId());
        //标识为0 成交
        transactionRecord.setRecordFlag("0");
        transactionRecordService.insert(transactionRecord);
        //更新销售订单表
        saleOrder.setBasis(transactionRecord.getBasis());
        saleOrder.setUnitPrice(transactionRecord.getTransactionPrice());
        this.updateById(saleOrder);
        //向改价记录表插入数据
        PriceChangeRecord priceChangeRecord = new PriceChangeRecord();
        priceChangeRecord.setId(IdGenerator.generateUUID());
        priceChangeRecord.setCompId(saleOrder.getCompId());
        priceChangeRecord.setOrderId(saleOrder.getId());
        priceChangeRecord.setPrice(transactionRecord.getTransactionPrice());
        priceChangeRecord.setPriceType("成交价");
        priceChangeRecordService.insert(priceChangeRecord);
        geTuiUtils.pushByCid("成交通知", "您的合同已成交，成交价：" + transactionRecord.getTransactionPrice() + "元/吨", saleOrder.getCommonId());
        UnimallMessage messageDO = new UnimallMessage();
        messageDO.setAdminId(saleOrder.getCommonId());
        messageDO.setCustomer(saleOrder.getCustomer());
        messageDO.setOperation("成交通知");
        messageDO.setResult("您的合同已成交，成交价：" + transactionRecord.getTransactionPrice() + "元/吨");
        messageDO.setGmtUpdate(new java.util.Date());
        messageDO.setGmtCreate(new Date());
        messageDO.setTaskId(IdGenerator.generateUUID());
        messageDO.setCompanyId(AuthSecurityUtils.getCurrentUserInfo().getCompId());
        messageDO.setPath("XXXXX");
        webSocket.sendOneMessage(messageDO);
        //查询销售计划
        SalePlanInfo salePlanInfo = salePlanInfoService.selectById(saleOrder.getPlanId());
        //生成收款信息
        CollectionManagement collectionManagement = new CollectionManagement();
        collectionManagement.setId(IdGenerator.generateUUID());
        collectionManagement.setCompId(saleOrder.getCompId());
        collectionManagement.setContractNo(saleOrder.getContractNo());
        collectionManagement.setGoodsName(saleOrder.getGoodsName());
        collectionManagement.setPlanId(saleOrder.getPlanId());
        collectionManagement.setBuyer(saleOrder.getBuyer());
        collectionManagement.setSeller(salePlanInfo.getSeller());
        collectionManagementService.insert(collectionManagement);
        return saleOrder.getId();
    }

    /**
     * 更改
     *
     * @param saleOrder
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String editStatus(SaleOrder saleOrder) {
        //查询销售订单信息
        SaleOrder saleOrder1 = this.selectById(saleOrder.getId());
        if (saleOrder1 != null) {
            //0补充定金
            if (saleOrder.getFlag() == 0) {
                saleOrder1.setFreezingDeposit(saleOrder1.getFreezingDeposit() + saleOrder.getMoney());
                saleOrder1.setDefaultDeposit(saleOrder1.getDefaultDeposit() - saleOrder.getMoney());
                //更改销售订单信息
                this.updateById(saleOrder1);
                return "OK";
            }
            //1解冻定金
            else if (saleOrder.getFlag() == 1) {
                saleOrder1.setFreezingDeposit(0.0f);
                //更改销售订单信息
                this.updateById(saleOrder1);
                return "OK";
            }
            //2 完成
            else if (saleOrder.getFlag() == 2) {
                saleOrder1.setStatusFlag(StatusEnum.ORDER_COMPLETED.getFlag());
                saleOrder1.setStatus(StatusEnum.ORDER_COMPLETED.getName());
                //更改销售订单信息
                this.updateById(saleOrder1);
                // 插入操作历史
                String staffName = this.billOperateHisService.getStaffAndName();
                // 插入操作历史
                this.billOperateHisService.saveBillOperateHis(saleOrder1.getId(), NumberConstant.CONSTANT_PURCHASE, staffName, null,
                        saleOrder1.getStatus(), null, "");
                return "OK";
            }
            //3更改基差
            else {
                saleOrder1.setBasis(saleOrder.getBasis());
                //更改销售订单信息
                this.updateById(saleOrder1);
                return "OK";
            }
        }
        return "NG";
    }

    /**
     * 平仓
     *
     * @param saleOrder
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String closePosition(SaleOrder saleOrder) {
        saleOrder.setBasis(saleOrder.getClosingBasis());
        //修改主表信息
        boolean one = this.updateById(saleOrder);
        //向平仓记录表插入数据
        TransactionRecord transactionRecord = new TransactionRecord();
        transactionRecord.setId(IdGenerator.generateUUID());
        transactionRecord.setOrderId(saleOrder.getId());
        transactionRecord.setCompId(saleOrder.getCompId());
        //标识为1 平仓
        transactionRecord.setRecordFlag("1");
        transactionRecord.setTransactionPrice(saleOrder.getTransactionPrice());
        transactionRecord.setClosingPrice(saleOrder.getCloseRate());
        transactionRecord.setBasis(saleOrder.getClosingBasis());
        transactionRecord.setTurnover(saleOrder.getClosingQuantity());
        transactionRecord.setDealDate(saleOrder.getClosePositionDate());
        boolean two = transactionRecordService.insert(transactionRecord);
        SaleOrder tmp = this.selectById(saleOrder.getId());
        geTuiUtils.pushByCid("平仓通知", "您的合同：" + saleOrder.getContractNo() + " 平仓成功", tmp.getCommonId());

        UnimallMessage messageDO = new UnimallMessage();
        messageDO.setAdminId(tmp.getId());
        messageDO.setCustomer(tmp.getCustomer());
        messageDO.setOperation("平仓通知");
        messageDO.setResult("您的合同：" + saleOrder.getContractNo() + " 平仓成功");
        messageDO.setGmtUpdate(new java.util.Date());
        messageDO.setGmtCreate(new Date());
        messageDO.setTaskId(IdGenerator.generateUUID());
        messageDO.setCompanyId(AuthSecurityUtils.getCurrentUserInfo().getCompId());
        messageDO.setPath("XXXXX");
        webSocket.sendOneMessage(messageDO);
        // 平仓报表
        // 查询计划
        SalePlanInfo salePlanInfo = salePlanInfoService.selectById(saleOrder.getPlanId());
        SalesClosingReport salesClosingReport = new SalesClosingReport();
        salesClosingReport.setId(IdGenerator.generateUUID());
        salesClosingReport.setCompId(saleOrder.getCompId());
        salesClosingReport.setContractNo(saleOrder.getContractNo());
        salesClosingReport.setClosePositionDate(saleOrder.getClosePositionDate());
        salesClosingReport.setClosingQuantity(saleOrder.getClosingQuantity());
        salesClosingReport.setTransactionPrice(saleOrder.getTransactionPrice());
        salesClosingReport.setCloseRate(saleOrder.getCloseRate());
        salesClosingReport.setBasisPrice(saleOrder.getBasis());
        salesClosingReport.setStatusFlag(StatusEnum.FORM_REVIEWED.getFlag());
        salesClosingReport.setStatus(StatusEnum.FORM_REVIEWED.getName());
        salesClosingReport.setCustomerName(saleOrder.getBuyer());
        BigDecimal transactionPrice = new BigDecimal(Float.toString(saleOrder.getTransactionPrice()));
        BigDecimal closeRate = new BigDecimal(Float.toString(saleOrder.getCloseRate()));
        BigDecimal closingBasis = new BigDecimal(Float.toString(Math.abs(saleOrder.getClosingBasis())));
        Float price = closeRate.subtract(transactionPrice).subtract(closingBasis).floatValue();
        if (price > 0) {
            salesClosingReport.setAmountIngPayable(CalculationUtil.mulToFloat(price, salesClosingReport.getClosingQuantity()));
            salesClosingReport.setAmountEdPayable(0f);
            salesClosingReport.setAmountNotPayable(salesClosingReport.getAmountIngPayable());
        } else {
            salesClosingReport.setCollectionIngPayable(CalculationUtil.mulToFloat(Math.abs(price), salesClosingReport.getClosingQuantity()));
            salesClosingReport.setCollectionEdPayable(0f);
            salesClosingReport.setCollectionNotPayable(salesClosingReport.getCollectionIngPayable());
        }
//        if(saleOrder.getClosingPositionPayable() < 0 ){
//            salesClosingReport.setCollectionIngPayable(Math.abs(saleOrder.getClosingPositionPayable()));
//        }
        if (salePlanInfo != null) {
            salesClosingReport.setWarehouseName(salePlanInfo.getSendWarehouse());
        }
        salesClosingReportService.insert(salesClosingReport);
        boolean isStartWorkflow = 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());
                salesClosingReportService.updateById(salesClosingReport);
                workflowService.startInstance(workflow.getId(), salesClosingReport.getId());
            }
        }
        // 退回的单子 再启用
        else {

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

    /**
     * 客户点价
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String pointPrice(String id, Float unitPrice) throws ParseException, ServiceException {
        //查询销售订单信息
        SaleOrder saleOrder = this.selectById(id);
        if (saleOrder != null) {
            String format = "HH:mm:ss";
            SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
            // 三个不可改价时间（8：00-11：30/12：30-15：00/20：00-23：00）
            Date startTime = new SimpleDateFormat(format).parse("08:00:00");
            Date endTime = new SimpleDateFormat(format).parse("11:30:00");
            Date startTimeNext = new SimpleDateFormat(format).parse("12:30:00");
            Date endTimeNext = new SimpleDateFormat(format).parse("15:30:00");
            Date startTimeFinal = new SimpleDateFormat(format).parse("20:00:00");
            Date endTimeFinal = new SimpleDateFormat(format).parse("23:00:00");
            Date now = new SimpleDateFormat(format).parse(formatter.format(new Date()));
            // 定义时间段
            boolean result = belongCalendar(now, startTime, endTime);
            boolean resultNext = belongCalendar(now, startTimeNext, endTimeNext);
            boolean resultFinal = belongCalendar(now, startTimeFinal, endTimeFinal);
            //判断三个时间段内不可点价
            if (result || resultNext || resultFinal) {
                throw new AppServiceException(ExceptionDefinition.POINT_PRICE_TIME_ERROR);
            } else {
                saleOrder.setUnitPrice(unitPrice);
                //更改销售订单信息
                this.updateById(saleOrder);
                //向改价记录表插入数据
                PriceChangeRecord priceChangeRecord = new PriceChangeRecord();
                priceChangeRecord.setId(IdGenerator.generateUUID());
                priceChangeRecord.setOrderId(saleOrder.getId());
                priceChangeRecord.setPrice(unitPrice);
                priceChangeRecord.setPriceType("点价");
                priceChangeRecordService.insert(priceChangeRecord);
                return "OK";
            }
        }
        return "NG";
    }

    /**
     * 判断时间是否在时间段内
     *
     * @param nowTime
     * @param beginTime
     * @param endTime
     * @return
     */
    public static boolean belongCalendar(Date nowTime, Date beginTime,
                                         Date endTime) {
        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);

        Calendar begin = Calendar.getInstance();
        begin.setTime(beginTime);

        Calendar end = Calendar.getInstance();
        end.setTime(endTime);

        if (date.after(begin) && date.before(end)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 销售订单列表
     *
     * @param saleOrder
     * @return
     */
    @Override
    public Page<SaleOrder> selectSaleOrder(SaleOrder saleOrder) {
        Map<String, Object> pageView = new HashMap<>();
        pageView.put("startRecord", (saleOrder.getCurrentPage() - 1)
                * saleOrder.getPageSize());
        //公司id
        pageView.put("compId", saleOrder.getCompId());
        pageView.put("commonId", saleOrder.getCommonId());
        pageView.put("searchKeyWord", saleOrder.getSearchKeyWord());
        pageView.put("searchType", saleOrder.getSearchType());
        pageView.put("pcFlag", saleOrder.getPcFlag());
        pageView.put("pageSize", saleOrder.getPageSize());
        pageView.put("currentPage", saleOrder.getCurrentPage());
        // 查询销售订单总数
        Integer dataCount = baseMapper.getCountByCondition(pageView);
        List<SaleOrder> dataList = baseMapper.getListByCondition(pageView);
        if (!CollectionUtils.isEmpty(dataList)) {
            for (SaleOrder saleOrdera : dataList) {
                SalePlanInfo salePlanInfo = salePlanInfoService.selectById(saleOrdera.getPlanId());
                if (salePlanInfo != null) {
                    saleOrdera.setSalePlanType(salePlanInfo.getSalePlanType());
                    saleOrdera.setTradingTarget(salePlanInfo.getTitle());
                }
                //查询合同Id
                ContractManagementInfo contractManagementInfo = contractManagementInfoService.selectOne(new EntityWrapper<ContractManagementInfo>()
                        .eq("contract_no", saleOrdera.getContractNo())
                        .eq("delete_flag", "0"));
                if (contractManagementInfo != null) {
                    saleOrdera.setContractId(contractManagementInfo.getId());
                    saleOrdera.setGoodsType(contractManagementInfo.getGoodsType());
                }
                //定义已出库量
                Float stockOutQuantity = 0.0f;
                //查询出库量
                List<WarehouseInOutInfo> warehouseInOutInfoList = warehouseInOutInfoService.selectList(new EntityWrapper<WarehouseInOutInfo>()
                        .eq("contract_no", saleOrdera.getContractNo())
                        .eq("in_out_flag", "1")
                        .eq("status_flag", "3")
                        .eq("delete_flag", "0"));
                if (!CollectionUtils.isEmpty(warehouseInOutInfoList)) {
                    for (WarehouseInOutInfo warehouseInOutInfo : warehouseInOutInfoList) {
                        stockOutQuantity = stockOutQuantity + Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight()));
                    }
                }
                //查询出库报表记录
                List<SalesDeliveryReport> salesDeliveryReportList = salesDeliveryReportService.selectList(new EntityWrapper<SalesDeliveryReport>()
                        .eq("contract_no", saleOrdera.getContractNo())
                        .eq("delete_flag", "0"));
                if (!CollectionUtils.isEmpty(salesDeliveryReportList)) {
                    Float deliveryUnpaid = 0.0f;
                    for (SalesDeliveryReport salesDeliveryReport : salesDeliveryReportList) {
                        deliveryUnpaid = deliveryUnpaid + (salesDeliveryReport.getCollectionNotPayable() != null ? salesDeliveryReport.getCollectionNotPayable() : 0);
                    }
                    saleOrdera.setDeliveryUnpaid(deliveryUnpaid);
                }
                //查询平仓报表记录
                List<SalesClosingReport> salesClosingReportList = salesClosingReportService.selectList(new EntityWrapper<SalesClosingReport>()
                        .eq("contract_no", saleOrdera.getContractNo())
                        .eq("delete_flag", "0"));
                if (!CollectionUtils.isEmpty(salesClosingReportList)) {
                    Float closedUnpaid = 0.0f;
                    for (SalesClosingReport salesClosingReport : salesClosingReportList) {
                        closedUnpaid = closedUnpaid + (salesClosingReport.getAmountNotPayable() != null ? salesClosingReport.getAmountNotPayable() : 0);
                    }
                    saleOrdera.setClosedUnpaid(closedUnpaid);
                }
                //查询改价记录
                List<PriceChangeRecord> priceChangeRecordList = priceChangeRecordService.selectList(new EntityWrapper<PriceChangeRecord>()
                        .eq("order_id", saleOrdera.getId())
                        .eq("delete_flag", "0")
                        .orderBy("create_date", false));
                //查询成交记录
                List<TransactionRecord> transactionRecordList = transactionRecordService.selectList(new EntityWrapper<TransactionRecord>()
                        .eq("order_id", saleOrdera.getId())
                        .eq("record_flag", "0")
                        .eq("delete_flag", "0"));
                if (!CollectionUtils.isEmpty(transactionRecordList)) {
                    Float cumulativeTurnover = 0.0f;
                    for (TransactionRecord transactionRecord : transactionRecordList) {
                        cumulativeTurnover = cumulativeTurnover + (transactionRecord.getTurnover() != null ? transactionRecord.getTurnover() : 0);
                    }
                    saleOrdera.setCumulativeTurnover(cumulativeTurnover);
                }
                //查询平仓记录
                List<TransactionRecord> closePositionList = transactionRecordService.selectList(new EntityWrapper<TransactionRecord>()
                        .eq("order_id", saleOrdera.getId())
                        .eq("record_flag", "1")
                        .eq("delete_flag", "0"));
                if (!CollectionUtils.isEmpty(closePositionList)) {
                    Float closedPosition = 0.0f;
                    for (TransactionRecord transactionRecord : closePositionList) {
                        closedPosition = closedPosition + (transactionRecord.getTurnover() != null ? transactionRecord.getTurnover() : 0);
                    }
                    saleOrdera.setClosedPosition(closedPosition);
                }
                //查询客户信息
                Wrapper<CustomerInfo> customerInfoWrapper = new EntityWrapper<>();
                customerInfoWrapper.andNew().eq("comp_name", saleOrdera.getCustomer()).or()
                        .eq("customer_name", saleOrdera.getCustomer());
                customerInfoWrapper.eq("delete_flag", "0");
                CustomerInfo customerInfo = customerInfoService.selectOne(customerInfoWrapper);
                if (customerInfo != null) {
                    saleOrdera.setCustomerInfo(customerInfo);
                }
                saleOrdera.setStockOutQuantityList(warehouseInOutInfoList);
                saleOrdera.setTransactionRecordList(transactionRecordList);
                saleOrdera.setClosePositionList(closePositionList);
                saleOrdera.setPriceChangeRecordList(priceChangeRecordList);
                saleOrdera.setStockOutQuantity(stockOutQuantity);
                saleOrdera.setOpenPosition(CalculationUtil.subToFloat(CalculationUtil.subToFloat(saleOrdera.getCumulativeTurnover(), saleOrdera.getClosedPosition()), saleOrdera.getStockOutQuantity()));
                String taskId = "";
                // 只有待审核状态才有taskId
                if (StringUtils.isNotBlank(saleOrdera.getWorkflowId())) {
                    JSONObject jsonObject = workflowService.getActiveTask(Lists.newArrayList(saleOrdera.getWorkflowId()), saleOrdera.getId());
                    taskId = jsonObject.getString("taskId");
                    saleOrdera.setTaskId(taskId);
                }

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

    /**
     * 添加销售订单
     *
     * @param saleOrder
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String insertSaleOrder(SaleOrder saleOrder) {
        //新增主键id
        saleOrder.setId(IdGenerator.generateUUID());
        saleOrder.setStatus(StatusEnum.ORDER_REVIEWED.getName());
        saleOrder.setStatusFlag(StatusEnum.ORDER_REVIEWED.getFlag());
        saleOrder.setOrderType("销售");
        // 操作主表数据
        boolean one = this.insert(saleOrder);
        boolean isStartWorkflow = StringUtils.isBlank(saleOrder.getWorkflowId());
//         不是退回的单子
        if (isStartWorkflow) {
            Workflow workflow = workflowService
                    .findLatestWorkflowByBusinessCodeByApp(saleOrder.getCompId(), "SALE-ORDER-APPROVE");
            // 没配置审核流程，直接结束并处理信息
            if (workflow == null) {
                throw new YException(YExceptionEnum.PURCHASE_ORDER_ERROR);
            }
            // 开启审核流
            else {
                // 设置状态 已提交审核
                saleOrder.setWorkflowId(workflow.getId());
                this.updateById(saleOrder);
                workflowService.startInstance(workflow.getId(), saleOrder.getId());
            }
        }
        // 退回的单子 再启用
        else {
            this.updateById(saleOrder);
            workflowService.activateInstance(saleOrder.getWorkflowId(), saleOrder.getId());
        }

        // 添加客户信息
        int count = customerInfoService.selectCount(new EntityWrapper<CustomerInfo>().eq("customer_phone", saleOrder.getBuyerPhone())
                .eq("customer_name",saleOrder.getBuyer())
                .eq("delete_flag", "0"));
        if (count == 0) {
            CustomerInfo customerInfo = new CustomerInfo();
            IdentityAuthenticationInfo identityAuthenticationInfo = iIdentityAuthenticationInfoService.selectOne(new EntityWrapper<IdentityAuthenticationInfo>()
                    .eq("customer_phone", saleOrder.getBuyerPhone())
                    .eq("cover", "0").eq("delete_flag", 0));
            if (identityAuthenticationInfo != null) {
                //个人
                if ("1".equals(identityAuthenticationInfo.getCustomerTypeFlag())) {
                    //姓名
                    customerInfo.setCustomerName(saleOrder.getBuyer());
                    //手机号
                    customerInfo.setCustomerPhone(saleOrder.getBuyerPhone());
                    //身份证号
                    customerInfo.setCustomerNumberCard(identityAuthenticationInfo.getCustomerNumberCard());
                    //身份证
                    customerInfo.setCardAddressUrl(identityAuthenticationInfo.getCardAddressUrl());
                    //银行卡
                    customerInfo.setPayeeAddressUrl(identityAuthenticationInfo.getPayeeAddressUrl());
                    customerInfo.setBankCard(identityAuthenticationInfo.getBankCard());
                    customerInfo.setBankDeposit(identityAuthenticationInfo.getBankDeposit());
                    customerInfo.setBankDepositBranch(identityAuthenticationInfo.getBankDepositBranch());
                    //地址
                    customerInfo.setCompAddress(identityAuthenticationInfo.getCompAddress());
                    customerInfo.setPayeeName(identityAuthenticationInfo.getPayeeName());
                    customerInfo.setPayeeNumberCard(identityAuthenticationInfo.getPayeeNumberCard());
                    customerInfo.setCustomerTypeFlag(identityAuthenticationInfo.getCustomerTypeFlag());
                }
                //公司
                else if ("2".equals(identityAuthenticationInfo.getCustomerTypeFlag())) {
                    //公司名
                    customerInfo.setCompName(saleOrder.getBuyer());
                    customerInfo.setCustomerPhone(saleOrder.getBuyerPhone());
                    customerInfo.setCustomerName(saleOrder.getBuyer());
                    //身份证号
                    customerInfo.setCustomerNumberCard(identityAuthenticationInfo.getCustomerNumberCard());
                    //身份证
                    customerInfo.setCardAddressUrl(identityAuthenticationInfo.getCardAddressUrl());
                    //银行卡
                    customerInfo.setPayeeAddressUrl(identityAuthenticationInfo.getPayeeAddressUrl());
                    customerInfo.setBankCard(identityAuthenticationInfo.getBankCard());
                    customerInfo.setBankDeposit(identityAuthenticationInfo.getBankDeposit());
                    customerInfo.setBankDepositBranch(identityAuthenticationInfo.getBankDepositBranch());
                    //地址
                    customerInfo.setCompAddress(identityAuthenticationInfo.getCompAddress());
                    customerInfo.setCustomerTypeFlag(identityAuthenticationInfo.getCustomerTypeFlag());
                    customerInfo.setBusinessLicenseAddressUrl(identityAuthenticationInfo.getBusinessLicenseAddressUrl());
                    customerInfo.setPayTaxesCard(identityAuthenticationInfo.getPayTaxesCard());
                }
            }
            customerInfo.setCompId(saleOrder.getCompId());
            customerInfoService.addCustomerInfo(customerInfo);
        }
        //向改价记录表插入数据
        PriceChangeRecord priceChangeRecord = new PriceChangeRecord();
        priceChangeRecord.setId(IdGenerator.generateUUID());
        priceChangeRecord.setCompId(saleOrder.getCompId());
        priceChangeRecord.setOrderId(saleOrder.getId());
        priceChangeRecord.setPrice(saleOrder.getUnitPrice());
        priceChangeRecord.setPriceType("预期单价");
        priceChangeRecordService.insert(priceChangeRecord);
        if (one) {
            return "OK";
        } else {
            return "NG";
        }
    }

    /**
     * 删除销售订单
     *
     * @param id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteSaleOrder(String id) {
        //删除销售订单
        SaleOrder saleOrder = this.selectById(id);
        this.deleteById(saleOrder.getId());
        //删除改价记录
        List<PriceChangeRecord> priceChangeRecordList = priceChangeRecordService.selectList(new EntityWrapper<PriceChangeRecord>()
                .eq(PriceChangeRecord.QueryFiles.ORDER_ID, id));
        if (!CollectionUtils.isEmpty(priceChangeRecordList)) {
            for (PriceChangeRecord priceChangeRecord : priceChangeRecordList) {
                priceChangeRecordService.deleteById(priceChangeRecord.getId());
            }
        }
        //删除成交记录
        List<TransactionRecord> transactionRecordList = transactionRecordService.selectList(new EntityWrapper<TransactionRecord>()
                .eq(TransactionRecord.QueryFiles.ORDER_ID, id));
        if (!CollectionUtils.isEmpty(transactionRecordList)) {
            for (TransactionRecord transactionRecord : transactionRecordList) {
                transactionRecordService.deleteById(transactionRecord.getId());
            }
        }
    }

    /**
     * 编辑销售订单
     *
     * @param saleOrder
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String editSaleOrder(SaleOrder saleOrder) {
        //现货审核通过
        if ("现货".equals(saleOrder.getSalePlanType())) {
            saleOrder.setStatusFlag(StatusEnum.ORDER_COMPLETED.getFlag());
            saleOrder.setStatus(StatusEnum.ORDER_COMPLETED.getName());
        }
        //期货
        else {
            saleOrder.setStatus(StatusEnum.ORDER_PASSED.getName());
            saleOrder.setStatusFlag(StatusEnum.ORDER_PASSED.getFlag());
            // 更新客户信息
            CustomerInfo customerInfo = customerInfoService.selectOne(new EntityWrapper<CustomerInfo>()
                    .eq("customer_phone", saleOrder.getBuyerPhone())
                    .eq("delete_flag", "0"));
            if (customerInfo != null) {
                //客户可用预存>=应冻结定金
                if (customerInfo.getTotalDeposit() - customerInfo.getFreezingDeposit() >= saleOrder.getFreezingDeposit()) {
                    customerInfo.setFreezingDeposit(customerInfo.getFreezingDeposit() + saleOrder.getFreezingDeposit());
                } else if (customerInfo.getTotalDeposit() - customerInfo.getFreezingDeposit() - saleOrder.getFreezingDeposit() <= 0) {
                    //订单拖欠定金
                    saleOrder.setDefaultDeposit(saleOrder.getFreezingDeposit() - (customerInfo.getTotalDeposit() - customerInfo.getFreezingDeposit()));
                    //订单冻结定金
                    saleOrder.setFreezingDeposit(customerInfo.getTotalDeposit() - customerInfo.getFreezingDeposit());
                    customerInfo.setFreezingDeposit(customerInfo.getTotalDeposit());
                }
                customerInfoService.updateById(customerInfo);
            }
        }
        //向改价记录表插入数据
        PriceChangeRecord priceChangeRecord = new PriceChangeRecord();
        priceChangeRecord.setId(IdGenerator.generateUUID());
        priceChangeRecord.setCompId(saleOrder.getCompId());
        priceChangeRecord.setOrderId(saleOrder.getId());
        priceChangeRecord.setPrice(saleOrder.getUnitPrice());
        priceChangeRecord.setPriceType("审核单价");
        priceChangeRecordService.insert(priceChangeRecord);
        SaleOrder tmp = this.selectById(saleOrder.getId());
        geTuiUtils.pushByCid("审核通知", "您的合同已审核，审核单价：" + saleOrder.getUnitPrice() + "元/吨", tmp.getCommonId());

        UnimallMessage messageDO = new UnimallMessage();
        messageDO.setAdminId(tmp.getId());
        messageDO.setCustomer(tmp.getCustomer());
        messageDO.setOperation("审核通知");
        messageDO.setResult("您的合同已审核，审核单价：" + saleOrder.getUnitPrice() + "元/吨");
        messageDO.setGmtUpdate(new java.util.Date());
        messageDO.setGmtCreate(new Date());
        messageDO.setTaskId(IdGenerator.generateUUID());
        messageDO.setCompanyId(AuthSecurityUtils.getCurrentUserInfo().getCompId());
        messageDO.setPath("XXXXX");
        webSocket.sendOneMessage(messageDO);
        boolean one = this.updateById(saleOrder);
        if (one) {
            return "OK";
        } else {
            return "NG";
        }
    }

    /**
     * 查看
     *
     * @param
     */
    @Override
    public SaleOrder getInfo(String id) {
        SaleOrder saleOrder = this.selectById(id);
        SalePlanInfo salePlanInfo = salePlanInfoService.selectById(saleOrder.getPlanId());
        if (salePlanInfo != null) {
            saleOrder.setSalePlanType(salePlanInfo.getSalePlanType());
            //查询客户信息
            Wrapper<CustomerInfo> customerInfoWrapper = new EntityWrapper<>();
            customerInfoWrapper.andNew().eq("comp_name", saleOrder.getCustomer()).or()
                    .eq("customer_name", saleOrder.getCustomer());
            customerInfoWrapper.eq("delete_flag", "0");
            CustomerInfo customerInfo = customerInfoService.selectOne(customerInfoWrapper);
            if (customerInfo != null) {
                saleOrder.setCustomerInfo(customerInfo);
            }
        }
        String taskId = "";
        // 只有待审核状态才有taskId
        if (StringUtils.isNotBlank(saleOrder.getWorkflowId())) {
            JSONObject jsonObject = workflowService.getActiveTask(Lists.newArrayList(saleOrder.getWorkflowId()), saleOrder.getId());
            taskId = jsonObject.getString("taskId");
            saleOrder.setTaskId(taskId);
        }
        return saleOrder;
    }
}
