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


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.Wrapper;
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.AppServiceException;
import com.yh.saas.plugin.yiliangyiyun.exception.ExceptionDefinition;
import com.yh.saas.plugin.yiliangyiyun.exception.ServiceException;
import com.yh.saas.plugin.yiliangyiyun.exception.YException;
import com.yh.saas.plugin.yiliangyiyun.exception.YExceptionEnum;
import com.yh.saas.plugin.yiliangyiyun.mapper.PurchaseOrderMapper;
import com.yh.saas.plugin.yiliangyiyun.service.*;
import com.yh.saas.plugin.yiliangyiyun.entity.PurchaseOrder;
import com.yh.saas.plugin.yiliangyiyun.entity.TransactionRecord;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.Lists;
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 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-07-22
 */
@Service
public class PurchaseOrderServiceImpl extends ServiceImpl<PurchaseOrderMapper, PurchaseOrder> implements IPurchaseOrderService {
    @Autowired
    private ITransactionRecordService transactionRecordService;
    @Autowired
    private ICommonBillOperateHisService billOperateHisService;
    @Autowired
    private IPriceChangeRecordService priceChangeRecordService;
    @Autowired
    private IWarehouseInOutInfoService warehouseInOutInfoService;
    @Autowired
    private INewWorkflowService workflowService;
    @Autowired
    private GeTuiUtils geTuiUtils;
    @Autowired
    private IPurchaseReceiptReportService purchaseReceiptReportService;
    @Autowired
    private IPurchaseClosingReportService purchaseClosingReportService;
    @Autowired
    private IProcurementPlanInfoService procurementPlanInfoService;
    @Autowired
    private ICustomerInfoService customerInfoService;
    @Autowired
    private IContractManagementInfoService contractManagementInfoService;
    @Autowired
    private IIdentityAuthenticationInfoService iIdentityAuthenticationInfoService;
    @Autowired
    private WebSocket webSocket;

    /**
     * 成交
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String deal(PurchaseOrder purchaseOrder) {
        //状态改为已成交
        purchaseOrder.setStatusFlag(StatusEnum.ORDER_DEALED.getFlag());
        purchaseOrder.setStatus(StatusEnum.ORDER_DEALED.getName());
        //向成交记录表插入数据
        TransactionRecord transactionRecord = purchaseOrder.getTransactionRecord();
        transactionRecord.setId(IdGenerator.generateUUID());
        transactionRecord.setOrderId(purchaseOrder.getId());
        transactionRecord.setCompId(purchaseOrder.getCompId());
        transactionRecord.setBasis(purchaseOrder.getBasis());
        //标识为0 成交
        transactionRecord.setRecordFlag("0");
        transactionRecordService.insert(transactionRecord);
        //更新采购订单表
        purchaseOrder.setUnitPrice(transactionRecord.getTransactionPrice());
        this.updateById(purchaseOrder);
        //向改价记录表插入数据
        PriceChangeRecord priceChangeRecord = new PriceChangeRecord();
        priceChangeRecord.setId(IdGenerator.generateUUID());
        priceChangeRecord.setCompId(purchaseOrder.getCompId());
        priceChangeRecord.setOrderId(purchaseOrder.getId());
        priceChangeRecord.setPrice(transactionRecord.getTransactionPrice());
        priceChangeRecord.setPriceType("成交价");
        priceChangeRecordService.insert(priceChangeRecord);
        PurchaseOrder tmp = this.selectById(purchaseOrder.getId());
        geTuiUtils.pushByCid("成交通知", "您的合同已成交，成交价：" + transactionRecord.getTransactionPrice() + "元/吨", tmp.getCommonId());

        UnimallMessage messageDO = new UnimallMessage();
        messageDO.setAdminId(tmp.getCommonId());
        messageDO.setCustomer(tmp.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);
        return purchaseOrder.getId();
    }

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

        UnimallMessage messageDO = new UnimallMessage();
        messageDO.setAdminId(tmp.getCommonId());
        messageDO.setCustomer(tmp.getCustomer());
        messageDO.setOperation("平仓通知");
        messageDO.setResult("您的合同：" + purchaseOrder.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);
        // 平仓报表
        // 查询计划
        ProcurementPlanInfo procurementPlanInfo = procurementPlanInfoService.selectById(purchaseOrder.getPlanId());
        PurchaseClosingReport purchaseClosingReport = new PurchaseClosingReport();
        purchaseClosingReport.setId(IdGenerator.generateUUID());
        purchaseClosingReport.setCompId(purchaseOrder.getCompId());
        purchaseClosingReport.setContractNo(purchaseOrder.getContractNo());
        purchaseClosingReport.setClosePositionDate(purchaseOrder.getClosePositionDate());
        purchaseClosingReport.setClosingQuantity(purchaseOrder.getClosingQuantity());
        purchaseClosingReport.setTransactionPrice(purchaseOrder.getTransactionPrice());
        purchaseClosingReport.setCloseRate(purchaseOrder.getCloseRate());
        purchaseClosingReport.setBasisPrice(purchaseOrder.getBasis());
        purchaseClosingReport.setCustomerName(purchaseOrder.getSeller());
        purchaseClosingReport.setStatusFlag(StatusEnum.FORM_REVIEWED.getFlag());
        purchaseClosingReport.setStatus(StatusEnum.FORM_REVIEWED.getName());

        BigDecimal transactionPrice = new BigDecimal(Float.toString(purchaseOrder.getTransactionPrice()));
        BigDecimal closeRate = new BigDecimal(Float.toString(purchaseOrder.getCloseRate()));
        BigDecimal closingBasis = new BigDecimal(Float.toString(purchaseOrder.getClosingBasis()));
        Float price = transactionPrice.subtract(closeRate).add(closingBasis).floatValue();
        if (price > 0) {
            purchaseClosingReport.setAmountIngPayable(CalculationUtil.mulToFloat(Math.abs(price), purchaseClosingReport.getClosingQuantity()));
            purchaseClosingReport.setAmountEdPayable(0f);
            purchaseClosingReport.setAmountNotPayable(purchaseClosingReport.getAmountIngPayable());
        } else {
            purchaseClosingReport.setCollectionIngPayable(CalculationUtil.mulToFloat(Math.abs(price), purchaseClosingReport.getClosingQuantity()));
            purchaseClosingReport.setCollectionEdPayable(0f);
            purchaseClosingReport.setCollectionNotPayable(purchaseClosingReport.getCollectionIngPayable());
        }
//        if (purchaseOrder.getClosingPositionPayable() < 0) {
//            purchaseClosingReport.setCollectionIngPayable(Math.abs(purchaseOrder.getClosingPositionPayable()));
//        }
        if (procurementPlanInfo != null) {
            purchaseClosingReport.setWarehouseName(procurementPlanInfo.getReceiveWarehouse());
        }
        purchaseClosingReportService.insert(purchaseClosingReport);

        boolean isStartWorkflow = 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());
                purchaseClosingReportService.updateById(purchaseClosingReport);
                workflowService.startInstance(workflow.getId(), purchaseClosingReport.getId());
            }
        }
        // 退回的单子 再启用
        else {

            purchaseClosingReportService.updateById(purchaseClosingReport);
            workflowService.activateInstance(purchaseClosingReport.getWorkflowId(), purchaseClosingReport.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 {
        //查询采购订单信息
        PurchaseOrder purchaseOrder = this.selectById(id);
        if (purchaseOrder != 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 {
                purchaseOrder.setUnitPrice(unitPrice);
                //更改采购订单信息
                this.updateById(purchaseOrder);
                //向改价记录表插入数据
                PriceChangeRecord priceChangeRecord = new PriceChangeRecord();
                priceChangeRecord.setId(IdGenerator.generateUUID());
                priceChangeRecord.setOrderId(purchaseOrder.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 purchaseOrder
     * @return
     */
    @Override
    public Page<PurchaseOrder> selectPurchaseOrder(PurchaseOrder purchaseOrder) {
        Map<String, Object> pageView = new HashMap<>();
        pageView.put("startRecord", (purchaseOrder.getCurrentPage() - 1)
                * purchaseOrder.getPageSize());
        //公司id
        pageView.put("compId", purchaseOrder.getCompId());
        pageView.put("commonId", purchaseOrder.getCommonId());
        pageView.put("searchKeyWord", purchaseOrder.getSearchKeyWord());
        pageView.put("searchType", purchaseOrder.getSearchType());
        pageView.put("pcFlag", purchaseOrder.getPcFlag());
        pageView.put("pageSize", purchaseOrder.getPageSize());
        pageView.put("currentPage", purchaseOrder.getCurrentPage());
        // 查询采购订单总数
        Integer dataCount = baseMapper.getCountByCondition(pageView);
        List<PurchaseOrder> dataList = baseMapper.getListByCondition(pageView);
        if (!CollectionUtils.isEmpty(dataList)) {
            for (PurchaseOrder purchaseOrdera : dataList) {
                ProcurementPlanInfo procurementPlanInfo = procurementPlanInfoService.selectById(purchaseOrdera.getPlanId());
                if (procurementPlanInfo != null) {
                    purchaseOrdera.setProcurementPlanType(procurementPlanInfo.getProcurementPlanType());
                    purchaseOrdera.setTradingTarget(procurementPlanInfo.getTitle());
                }
                //查询合同Id
                ContractManagementInfo contractManagementInfo = contractManagementInfoService.selectOne(new EntityWrapper<ContractManagementInfo>()
                        .eq("contract_no", purchaseOrdera.getContractNo())
                        .eq("delete_flag", "0"));
                if (contractManagementInfo != null) {
                    purchaseOrdera.setContractId(contractManagementInfo.getId());
                    purchaseOrdera.setGoodsType(contractManagementInfo.getGoodsType());
                }
                //定义已入库量
                Float stockInQuantity = 0.0f;
                //查询入库量
                List<WarehouseInOutInfo> warehouseInOutInfoList = warehouseInOutInfoService.selectList(new EntityWrapper<WarehouseInOutInfo>()
                        .eq("contract_no", purchaseOrdera.getContractNo())
                        .eq("in_out_flag", "2")
                        .eq("status_flag", "3")
                        .eq("delete_flag", "0"));
                if (!CollectionUtils.isEmpty(warehouseInOutInfoList)) {
                    for (WarehouseInOutInfo warehouseInOutInfo : warehouseInOutInfoList) {
                        stockInQuantity = stockInQuantity + Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight()));
                    }
                }
                //查询改价记录
                List<PriceChangeRecord> priceChangeRecordList = priceChangeRecordService.selectList(new EntityWrapper<PriceChangeRecord>()
                        .eq("order_id", purchaseOrdera.getId())
                        .eq("delete_flag", "0")
                        .orderBy("create_date", false));
                //查询成交记录
                List<TransactionRecord> transactionRecordList = transactionRecordService.selectList(new EntityWrapper<TransactionRecord>()
                        .eq("order_id", purchaseOrdera.getId())
                        .eq("record_flag", "0")
                        .eq("delete_flag", "0")
                        .orderBy("deal_date", false));
                if (!CollectionUtils.isEmpty(transactionRecordList)) {
                    Float cumulativeTurnover = 0.0f;
                    for (TransactionRecord transactionRecord : transactionRecordList) {
                        cumulativeTurnover = cumulativeTurnover + (transactionRecord.getTurnover() != null ? transactionRecord.getTurnover() : 0);
                    }
                    purchaseOrdera.setCumulativeTurnover(cumulativeTurnover);
                }
                //查询入库报表记录
                List<PurchaseReceiptReport> purchaseReceiptReportList = purchaseReceiptReportService.selectList(new EntityWrapper<PurchaseReceiptReport>()
                        .eq("contract_no", purchaseOrdera.getContractNo())
                        .eq("delete_flag", "0"));
                if (!CollectionUtils.isEmpty(purchaseReceiptReportList)) {
                    Float receiptUnpaid = 0.0f;
                    for (PurchaseReceiptReport purchaseReceiptReport : purchaseReceiptReportList) {
                        receiptUnpaid = receiptUnpaid + (purchaseReceiptReport.getAmountNotPayable() != null ? purchaseReceiptReport.getAmountNotPayable() : 0);
                    }
                    purchaseOrdera.setReceiptUnpaid(receiptUnpaid);
                }
                //查询平仓报表记录
                List<PurchaseClosingReport> purchaseClosingReportList = purchaseClosingReportService.selectList(new EntityWrapper<PurchaseClosingReport>()
                        .eq("contract_no", purchaseOrdera.getContractNo())
                        .eq("delete_flag", "0"));
                if (!CollectionUtils.isEmpty(purchaseClosingReportList)) {
                    Float closedUnpaid = 0.0f;
                    for (PurchaseClosingReport purchaseClosingReport : purchaseClosingReportList) {
                        closedUnpaid = closedUnpaid + (purchaseClosingReport.getAmountNotPayable() != null ? purchaseClosingReport.getAmountNotPayable() : 0);
                    }
                    purchaseOrdera.setClosedUnpaid(closedUnpaid);
                }
                //查询平仓记录
                List<TransactionRecord> closePositionList = transactionRecordService.selectList(new EntityWrapper<TransactionRecord>()
                        .eq("order_id", purchaseOrdera.getId())
                        .eq("record_flag", "1")
                        .eq("delete_flag", "0")
                        .orderBy("deal_date", false));
                if (!CollectionUtils.isEmpty(closePositionList)) {
                    Float closedPosition = 0.0f;
                    for (TransactionRecord transactionRecord : closePositionList) {
                        closedPosition = closedPosition + (transactionRecord.getTurnover() != null ? transactionRecord.getTurnover() : 0);
                    }
                    purchaseOrdera.setClosedPosition(closedPosition);
                }
                //查询客户信息
                Wrapper<CustomerInfo> customerInfoWrapper = new EntityWrapper<>();
                customerInfoWrapper.andNew().eq("comp_name", purchaseOrdera.getCustomer()).or()
                        .eq("customer_name", purchaseOrdera.getCustomer());
                customerInfoWrapper.eq("delete_flag", "0");
                CustomerInfo customerInfo = customerInfoService.selectOne(customerInfoWrapper);
                if (customerInfo != null) {
                    purchaseOrdera.setCustomerInfo(customerInfo);
                }
                purchaseOrdera.setStockInQuantityList(warehouseInOutInfoList);
                purchaseOrdera.setTransactionRecordList(transactionRecordList);
                purchaseOrdera.setClosePositionList(closePositionList);
                purchaseOrdera.setPriceChangeRecordList(priceChangeRecordList);
                purchaseOrdera.setStockInQuantity(stockInQuantity);
                purchaseOrdera.setOpenPosition(CalculationUtil.subToFloat(CalculationUtil.subToFloat(purchaseOrdera.getCumulativeTurnover(), purchaseOrdera.getClosedPosition()), purchaseOrdera.getStockInQuantity()));

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

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


    /**
     * 更改状态
     *
     * @param purchaseOrder
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String editStatus(PurchaseOrder purchaseOrder) {
        //查询采购订单信息
        PurchaseOrder purchaseOrder1 = this.selectById(purchaseOrder.getId());
        if (purchaseOrder1 != null) {
            //0补充定金
            if (purchaseOrder.getFlag() == 0) {

                // 更新客户信息
                CustomerInfo customerInfo = customerInfoService.selectOne(new EntityWrapper<CustomerInfo>()
                        .eq("customer_phone", purchaseOrder.getSellerPhone())
                        .eq("delete_flag", "0"));
                if (customerInfo != null) {
                    if (customerInfo.getFreezingDeposit() != null && customerInfo.getFreezingDeposit() >= purchaseOrder.getFreezingDeposit()) {
                        customerInfo.setFreezingDeposit(customerInfo.getFreezingDeposit() + purchaseOrder.getMoney());
                        customerInfoService.updateById(customerInfo);
                    }


                }
                purchaseOrder1.setFreezingDeposit(purchaseOrder1.getFreezingDeposit() + purchaseOrder.getMoney());
                purchaseOrder1.setDefaultDeposit(purchaseOrder1.getDefaultDeposit() - purchaseOrder.getMoney());
                //更改采购订单信息
                this.updateById(purchaseOrder1);
                return "OK";
            }
            //1解冻定金
            else if (purchaseOrder.getFlag() == 1) {
                // 更新客户信息
                CustomerInfo customerInfo = customerInfoService.selectOne(new EntityWrapper<CustomerInfo>()
                        .eq("customer_phone", purchaseOrder.getSellerPhone())
                        .eq("delete_flag", "0"));
                if (customerInfo != null) {
                    if (customerInfo.getFreezingDeposit() != null && customerInfo.getFreezingDeposit() >= purchaseOrder.getFreezingDeposit()) {
                        customerInfo.setFreezingDeposit(customerInfo.getFreezingDeposit() - purchaseOrder.getFreezingDeposit());
                        customerInfoService.updateById(customerInfo);
                    }


                }

                purchaseOrder1.setFreezingDeposit(0.0f);
                //更改采购订单信息
                this.updateById(purchaseOrder1);
                return "OK";
            }
            //2 完成
            else if (purchaseOrder.getFlag() == 2) {
                purchaseOrder1.setStatusFlag(StatusEnum.ORDER_COMPLETED.getFlag());
                purchaseOrder1.setStatus(StatusEnum.ORDER_COMPLETED.getName());
                purchaseOrder1.setDefaultDeposit(0.0f);
                //更改采购订单信息
                this.updateById(purchaseOrder1);
                // 插入操作历史
                String staffName = this.billOperateHisService.getStaffAndName();
                // 插入操作历史
                this.billOperateHisService.saveBillOperateHis(purchaseOrder1.getId(), NumberConstant.CONSTANT_PURCHASE, staffName, null,
                        purchaseOrder1.getStatus(), null, "");
                return "OK";
            }
            //3更改基差
            else {
                purchaseOrder1.setBasis(purchaseOrder.getBasis());
                //更改采购订单信息
                this.updateById(purchaseOrder1);
                return "OK";
            }
        }
        return "NG";
    }

    /**
     * 添加采购订单
     *
     * @param purchaseOrder
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String insertPurchaseOrder(PurchaseOrder purchaseOrder) {
        //新增主键id
        purchaseOrder.setId(IdGenerator.generateUUID());
        purchaseOrder.setStatus(StatusEnum.ORDER_REVIEWED.getName());
        purchaseOrder.setStatusFlag(StatusEnum.ORDER_REVIEWED.getFlag());
        purchaseOrder.setOrderType("采购");
        // 操作主表数据
        boolean one = this.insert(purchaseOrder);
        // 添加客户信息
        int count = customerInfoService.selectCount(new EntityWrapper<CustomerInfo>().eq("customer_phone", purchaseOrder.getSellerPhone())
                .eq("customer_name",purchaseOrder.getSeller())
                .eq("delete_flag", "0"));
        if (count == 0) {
            CustomerInfo customerInfo = new CustomerInfo();
            IdentityAuthenticationInfo identityAuthenticationInfo = iIdentityAuthenticationInfoService.selectOne(new EntityWrapper<IdentityAuthenticationInfo>()
                    .eq("customer_phone", purchaseOrder.getSellerPhone())
                    .eq("cover", "0").eq("delete_flag", 0));
            if (identityAuthenticationInfo != null) {
                //个人
                if ("1".equals(identityAuthenticationInfo.getCustomerTypeFlag())) {
                    //姓名
                    customerInfo.setCustomerName(purchaseOrder.getSeller());
                    //手机号
                    customerInfo.setCustomerPhone(purchaseOrder.getSellerPhone());
                    //身份证号
                    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(purchaseOrder.getSeller());
                    customerInfo.setCustomerPhone(purchaseOrder.getSellerPhone());
                    customerInfo.setCustomerName(purchaseOrder.getSeller());
                    //身份证号
                    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(purchaseOrder.getCompId());
            customerInfoService.addCustomerInfo(customerInfo);
        }
        //向改价记录表插入数据
        PriceChangeRecord priceChangeRecord = new PriceChangeRecord();
        priceChangeRecord.setId(IdGenerator.generateUUID());
        priceChangeRecord.setCompId(purchaseOrder.getCompId());
        priceChangeRecord.setOrderId(purchaseOrder.getId());
        priceChangeRecord.setPrice(purchaseOrder.getUnitPrice());
        priceChangeRecord.setPriceType("预期单价");
        priceChangeRecordService.insert(priceChangeRecord);
        if (one) {
            return purchaseOrder.getId();
        } else {
            return "NG";
        }
    }


    /**
     * 添加采购订单
     *
     * @param purchaseOrder
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String submitPurchaseOrder(PurchaseOrder purchaseOrder) {
        purchaseOrder = this.selectById(purchaseOrder.getId());
        boolean isStartWorkflow = StringUtils.isBlank(purchaseOrder.getWorkflowId());
        // 不是退回的单子
        if (isStartWorkflow) {
            Workflow workflow = workflowService
                    .findLatestWorkflowByBusinessCodeByApp(purchaseOrder.getCompId(), "PROCUREMENT-ORDER-APPROVE");
            // 没配置审核流程，直接结束并处理信息
            if (workflow == null) {
                throw new YException(YExceptionEnum.PURCHASE_ORDER_ERROR);
            }
            // 开启审核流
            else {

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

            this.updateById(purchaseOrder);
            workflowService.activateInstance(purchaseOrder.getWorkflowId(), purchaseOrder.getId());
        }
        return "OK";
    }

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


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


        UnimallMessage messageDO = new UnimallMessage();
        messageDO.setAdminId(tmp.getCommonId());
        messageDO.setCustomer(tmp.getCustomer());
        messageDO.setOperation("审核通知");
        messageDO.setResult("您的合同已审核，审核单价：" + purchaseOrder.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);
        if (one) {
            return "OK";
        } else {
            return "NG";
        }
    }

    /**
     * 我的合同列表
     *
     * @param purchaseOrder
     * @return
     */
    @Override
    public Page<PurchaseOrder> selectPurchaseOrderApp(PurchaseOrder purchaseOrder) {
        Map<String, Object> pageView = new HashMap<>();
        pageView.put("startRecord", (purchaseOrder.getCurrentPage() - 1)
                * purchaseOrder.getPageSize());
        pageView.put("commonId", purchaseOrder.getCommonId());
        pageView.put("pageSize", purchaseOrder.getPageSize());
        pageView.put("currentPage", purchaseOrder.getCurrentPage());
        List<PurchaseOrder> dataList = baseMapper.getListByConditionApp(pageView);
        Page<PurchaseOrder> page = new Page<>();
        page.setRecords(dataList == null ? Lists.newArrayList() : dataList);
        page.setCurrent(purchaseOrder.getCurrentPage());
        page.setSize(purchaseOrder.getPageSize());
        return page;
    }

}

