<?php
/**
 * 采购数据模型
 * Created by PhpStorm.
 * User: XiaoMing
 * Date: 2019/11/11
 * Time: 17:49
 */

namespace JinDouYun\Model\Purchase;

use Exception;

use JinDouYun\Cache\Stock;
use JinDouYun\Controller\Common\Logger;

use JinDouYun\Dao\Order\DOrder;
use JinDouYun\Dao\Order\DOrderGoods;
use JinDouYun\Dao\Stock\DInventoryWarehouse;
use JinDouYun\Model\Order\MOrder;
use Mall\Framework\Core\ErrorCode;
use Mall\Framework\Core\ResultWrapper;
use Mall\Framework\Core\StatusCode;

use JinDouYun\Model\Stock\MInventoryIn;
use JinDouYun\Model\GoodsManage\MSku;
use JinDouYun\Model\GoodsManage\MGoodsBasic;
use JinDouYun\Model\MBaseModel;
use JinDouYun\Model\Stock\MInventory;
use JinDouYun\Model\Shop\MShop;
use JinDouYun\Model\Merchant\MMerchant;
use JinDouYun\Model\Stock\MWarehouse;
use JinDouYun\Model\System\MPrintNum;
use JinDouYun\Model\Finance\MRefund;

use JinDouYun\Dao\Purchase\DPurchase;
use JinDouYun\Dao\Purchase\DPurchaseGoods;
use JinDouYun\Dao\Stock\DInventory;

use JinDouYun\Dao\Shop\DShop;

use Mall\Framework\Factory;
use const Grpc\STATUS_ABORTED;


//use Util\Common\AgentTools;



class MPurchase extends MBaseModel
{
    private $objDPurchase;

    private $onlineUserId;

    private $onlineEnterpriseId;

    private $objPurchaseGoods;

    private $objDPurchaseGoods;

    private $objDInventory;

    private $objStock;

    private $cutTable = 200000;
    
    
    private $objDShop;
    

    /**
     * MOrder constructor.
     * @param $onlineUserId
     * @param $onlineEnterpriseId
     * @throws Exception
     */
    public function __construct($onlineUserId, $onlineEnterpriseId)
    {

        $this->onlineUserId = $onlineUserId;
        $this->onlineEnterpriseId = $onlineEnterpriseId;
        parent::__construct($this->onlineEnterpriseId, $this->onlineUserId);
        $this->objDPurchase = new DPurchase('stock');
        $this->objDPurchaseGoods = new DPurchaseGoods('stock');
        $this->objPurchaseGoods = new MPurchaseGoods($this->onlineUserId, $this->onlineEnterpriseId);

        $this->objDInventory = new DInventory('stock');
        $this->objDInventory->setTable('qianniao_inventory_' . $this->onlineEnterpriseId);

        $this->objDPurchase->setTable($this->objDPurchase->get_Table() . '_' . $this->onlineEnterpriseId);
        $this->objDPurchaseGoods->setTable($this->objDPurchaseGoods->get_Table() . '_' . $this->onlineEnterpriseId);

        $this->objDPurchaseGoods->setSearchIndex('purchase_details_search')->setType('purchase_details');

        $this->objStock = new Stock($this->onlineEnterpriseId);
        
        $this->objDShop = new DShop();
        $this->objDShop->setTable('qianniao_shop_1');
        
    }

    /**
     * 增加采购订单
     * @param $params
     * @return ResultWrapper
     * @throws Exception
     */
    public function addPurchase($params)
    {
        if(isset($params['departmentPath'])){
            $params['extends'] = json_encode(['departmentPath' => (string)$params['departmentPath']]);
            unset($params['departmentPath']);
        }
        $beginStatus = $this->objDPurchase->beginTransaction();
        $goodData = $params['goodsData'];
        unset($params['deleteArray']);
        unset($params['goodsData']);

        $purchaseAmount = 0; //采购总额
        $goodsNum = 0; // 统计采购订单总商品数
        foreach ($goodData as $key => $val) {
            $goodsNum = bcadd($val['buyerNum'], $goodsNum, 2);
            $purchaseAmount = bcadd($purchaseAmount, $val['subtotalPrice'], 4);
        }
        $params['purchaseAmount'] = $purchaseAmount;
        $params['goodsNum'] = $goodsNum;
        $params['createTime'] = time();
        $params['updateTime'] = time();

        //添加采购订单
        //no编号
        $dbResult =  $this->objDPurchase->get('createTime >='.strtotime(date('Ymd'.'0:0:0')), 'no', 'createTime desc');
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDPurchase->error(), ErrorCode::$dberror);
        }
        if(empty($dbResult)){
            $params['no'] = createSerialNumberByDate('');
        }else{
            $params['no'] = createSerialNumberByDate($dbResult['no']);
        }

        //查询仓库数据
        $objMWarehouse = new MWarehouse($this->onlineEnterpriseId);
        $modelResult = $objMWarehouse->getWarehouse(['id' => $params['warehouseId'], 'deleteStatus' => StatusCode::$standard]);
        if(!$modelResult->isSuccess()){
            return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
        }
        $warehouseData = $modelResult->getData();
        unset($modelResult);
        if(empty($warehouseData)){
            return ResultWrapper::fail('仓库信息查询失败', ErrorCode::$paramError);
        }

        $params['warehouseId'] = $warehouseData['id'];
        $params['warehouseName'] = $warehouseData['warehouseName'];
        $params['inStatus'] = StatusCode::$delete;
        $params['returnStatus'] = StatusCode::$orderReturn['notReturn'];
        $params['auditStatus'] = StatusCode::$auditStatus['auditing'];
        $params['auditName'] = '';
        $params['auditId'] = 0;
        $params['auditTime'] = 0;
        $params['deleteStatus'] = StatusCode::$standard;
        $params['serialNum'] = $this->objStock->createSerialSn(0, 'purchase');

        $purchaseId = $this->objDPurchase->insert($params);
        if ($purchaseId === false) {
            $this->objDPurchase->rollBack();
            return ResultWrapper::fail($this->objDPurchase->error(), ErrorCode::$dberror);
        }

        $insert = [];
        foreach ($goodData as $details) {
            $insert[] = [
                'basicGoodsId'   => $details['basicGoodsId'],
                'goodsCode'      => $details['goodsCode'],
                'goodsName'      => $details['goodsName'],
                'skuId'          => $details['skuId'],
                'buyerNum'       => $details['buyerNum'],//采购数量
                'inNum'          => 0,//入库数量
                'otherNum'      => $details['otherNum'],
                'inOfNum'        => $details['buyerNum'],//待入库数量
                'returnOnNum'    => 0,//可退数量
                'returnNum'      => 0,//退货数量
                'buyerUnitPrice' => $details['buyerUnitPrice'],
                'subtotalPrice'  => $details['subtotalPrice'],
                'couponAmount'   => getArrayItem($details, 'couponAmount', 0),
                'otherAmount'    => getArrayItem($details, 'otherAmount', 0),
                'purchaseId'     => $purchaseId,
                'categoryId'     => $details['categoryId'],
                'categoryName'   => $details['categoryName'],
                'returnStatus'   => StatusCode::$orderReturn['notReturn'],
                'deleteStatus'   => StatusCode::$standard,
                'unitName'       => isset($details['unitName']) ? $details['unitName'] : '',//单位名称
                'skuName'        => isset($details['skuName']) ? $details['skuName'] : ''
            ];
        }

        $dbResult = $this->objPurchaseGoods->addPurchaseGoods($insert);
        if (!$dbResult->isSuccess()) {
            $this->objDPurchase->rollBack();
            return ResultWrapper::fail($dbResult->getData(), ErrorCode::$dberror);
        }

        // 增加es数据
        /*
        $ids = $dbResult->getData();
        $modelResult = self::addEsData($insert, $params, $ids);
        if (!$modelResult->isSuccess()) {
            $this->objDPurchase->rollBack();
            return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
        }*/

        $beginStatus && $this->objDPurchase->commit();
        return ResultWrapper::success($purchaseId);
    }

    /**
     * 采购订单详情
     * @param $id
     * @return ResultWrapper
     * @throws Exception
     */
    public function getPurchaseInfoById($id)
    {
        $dbResult = $this->objDPurchase->get($id);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDPurchase->error(), ErrorCode::$dberror);
        }
        if (empty($dbResult)) return ResultWrapper::success([]);
        $purchaseData = $dbResult;
        unset($dbResult);
        $dbResult = $this->objDPurchaseGoods->select(['purchaseId' => $purchaseData['id'], 'deleteStatus' => StatusCode::$standard]);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDPurchaseGoods->error(), ErrorCode::$paramError);
        }
        $purchaseData['details'] = $dbResult;
        $purchaseData['type'] = StatusCode::$orderType['purchaseOrder'];
        unset($dbResult);

        $purchaseData['details'] = parent::formatOrderMan($this->onlineEnterpriseId, $purchaseData['details']);
        $objMPrintNum = new MPrintNum($this->onlineEnterpriseId);
        $purchaseData['printNum'] = $objMPrintNum->getObjectPrintNum($purchaseData['no'], StatusCode::$orderType['purchaseIn']);
        return ResultWrapper::success($purchaseData);
    }

    /**
     * 采购订单详情和批次数据(采购退货专用)
     * @param $params
     * @return ResultWrapper
     * @throws Exception
     */
    public function getPurchaseAndBatchInfoById($params)
    {
        $id = $params['id'];
        $warehouseId = $params['warehouseId'];
        if(empty($warehouseId)){
            return ResultWrapper::fail('查询批次仓库id错误', ErrorCode::$paramError);
        }
        //查询采购数量
        $dbResult = $this->objDPurchaseGoods->select(['purchaseId' => $id, 'deleteStatus' => StatusCode::$standard, 'inStatus' => [5,6], 'returnStatus' => [0,1]]);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDPurchaseGoods->error(), ErrorCode::$dberror);
        }
        $detailsResult = $dbResult;
        unset($dbResult);

        //查询所有单位的主单位
        $skuIds = array_column($detailsResult, 'skuId');
        $objMSku = new MSku($this->onlineUserId, $this->onlineEnterpriseId);
        $modelResult = $objMSku->getConversion($skuIds);
        if(!$modelResult->isSuccess()){
            return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
        }
        $skuResult = $modelResult->getData();
        unset($modelResult);
        foreach($detailsResult as &$value){
            $value['masterSkuId'] = $skuResult[$value['skuId']]['masterSkuId'];
        }
        unset($value);

        //库存剩余
        $sql = 'select * from qianniao_inventory_batch_'.$this->onlineEnterpriseId.'_'.$warehouseId.' where originId = '.$id;
        $dbResult = $this->objDPurchaseGoods->query($sql);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDPurchase->error(), ErrorCode::$dberror);
        }
        $batchResult = $dbResult;
        unset($dbResult);
        $batchData = [];
        foreach($batchResult as $value){
            $batchData[$value['skuId']]['num'] += $value['num'];
        }

        //映射数量
        foreach($detailsResult as &$value){
            if(isset($batchData[$value['masterSkuId']])){
                $value['num'] = $batchData[$value['masterSkuId']]['num'];
            }
        }

        //转换数量
        $objMInventory = new MInventory($this->onlineEnterpriseId, $this->onlineUserId);
        $modelResult = $objMInventory->conversionMinorSku($detailsResult);
        if (!$modelResult->isSuccess()) {
            return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
        }
        $details = $modelResult->getData();
        unset($modelResult);

        $returnData = parent::formatOrderMan($this->onlineEnterpriseId, $details);
        return ResultWrapper::success($returnData);
    }

    /**
     * 修改采购单 and ESData 库存审核入库用
     * 可公用
     * @param $updateData
     * @param $where
     * @return ResultWrapper
     * @throws Exception
     */
    public function updatePurchaseData($updateData, $where)
    {
        $updateData['updateTime'] = time();
        $updateDetailsData = $updateData['details'];
        unset($updateData['details']);

        //查询详情
        $this->objDPurchaseGoods->setTable('qianniao_purchase_goods' . '_' . $this->onlineEnterpriseId);
        $dbResult = $this->objDPurchaseGoods->select(['purchaseId' => $where['id'], 'deleteStatus' => StatusCode::$standard]);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDPurchaseGoods->error(), ErrorCode::$dberror);
        }
        $details = $dbResult;
        unset($dbResult);

        //修改采购单es 入库状态  入库数量
        $updateData['inStatus'] = 5;
        foreach ($details as $value) {
            if($updateDetailsData[$value['skuId']]){
                $inStatus = 5;
                if(bcsub($value['buyerNum'], bcadd($updateDetailsData[$value['skuId']]['inNum'], $value['inNum'])) > 0){
                    $updateData['inStatus'] = 6;
                    $inStatus = 6;
                }
                $updateDetails = [
                    'inNum' => bcadd($updateDetailsData[$value['skuId']]['inNum'], $value['inNum']),
                    'inOfNum' => bcsub($value['inOfNum'], $updateDetailsData[$value['skuId']]['inNum']),
                    'returnOnNum' => bcadd($updateDetailsData[$value['skuId']]['inNum'], $value['returnOnNum']),
                    'inStatus' => $inStatus,
                    'updateTime' => time(),
                ];
                $dbResult = $this->objDPurchaseGoods->update($updateDetails, ['id' => $value['id'], 'skuId' => $value['skuId']]);
                if($dbResult === false){
                    return ResultWrapper::fail($this->objDPurchaseGoods->error(), ErrorCode::$dberror);
                }

//                $esId = parent::setEsId($this->onlineEnterpriseId, 'PurchaseDetailsId', $value['id']);
//                $esResult = $this->objDPurchaseGoods->esupdateTypeFieldVaule($updateDetails, $esId);
//                if (!$esResult) {
//                    return ResultWrapper::fail($esResult, ErrorCode::$dberror);
//                }
            }else{
                $updateData['inStatus'] = 6;
            }
        }

        $dbResult = $this->objDPurchase->update($updateData, $where);
        if ($dbResult === false) {
            ResultWrapper::fail($this->objDPurchase->error(), ErrorCode::$dberror);
        }
        $returnData = $dbResult;
        unset($dbResult);
        if($updateData['inStatus']==5){
//            $xxx=AgentTools::addTaskNew($where['id'], $this->onlineEnterpriseId);
        }
        
        return ResultWrapper::success($returnData);
    }

    /**
     * 修改采购单退货状态
     * @param $purchaseId
     * @param $detailsData
     * @return ResultWrapper
     * @throws Exception
     */
    public function updatePurchaseDetailsReturnStatus($purchaseId, $detailsData)
    {
        $updateData['updateTime'] = time();
        //默认全部退货
        $updateData['returnStatus'] = StatusCode::$orderReturn['allReturn'];

        //查询详情
        $this->objDPurchaseGoods->setTable('qianniao_purchase_goods' . '_' . $this->onlineEnterpriseId);
        $dbResult = $this->objDPurchaseGoods->select(['purchaseId' => $purchaseId, 'deleteStatus' => StatusCode::$standard]);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDPurchaseGoods->error(), ErrorCode::$dberror);
        }
        $details = $dbResult;
        unset($dbResult);
        $beginStatus = $this->objDPurchaseGoods->beginTransaction();
        //修改采购单es 入库状态
        foreach ($details as $value) {
            if(isset($detailsData[$value['skuId']])){
                if($detailsData[$value['skuId']]['num'] > $value['returnOnNum']){
                    $this->objDPurchaseGoods->rollBack();
                    return ResultWrapper::fail('退货数量不能大于可退数量', ErrorCode::$paramError);
                }
                $returnStatus = 2;
                if(bcsub($value['returnOnNum'], $detailsData[$value['skuId']]['num']) > 0){
                    //部分退货
                    $updateData['returnStatus'] = StatusCode::$orderReturn['partReturn'];
                    $returnStatus = 1;
                }

                $updateDetails = [
                    'updateTime' => time(),
                    'returnOnNum' => bcsub($value['returnOnNum'], $detailsData[$value['skuId']]['num']),//可退数量
                    'returnNum' => bcadd($detailsData[$value['skuId']]['num'], $value['returnNum']),//退货数量
                    'returnStatus' => $returnStatus
                ];
                //修改数据库
                $dbResult = $this->objDPurchaseGoods->update($updateDetails, ['id' => $value['id'], 'skuId' => $value['skuId']]);
                if($dbResult === false){
                    $this->objDPurchaseGoods->rollBack();
                    return ResultWrapper::fail($this->objDPurchaseGoods->error(), ErrorCode::$dberror);
                }

                //修改es
                /*
                $esId = parent::setEsId($this->onlineEnterpriseId, 'PurchaseDetailsId', $value['id']);
                $esResult = $this->objDPurchaseGoods->esupdateTypeFieldVaule($updateDetails, $esId);
                if (!$esResult) {
                    $this->objDPurchaseGoods->rollBack();
                    return ResultWrapper::fail($esResult, ErrorCode::$dberror);
                }*/
            }else{
                //部分退货
                $updateData['returnStatus'] = StatusCode::$orderReturn['partReturn'];
            }
        }

        //修改采购单
        $dbResult = $this->objDPurchase->update($updateData, ['id' => $purchaseId]);
        if ($dbResult === false) {
            $this->objDPurchaseGoods->rollBack();
            ResultWrapper::fail($this->objDPurchase->error(), ErrorCode::$dberror);
        }
        $returnData = $dbResult;
        unset($dbResult);
        $beginStatus && $this->objDPurchaseGoods->commit();
        return ResultWrapper::success($returnData);
    }

    /**
     * 编辑采购订单
     * @param $params
     * @return ResultWrapper
     * @throws Exception
     */
    public function editPurchase($params)
    {
        if (empty($params['id'])) {
            return ResultWrapper::fail('没有id', ErrorCode::$paramError);
        }

        $id = $params['id'];
        $deleteArray = $params['deleteArray'];
        unset($params['id']);
        unset($params['source']);
        unset($params['deleteArray']);

        $this->objDPurchase->beginTransaction();
        $goodData = $params['goodsData'];
        unset($params['goodsData']);

        $purchaseAmount = 0; //采购总额
        $goodsNum = 0; // 统计采购订单总商品数
        foreach ($goodData as $key => $val) {
            $goodsNum = bcadd($val['buyerNum'], $goodsNum, 2);
            $purchaseAmount = bcadd($purchaseAmount, $val['subtotalPrice'], 4);
            $goodData[$key]['inOfNum'] = $val['buyerNum'];
        }
        $params['purchaseAmount'] = $purchaseAmount;
        $params['goodsNum'] = $goodsNum;
        $dbResult = $this->objDPurchase->update($params, $id);
        if ($dbResult === false) {
            $this->objDPurchase->rollBack();
            return ResultWrapper::fail($this->objDPurchase->error(), ErrorCode::$dberror);
        }
        unset($dbResult);

        $objPurchaseGoods = new MPurchaseGoods($this->onlineUserId, $this->onlineEnterpriseId);
        $dbResult = $objPurchaseGoods->editPurchaseGoods($goodData, ['purchaseId' => $id, 'deleteArray' => $deleteArray]);

        if (!$dbResult->isSuccess()) {
            $this->objDPurchase->rollBack();
            return ResultWrapper::fail($dbResult->getData(), ErrorCode::$dberror);
        }

        $this->objDPurchase->commit();
        return ResultWrapper::success($dbResult);

    }

    /**
     * 更新审核状态
     * @param $params
     * @return ResultWrapper
     * @throws Exception
     */
    public function updateAuditStatus($params)
    {
        $id = $params['id'];
        unset($params['id']);
        $sql = "select *,p.id as pid,g.id as gid from " . $this->objDPurchase->get_Table() . " p left join qianniao_purchase_goods_" . $this->onlineEnterpriseId . " g on p.id = g.purchaseId where p.id = " . $id . " and p.deleteStatus = " . StatusCode::$standard . ' and g.deleteStatus = ' . StatusCode::$standard;
        $purchaseData = $this->objDPurchase->query($sql);
        if ($purchaseData === false) {
            return ResultWrapper::fail($this->objDPurchase->error(), ErrorCode::$dberror);
        }
        if (empty($purchaseData)) {
            return ResultWrapper::fail('审核的单据不存在', ErrorCode::$contentNotExists);
        }

        if ($purchaseData[0]['auditStatus'] == StatusCode::$auditStatus['auditPass']) {
            return ResultWrapper::fail('当前单据已经审核通过', ErrorCode::$notAllowAccess);
        }

        $beginStatus = $this->objDPurchase->beginTransaction();
        $dbResult = $this->objDPurchase->update($params, $id);
        if ($dbResult === false) {
            $this->objDPurchase->rollBack();
            return ResultWrapper::fail($this->objDPurchase->error(), ErrorCode::$dberror);
        }

        if($purchaseData[0]['purchaseType'] == StatusCode::$standard){
            $source = StatusCode::$orderType['merchantPurchase'];
            $type = StatusCode::$orderType['merchantPurchaseIn'];
        }else{
            $source = StatusCode::$orderType['purchaseOrder'];
            $type = StatusCode::$orderType['purchaseIn'];
        }


        $purchaseInData = [
            'sourceId'       => $purchaseData[0]['purchaseId'],//来源id
            'sourceNo'       => $purchaseData[0]['no'],//来源单号
            'materielNum'    => 0, //入库数量
            'merchantId'     => $purchaseData[0]['merchantId'],//商户id
            'originId'       => $purchaseData[0]['purchaseId'],//源头id
            'originNo'       => $purchaseData[0]['no'],//源头单号
            'shopId'         => $purchaseData[0]['shopId'],
            'warehouseId'    => $purchaseData[0]['warehouseId'],//仓库id
            'warehouseName'  => $purchaseData[0]['warehouseName'],//仓库名称
            'operatorId'     => $purchaseData[0]['operatorId'], //制单人id
            'operatorName'   => $purchaseData[0]['operatorName'], //制单人姓名
            'source'         => $source,
            'type'           => $type,
            'orderGoodsData' => []
        ];
        $amount = 0;
        foreach ($purchaseData as $key => $value) {
            $purchaseInData['materielNum']++;
            $amount += $value['subtotalPrice'];
            $purchaseInData['orderGoodsData'][] = [
                'materielId'   => $value['basicGoodsId'],
                'materielName' => $value['goodsName'],
                'materielCode' => $value['goodsCode'],
                'skuId'        => $value['skuId'],
                'unitName'     => isset($value['unitName']) ? $value['unitName'] : '',
                'skuName'      => isset($value['skuName']) ? $value['skuName'] : '',
                'num'          => $value['buyerNum'],
                'otherNum'          => $value['otherNum'],
                'unitPrice'    => $value['buyerUnitPrice'],
                'totalPrice'   => $value['subtotalPrice'],
            ];
            //更新es审核
            /*
            $esId = parent::setEsId($this->onlineEnterpriseId, 'PurchaseDetailsId', $value['gid']);
            $esResult = $this->objDPurchaseGoods->esupdateTypeFieldVaule($params, $esId);
            if (!$esResult) {
                return ResultWrapper::fail($esResult, ErrorCode::$dberror);
            }*/
        }
        $purchaseInData['operatorId'] = $params['auditId'];
        $purchaseInData['operatorName'] = $params['auditName'];
        $purchaseInData['amount'] = $amount;
        $objMInventoryIn = new MInventoryIn($this->onlineEnterpriseId, $this->onlineUserId);
        $dbResult = $objMInventoryIn->addInventoryIn($purchaseInData);
        if (!$dbResult->isSuccess()) {
            $this->objDPurchase->rollBack();
            return ResultWrapper::fail($dbResult->getData(), ErrorCode::$dberror);
        }
        $beginStatus && $this->objDPurchase->commit();
        return ResultWrapper::success($dbResult->getData());
    }

    /**
     * 删除采购单
     * @param $id
     * @return ResultWrapper
     */
    public function delPurchase($id)
    {
        $dbResult = $this->objDPurchase->update(['deleteStatus' => StatusCode::$delete], $id);

        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDPurchase->error(), ErrorCode::$dberror);
        } else {
            return ResultWrapper::success($dbResult);
        }
    }

    /**
     * 采购单列表
     * @param $selectParams
     * @param $export
     * @return ResultWrapper
     * @throws Exception
     */
    public function getAllPurchase($selectParams, $export)
    {
        $selectParams = parent::getStaffQueryParams($selectParams, 'buyerId');
        $limit = $selectParams['limit'];
        unset($selectParams['limit']);
        $offset = $selectParams['offset'];
        unset($selectParams['offset']);
        $isSelectInventory = isset($selectParams['isSelectInventory']) ? $selectParams['isSelectInventory'] : true;
        unset($selectParams['isSelectInventory']);

        $selectParams['deleteStatus'] = StatusCode::$standard;

        //查询商铺绑定仓库
        if(isset($selectParams['shopId']) && !empty($selectParams['shopId'])){
            $objMShop = new MShop($this->onlineEnterpriseId);
            $modelResult = $objMShop->getShopBindWarehouse($selectParams['shopId']);
            if(!$modelResult->isSuccess()){
                return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
            }
            $shop = $modelResult->getData();
            unset($modelResult);
            if(empty($shop)){
                return ResultWrapper::fail('商铺查询失败', ErrorCode::$dberror);
            }
            $selectParams['warehouseId'] = $shop['warehouseId'];
        }

        if ($export) {
            $modelResult = self::export($selectParams);
            if (!$modelResult->isSuccess()) {
                return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
            }
            exit;
        }

        $dbResult = $this->objDPurchase->select($selectParams, '*', 'createTime desc', $limit, $offset);

        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDPurchase->error(), ErrorCode::$dberror);
        }
        $total = $this->objDPurchase->count($selectParams);

        $purchaseData = self::format($dbResult);

        $return = [
            'data'  => $purchaseData,
            'total' => ($total) ? intval($total) : 0,
        ];
        $objMInventory = new MInventory($this->onlineEnterpriseId, $this->onlineUserId);
        $objMInventory->updateCache = true;

        return ResultWrapper::success($return);
    }

    /**
     * 根据采购单查询批次商品sku剩余库存数量
     * @param $purchaseId
     * @return ResultWrapper
     */
    public function getInventoryBatchNum($purchaseId)
    {
        $dbResult = $this->objDPurchase->get(['id' => $purchaseId, 'deleteStatus' => StatusCode::$standard]);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDPurchase->error, ErrorCode::$dberror);
        }
        if (empty($dbResult)) {
            return ResultWrapper::fail('采购单据查询失败', ErrorCode::$dberror);
        }
        $purchaseData = $dbResult;
        unset($dbResult);
        $dbResult = $this->objDPurchaseGoods->select(['purchaseId' => $purchaseId, 'deleteStatus' => StatusCode::$standard]);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDPurchaseGoods->error, ErrorCode::$dberror);
        }
        if (empty($dbResult)) {
            return ResultWrapper::fail('采购单据详情查询失败', ErrorCode::$dberror);
        }
        $purchaseData['goodsData'] = $dbResult;
        unset($dbResult);

        $objMInventory = new MInventory($this->onlineEnterpriseId, $this->onlineUserId);
        foreach ($purchaseData['goodsData'] as $value) {
            $skuIds[] = $value['skuId'];
        }
        $modelResult = $objMInventory->getBatchDataByOriginId($purchaseData['warehouseId'], $purchaseData['id'], $skuIds);
        if (!$modelResult->isSuccess()) {
            return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
        }
        $batchData = $modelResult->getData();
        if (empty($batchData)) {
            return ResultWrapper::fail('批次数据查询失败', ErrorCode::$paramError);
        }

        // 采购订单有多个入库批次情况
        foreach ($batchData as $key => $value){
            $batchData[$value['skuId']]['num'] += $value['num'];
        }

        foreach ($purchaseData['goodsData'] as &$value) {
            $value['inventoryBatchNum'] = 0;
            if (isset($batchData[$value['skuId']])) {
                $value['inventoryBatchNum'] = $batchData[$value['skuId']]['num'];
            }
        }
        return ResultWrapper::success($purchaseData);
    }

    /**
     * 采购汇总
     * @param $selectParams
     * @param $type
     * @return ResultWrapper
     * @throws Exception
     */
    public function getAllPurchaseByFields($selectParams, $type ,$export = 0)
    {
        $defaultDbName = Factory::config()->get('db.default.dbname');
        $limit = $selectParams['limit'];
        unset($selectParams['limit']);
        $offset = $selectParams['offset'];
        unset($selectParams['offset']);
        $onReturn = $selectParams['onReturn'];
        unset($selectParams['onReturn']);
        if($export){
            $limit = 999;
            $offset = 0;
        }
        $groupBySql = '';
        if ($type == 1) {//商品
            $groupBySql = ' GROUP BY g.basicGoodsId';
        } elseif ($type == 2) {//供应商
            $groupBySql = ' GROUP BY p.supplierId,g.basicGoodsId';
        } elseif ($type == 3) {//采购人员
            $groupBySql = ' GROUP BY p.buyerId,g.basicGoodsId';
        } elseif($type  == 4){
            $groupBySql = ' GROUP BY p.shopId,g.basicGoodsId';
        }else {
            return ResultWrapper::fail('type参数错误', ErrorCode::$paramError);
        }

        $whereSql = '';
        if (isset($selectParams['warehouseId']) && !empty($selectParams['warehouseId'])) {
            $where = empty($whereSql) ? ' WHERE ' : ' AND ';
            $whereSql .= $where . ' p.warehouseId = ' . $selectParams['warehouseId'];
        }
        if (isset($selectParams['inStatus']) && !empty($selectParams['inStatus'])) {
            $where = empty($whereSql) ? ' WHERE ' : ' AND ';
            $whereSql .= $where . ' p.inStatus = ' . $selectParams['inStatus'];
        }
        if (isset($selectParams['goodsName']) && !empty($selectParams['goodsName'])) {
            $where = empty($whereSql) ? ' WHERE ' : ' AND ';
            $whereSql .= $where . ' g.goodsName LIKE "%' . $selectParams['goodsName'] . '%" ';
        }
        if (isset($selectParams['categoryId']) && !empty($selectParams['categoryId'])) {
            $where = empty($whereSql) ? ' WHERE ' : ' AND ';
            $whereSql .= $where . ' g.categoryId = ' . $selectParams['categoryId'];
        }
        if (isset($selectParams['start']) && !empty($selectParams['start']) && isset($selectParams['end']) && !empty($selectParams['end'])) {
            $where = empty($whereSql) ? ' WHERE ' : ' AND ';
            $whereSql .= $where . ' p.createTime BETWEEN ' . $selectParams['start'] . ' AND ' . $selectParams['end'];
        }
        if (isset($selectParams['supplierId']) && !empty($selectParams['supplierId'])) {
            $where = empty($whereSql) ? ' WHERE ' : ' AND ';
            $whereSql .= $where . ' p.supplierId = ' . $selectParams['supplierId'];
        }
        if (isset($selectParams['buyerId']) && !empty($selectParams['buyerId'])) {
            $where = empty($whereSql) ? ' WHERE ' : ' AND ';
            $whereSql .= $where . ' p.buyerId = ' . $selectParams['buyerId'];
        }
        if (isset($selectParams['shopId']) && !empty($selectParams['shopId'])) {
            $where = empty($whereSql) ? ' WHERE ' : ' AND ';
            $whereSql .= $where . ' p.shopId = ' . $selectParams['shopId'];
        }
        

        //统计已审核 未删除主单据 未删除详情 的采购订单
        $where = empty($whereSql) ? ' WHERE ' : ' AND ';
        $whereSql .= $where . ' p.auditStatus = ' . StatusCode::$auditStatus['auditPass'] . ' AND p.deleteStatus = ' . StatusCode::$standard . ' AND g.deleteStatus = ' . StatusCode::$standard;
        $sql = 'SELECT p.warehouseId,p.warehouseName,p.id,p.`no`,p.buyerId,p.buyerName,p.supplierId,p.supplierName,p.operatorId,p.operatorName,p.inStatus,s.name as shopName,g.skuId,g.categoryId,g.categoryName,g.basicGoodsId AS materielId,g.goodsName AS materielName,g.goodsCode AS materielCode,SUM(g.buyerNum) AS allNum,SUM(g.subtotalPrice) AS total,(SUM(g.subtotalPrice) / SUM(g.buyerNum)) AS costPrice, SUM(g.otherNum) AS otherNum '
                . 'FROM ' . $this->objDPurchase->get_Table() . ' p '
                . 'LEFT JOIN `'.$defaultDbName.'`.'.$this->objDShop->get_Table().' s ON s.id = p.shopId '
                . 'LEFT JOIN ' . $this->objDPurchaseGoods->get_Table() . ' g ON p.id = g.purchaseId '
                . $whereSql . ' ' . $groupBySql . ' '
                . 'ORDER BY p.createTime DESC LIMIT ' . $offset . ' , ' . $limit;

        $dbResult = $this->objDPurchase->query($sql);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDPurchase->error(), ErrorCode::$dberror);
        }
        $selectData = $dbResult;
        unset($dbResult);
        $totalSql = 'SELECT COUNT(id) AS total FROM (SELECT p.id FROM ' . $this->objDPurchase->get_Table() . ' p '
                . 'LEFT JOIN `'.$defaultDbName.'`.'.$this->objDShop->get_Table().' s ON s.id = p.shopId '
                . 'LEFT JOIN ' . $this->objDPurchaseGoods->get_Table() . ' g ON p.id = g.purchaseId ' . $whereSql . ' ' . $groupBySql . ') AS selectData';
        $dbResult = $this->objDPurchase->query($totalSql);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDPurchase->error(), ErrorCode::$dberror);
        }
        $countData = array_shift($dbResult);
        unset($dbResult);

        //判断是否需要退货
        /*if ($onReturn) {
            //查询所有已退货的采购单  查询条件 已审核 未删除主单据 未删除详情 的采购退货单 关联 采购单
            $objMPurchaseOut = new MPurchaseOut($this->onlineUserId, $this->onlineEnterpriseId);
            $modelResult = $objMPurchaseOut->getReturnDataByShopIds([$selectParams['shopId']]);
            if (!$modelResult->isSuccess()) {
                return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
            }
            $purchaseOutData = $modelResult->getData();
            foreach ($selectData as &$value) {
                if (isset($purchaseOutData[$value['materielId']])) {
                    $value['allNum'] = bcsub($value['allNum'], $purchaseOutData[$value['materielId']]['num']);
                    $value['total'] = bcmul($value['allNum'], $value['costPrice']);
                }
            }
            unset($value);
        }*/

        $return = [
            'data'  => parent::formatOrderMan($this->onlineEnterpriseId, $selectData),
            'total' => ($countData['total']) ? intval($countData['total']) : 0,
        ];
        //导出
       if($export){
           self::exportPurchaseByFields($return['data']);
           exit;
       }
        return ResultWrapper::success($return);
    }

    /**
     * 汇总搜索  (暂未使用)
     * @param $params
     * @param $type
     * @param $export
     * @return ResultWrapper
     */
    public function searchAllPurchaseByFields($params, $type, $export)
    {
        $onReturn = $params['onReturn'];
        unset($params['onReturn']);
        $defaultDSL = ['from' => $params['offset'], 'size' => $params['limit'], 'sort' => ['createTime' => ['order' => 'desc']]];
        $selectParams = [];

        $groupBySql = '';
        if ($type == 1) {//商品
            $groupBySql = ' GROUP BY g.basicGoodsId';
        } elseif ($type == 2) {//供应商
            $groupBySql = ' GROUP BY p.supplierId,g.basicGoodsId';
        } elseif ($type == 3) {//采购人员
            $groupBySql = ' GROUP BY p.buyerId,g.basicGoodsId';
        } else {
            return ResultWrapper::fail('type参数错误', ErrorCode::$paramError);
        }

        $selectParams[] = ['term' => ['enterpriseId' => $this->onlineEnterpriseId]];
        !empty($params['categoryId']) && $selectParams[] = ['term' => ['categoryId' => $params['categoryId']]];
        !empty($params['shopId']) && $selectParams[] = ['term' => ['shopId' => $params['shopId']]];
        !empty($params['inStatus']) && $selectParams[] = ['term' => ['inStatus' => $params['inStatus']]];
        (!empty($params['start']) && !empty($params['end'])) && $selectParams[] = ['range' => ['createTime' => ['gte' => $params['start'], 'lte' => $params['end']]]];
        !empty($params['search']) && $selectParams[] = ['multi_match' => ['fields' => ['goodsName', 'goodsCode'], 'query' => $params['search'], 'fuzziness' => 'AUTO']];
        $dsl = [];
        !empty($selectParams) && $dsl['query']['bool']['must'][] = $selectParams;
        $dsl = array_merge($defaultDSL, $dsl);
      
        $dbResult = $this->objDPurchaseGoods->getSearchQueryDsl($dsl);
        if (isset($dbResult['error'])) {
            return ResultWrapper::fail($dbResult, ErrorCode::$dberror);
        }
        $returnData = parent::formatEsSelectData($dbResult, $this->onlineEnterpriseId, StatusCode::$orderType['purchaseOrder']);

        return ResultWrapper::success($returnData);
    }

    /**
     * 查询采购数据和详情数据
     * @param $selectParams
     * @return ResultWrapper
     * @throws Exception
     */
    public function getAllPurchaseAndDetails($selectParams)
    {
        $this->objDPurchaseGoods->setTable('qianniao_purchase_goods' . '_' . $this->onlineEnterpriseId);

        $limit = $selectParams['limit'];
        unset($selectParams['limit']);
        $offset = $selectParams['offset'];
        unset($selectParams['offset']);
        $field = 'p.*,g.basicGoodsId,g.goodsName,g.goodsCode,g.skuId,g.buyerNum,g.buyerUnitPrice,g.subtotalPrice';
        $where = ' where p.deleteStatus = ' . StatusCode::$standard;
        isset($selectParams['orderStatus']) && $where .= ' and p.orderStatus = ' . $selectParams['orderStatus'];
        $orderBy = ' order by p.createTime desc ';
        $limitSql = ' limit ' . $offset . ',' . $limit;
        $sql = 'select ' . $field . ' from ' . $this->objDPurchase->get_Table() . ' p left join ' . $this->objDPurchaseGoods->get_Table() . ' g on p.id = g.purchaseId' . $where . $orderBy . $limitSql;
        $dbResult = $this->objDPurchase->query($sql);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDPurchase->error(), ErrorCode::$dberror);
        }
        $field = 'count(g.id) as count';
        $sql = 'select ' . $field . ' from ' . $this->objDPurchase->get_Table() . ' p left join ' . $this->objDPurchaseGoods->get_Table() . ' g on p.id = g.purchaseId' . $where;
        $totalData = $this->objDPurchase->query($sql);
        if ($totalData === false) {
            return ResultWrapper::fail($this->objDPurchase->error(), ErrorCode::$dberror);
        }
        $total = array_shift($totalData)['count'];
        $return = [
            'data'  => $dbResult,
            'total' => ($total) ? intval($total) : 0,
        ];

        return ResultWrapper::success($return);

    }

    /**
     * 采购明细页面数据统计
     *
     * @throws Exception
     */
    public function getAllData()
    {
        $this->objDPurchaseGoods->setTable('qianniao_purchase_goods' . '_' . $this->onlineEnterpriseId);
        //供应商总数
        $objMSupplier = new MSupplier($this->onlineUserId, $this->onlineEnterpriseId);
        $modelResult = $objMSupplier->getAllSupplierNum();
        if (!$modelResult->isSuccess()) {
            return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
        }
        $data['supplierNum'] = $modelResult->getData();
        unset($modelResult);
        //采购订单总数
        $dbResult = $this->objDPurchase->count(['deleteStatus' => StatusCode::$standard]);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDPurchase->error(), ErrorCode::$dberror);
        }
        $data['purchaseNum'] = $dbResult;
        unset($dbResult);
        //采购总金额
        $sql = "select sum(purchaseAmount) amount from " . $this->objDPurchase->get_Table() . " where deleteStatus = " . StatusCode::$standard;
        $dbResult = $this->objDPurchase->query($sql);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDPurchase->error(), ErrorCode::$dberror);
        }
        $data['purchaseAmount'] = array_shift($dbResult)['amount'];
        unset($dbResult);
        //商品种类数量(根据商品skuId)
        $sql = "SELECT count(1) as count FROM (SELECT skuId FROM " . $this->objDPurchaseGoods->get_Table() . " GROUP BY skuId) as skuData";
        $dbResult = $this->objDPurchaseGoods->query($sql);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDPurchaseGoods->error(), ErrorCode::$dberror);
        }
        $data['skuNum'] = array_shift($dbResult)['count'];
        unset($dbResult);
        //商品总数
        $sql = "select sum(buyerNum) as num from " . $this->objDPurchaseGoods->get_Table() . " where deleteStatus = " . StatusCode::$standard;
        $dbResult = $this->objDPurchaseGoods->query($sql);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDPurchaseGoods->error(), ErrorCode::$dberror);
        }
        $data['goodsNum'] = array_shift($dbResult)['num'];
        unset($dbResult);
        return ResultWrapper::success($data);
    }

    /**
     * 采购明细
     * @param $selectParams
     * @param $export
     * @return ResultWrapper
     * @throws Exception
     */
    public function getAllPurchaseDetails($selectParams, $export = 0)
    {
        $limit = $selectParams['limit'];
        unset($selectParams['limit']);
        $offset = $selectParams['offset'];
        unset($selectParams['offset']);

        $this->objDPurchaseGoods->setTable('qianniao_purchase_goods' . '_' . $this->onlineEnterpriseId);
        $this->objDPurchase->setTable('qianniao_purchase' . '_' . $this->onlineEnterpriseId);

        $whereSql = '';
        if(!empty($selectParams['merchantId'])){
            $whereSql .= ' and p.merchantId = '.$selectParams['merchantId'];
        }
        if(!empty($selectParams['shopId'])){
            $whereSql .= ' and p.shopId = '.$selectParams['shopId'];
        }
        if(!empty($selectParams['categoryId'])){
            $whereSql .= ' and g.categoryId = '.$selectParams['categoryId'];
        }
        if(!empty($selectParams['supplierId'])){
            $whereSql .= ' and p.supplierId = '.$selectParams['supplierId'];
        }
        if(!empty($selectParams['auditStatus'])){
            $whereSql .= ' and p.auditStatus = '.$selectParams['auditStatus'];
        }
        if(!empty($selectParams['start']) && !empty($selectParams['end'])){
            $whereSql .= ' and p.createTime between '.$selectParams['start'].' and '.$selectParams['end'];
        }
        if(!empty($selectParams['search'])){
            $whereSql .= ' and g.goodsName like "%'.$selectParams['search'].'%" ';
        }

        $sql = "select p.merchantId,p.no,p.inStatus,p.supplierName,p.buyerName,p.remark,p.operatorName,g.id,g.goodsName,g.buyerNum,g.buyerUnitPrice,g.subtotalPrice,g.basicGoodsId,g.skuId,g.otherNum from " . $this->objDPurchase->get_Table() . " p LEFT JOIN " . $this->objDPurchaseGoods->get_Table() . " g on p.id = g.purchaseId where g.deleteStatus = " . StatusCode::$standard . $whereSql . " ORDER BY g.createTime desc ";

        if ($export) {
            $result = $this->objDPurchase->exportQuery($sql);
            if ($result === false) {
                return ResultWrapper::fail($this->objDPurchase->error(), ErrorCode::$dberror);
            }
            $modelResult = self::formatPurchaseDetails($result);
            if (!$modelResult->isSuccess()) {
                return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
            }
            $data = $modelResult->getData();
            self::exportPurchaseDetails($data);
            exit;
        }
        $sql .= " limit " . $offset . "," . $limit;
        $dbResult = $this->objDPurchase->query($sql);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDPurchase->error(), ErrorCode::$dberror);
        }
        $sql = "select count(g.id) as count from " . $this->objDPurchase->get_Table() . " p LEFT JOIN " . $this->objDPurchaseGoods->get_Table() . " g on p.id = g.purchaseId where g.deleteStatus = " . StatusCode::$standard. $whereSql;
        $totalData = $this->objDPurchase->query($sql);
        if ($totalData === false) {
            return ResultWrapper::fail($this->objDPurchase->error(), ErrorCode::$dberror);
        }
        $total = array_shift($totalData)['count'];
        $modelResult = self::formatPurchaseDetails($dbResult);
        if (!$modelResult->isSuccess()) {
            return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
        }
        $data = $modelResult->getData();
        $return = [
            'data'  => $data,
            'total' => ($total) ? intval($total) : 0,
        ];

        return ResultWrapper::success($return);
    }

    /**
     * 采购明细搜索
     * @param $params
     * @param $export
     * @return ResultWrapper
     * @throws Exception
     */
    public function searchAllPurchaseDetails($params, $export)
    {
        $defaultDSL = ['from' => $params['offset'], 'size' => $params['limit'], 'sort' => ['createTime' => ['order' => 'desc']]];
        $selectParams = [];
        $selectParams[] = ['term' => ['enterpriseId' => $this->onlineEnterpriseId]];
        !empty($params['categoryId']) && $selectParams[] = ['term' => ['categoryId' => $params['categoryId']]];
        !empty($params['shopId']) && $selectParams[] = ['term' => ['shopId' => $params['shopId']]];
        !empty($params['supplierId']) && $selectParams[] = ['term' => ['supplierId' => $params['supplierId']]];
        !empty($params['auditStatus']) && $selectParams[] = ['term' => ['auditStatus' => $params['auditStatus']]];
        (!empty($params['start']) && !empty($params['end'])) && $selectParams[] = ['range' => ['createTime' => ['gte' => $params['start'], 'lte' => $params['end']]]];
        !empty($params['search']) && $selectParams[] = ['multi_match' => ['fields' => ['goodsName', 'goodsCode'], 'query' => $params['search'], "type" => "best_fields", "tie_breaker" => 0.3, "minimum_should_match" => "50%"]];
        $dsl = [];
        !empty($selectParams) && $dsl['query']['bool']['must'][] = $selectParams;
        $dsl = array_merge($defaultDSL, $dsl);

        //导出
        if ($export) {
            $esResult = $this->objDPurchaseGoods->getScrollSearchQueryDsl($dsl);
            if (isset($esResult['error'])) {
                return ResultWrapper::fail($esResult, ErrorCode::$dberror);
            }
            $formatData = parent::formatEsSelectData($esResult);
            $modelResult = self::formatPurchaseDetails($formatData['data']);
            if (!$modelResult->isSuccess()) {
                return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
            }
            $formatData['data'] = $modelResult->getData();
            self::exportPurchaseDetails($formatData['data']);
            exit;
        }
        $dbResult = $this->objDPurchaseGoods->getSearchQueryDsl($dsl);
        if (isset($dbResult['error'])) {
            return ResultWrapper::fail($dbResult, ErrorCode::$dberror);
        }
        $formatData = parent::formatEsSelectData($dbResult);
        $modelResult = self::formatPurchaseDetails($formatData['data']);
        if (!$modelResult->isSuccess()) {
            return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
        }
        $formatData['data'] = $modelResult->getData();
        return ResultWrapper::success($formatData);
    }

    /**
     * 采购明细导出方法
     * @param $result
     * @return void
     * @throws Exception
     */
    public function exportPurchaseDetails($result)
    {
        //导出到本地
        header("Content-type:application/vnd.ms-excel");
        header("Content-Disposition:filename=采购明细记录表.csv");
        header('Cache-Control: max-age=0');

        $fp = fopen('php://output', 'a');

        $head = ['序号', '采购单号', '商品编号', '商品名称', '单位', '属性', '分类', '品牌', '采购数量','其他单位', '采购单价', '采购金额', '入库状态', '供应商'];       //定义标题

        foreach ($head as $i => $v) {
            $head[$i] = mb_convert_encoding($v, 'GBK', 'utf-8');     //将中文标题转换编码，否则乱码
        }

        fputcsv($fp, $head);

        $limit = 10000;
        $num = 0;                                         //计数器
        foreach ($result as $v) {                           //循环数据
            $num++;
            if ($num == $limit) {
                ob_flush();         //释放内存
                flush();
            }

            $rows['id'] = isset($v['id']) ? $v['id'] : null;
            $rows['no'] = isset($v['no']) ? $v['no'] : null;
            $rows['goodsCode'] = isset($v['goodsCode']) ? $v['goodsCode'] : null;
            $rows['goodsName'] = isset($v['goodsName']) ? $v['goodsName'] : null;
            $rows['unitName'] = isset($v['unitName']) ? $v['unitName'] : null;
            $rows['skuName'] = isset($v['skuName']) ? $v['skuName'] : null;
            $rows['categoryName'] = isset($v['categoryName']) ? $v['categoryName'] : null;
            $rows['brandName'] = isset($v['brandName']) ? $v['brandName'] : null;
            $rows['buyerNum'] = isset($v['buyerNum']) ? $v['buyerNum'] : null;
            $rows['otherNum'] = isset($v['otherNum']) ? $v['otherNum'] : null;
            $rows['buyerUnitPrice'] = isset($v['buyerUnitPrice']) ? $v['buyerUnitPrice'] : null;
            $rows['subtotalPrice'] = isset($v['subtotalPrice']) ? $v['subtotalPrice'] : null;
            $rows['inStatus'] = isset($v['inStatus']) ? $v['inStatus'] == StatusCode::$standard ? '已入库' : '未入库' : null;
            $rows['supplierName'] = isset($v['supplierName']) ? $v['supplierName'] : null;
            foreach ($rows as $kk => $vv) {
                $rs[$kk] = mb_convert_encoding($vv, 'GBK', 'utf-8');  //转译编码
            }
            fputcsv($fp, $rs);

            $rows = [];
        }
    }

    /**
     * 导出方法
     * @param $condition
     * @return ResultWrapper
     * @throws Exception
     */
    public function export($condition)
    {
        $result = $this->objDPurchase->exportSelect($condition, 'id,no,supplierName,purchaseAmount,buyerName,operatorName,createTime,auditStatus');
        if ($result === false) {
            return ResultWrapper::fail($this->objDPurchase->error(), ErrorCode::$dberror);
        }

        $formatIds = [];
        $formatData = [];
        foreach ($result as $value) {
            $formatData[$value['id']] = $value;
            $formatIds[] = $value['id'];
        }
        $this->objDPurchaseGoods->setTable('qianniao_purchase_goods' . '_' . $this->onlineEnterpriseId);
        $dbResult = $this->objDPurchaseGoods->exportSelect(['purchaseId' => $formatIds, 'deleteStatus' => StatusCode::$standard]);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDPurchaseGoods->error(), ErrorCode::$paramError);
        }

        //导出到本地
        header("Content-type:application/vnd.ms-excel");
        header("Content-Disposition:filename=采购记录表.csv");
        header('Cache-Control: max-age=0');

        $fp = fopen('php://output', 'a');

        $head = ['编号', '采购单号', '供应商', '采购单总金额', '采购人员', '制单人员', '制单日期', '审核状态', '商品名称', '商品编码', '单位', '分类', '采购数量','其他单位', '采购单价', '采购总价'];//定义标题

        foreach ($head as $i => $v) {
            $head[$i] = mb_convert_encoding($v, 'GBK', 'utf-8');//将中文标题转换编码，否则乱码
        }

        fputcsv($fp, $head);

        $limit = 10000;
        $num = 0;//计数器
        foreach ($dbResult as $value) {//循环数据
            $num++;
            if ($num == $limit) {
                ob_flush();//释放内存
                flush();
            }

            $value = parent::formatOrderMan($this->onlineEnterpriseId, $value);

            $v = $formatData[$value['purchaseId']];

            $rows['id'] = isset($v['id']) ? $v['id'] : null;
            $rows['no'] = isset($v['no']) ? $v['no'] : null;
            $rows['supplierName'] = isset($v['supplierName']) ? $v['supplierName'] : null;
            $rows['purchaseAmount'] = isset($v['purchaseAmount']) ? $v['purchaseAmount'] : null;
            $rows['buyerName'] = isset($v['buyerName']) ? $v['buyerName'] : null;
            $rows['operatorName'] = isset($v['operatorName']) ? $v['operatorName'] : null;
            $rows['createTime'] = isset($v['createTime']) ? date('Y-m-d H:i:s', $v['createTime']) : null;
            $rows['auditStatus'] = isset($v['auditStatus']) ? ($v['auditStatus'] == StatusCode::$auditStatus['auditPass'] ? '已审核' : '未审核') : null;

            $rows['goodsName'] = isset($value['goodsName']) ? $value['goodsName'] : null;
            $rows['goodsCode'] = isset($value['goodsCode']) ? $value['goodsCode'] : null;
            $rows['unitName'] = isset($value['unitName']) ? $value['unitName'] : null;
            $rows['categoryName'] = isset($value['categoryName']) ? $value['categoryName'] : null;
            $rows['buyerNum'] = isset($value['buyerNum']) ? $value['buyerNum'] : null;
            $rows['otherNum'] = isset($value['otherNum']) ? $value['otherNum'] : null;
            $rows['buyerUnitPrice'] = isset($value['buyerUnitPrice']) ? $value['buyerUnitPrice'] : null;
            $rows['subtotalPrice'] = isset($value['subtotalPrice']) ? $value['subtotalPrice'] : null;
            foreach ($rows as $kk => $vv) {
                $rs[$kk] = mb_convert_encoding($vv, 'GBK', 'utf-8');  //转译编码
            }
            fputcsv($fp, $rs);

            $rows = [];
        }
        return ResultWrapper::success('成功');
    }

    /**
     * 格式化采购明细列表数据
     * @param $data
     * @return ResultWrapper
     * @throws Exception
     */
    public function formatPurchaseDetails($data)
    {
        if (empty($data)) return ResultWrapper::success($data);
        $skuIds = [];
        $nos = [];
        $basics = [];
        foreach ($data as $value) {
            $skuIds[] = $value['skuId'];
            $nos[] = $value['no'];
            $basics[] = $value['basicGoodsId'];
        }
        //单位name
        $skuNames = [];
        if ($skuIds) {
            $objMSku = new MSku($this->onlineUserId, $this->onlineEnterpriseId);
            $return = $objMSku->getNameByIds($skuIds);
            if (!$return->isSuccess()) {
                return ResultWrapper::fail($return->getData(), $return->getErrorCode());
            }
            $skuNames = $return->getData();
            unset($return);
        }

        //采购入库 入库状态
        $purchaseInData = [];
        if ($nos) {
            $objMInventoryIn = new MInventoryIn($this->onlineEnterpriseId, $this->onlineUserId);
            $modelResult = $objMInventoryIn->getAllInventoryInByNo($nos);
            if (!$modelResult->isSuccess()) {
                return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
            }
            $purchaseInData = $modelResult->getData();
            unset($modelResult);
        }
        //分类信息
        $categoryData = [];
        $brandData = [];
        if ($basics) {
            $objMGoodsBasic = new MGoodsBasic($this->onlineUserId, $this->onlineEnterpriseId);
            $modelResult = $objMGoodsBasic->getCategoryByIds($basics);
            if (!$modelResult->isSuccess()) {
                return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
            }
            $categoryData = $modelResult->getData();
            unset($modelResult);

            $modelResult = $objMGoodsBasic->getBrandByIds($basics);
            if (!$modelResult->isSuccess()) {
                return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
            }
            $brandData = $modelResult->getData();
            unset($modelResult);
        }
        foreach ($data as $key => &$value) {
            $value['goodsCode'] = createCode(StatusCode::$code['goodsBasic']['prefix'], $value['basicGoodsId'], StatusCode::$code['goodsBasic']['length']);
            $nos && $value['purchaseInStatus'] = isset($purchaseInData[$value['no']]) ? $purchaseInData[$value['no']]['auditStatus'] : StatusCode::$delete;
            $basics && $value['categoryName'] = isset($categoryData[$value['basicGoodsId']]) ? $categoryData[$value['basicGoodsId']]['title'] : null;
            $basics && $value['brandName'] = isset($brandData[$value['basicGoodsId']]) ? $brandData[$value['basicGoodsId']]['title'] : null;

        }
        $data = parent::formatOrderMan($this->onlineEnterpriseId, $data, StatusCode::$orderType['purchaseOrder']);
        return ResultWrapper::success($data);
    }

    /**
     * 格式化采购列表
     * @param $data
     * @return mixed
     * @throws Exception
     */
    private function format($data)
    {
        if (isset($data['id'])) {
            $dimension = $data;
            unset($data);
            $data[] = $dimension;
        }

        $allPurchaseIds = [];
        foreach ($data as $key => $val) {
            $allPurchaseIds[] = $val['id'];
        }

        $objMPurchaseGoods = new MPurchaseGoods($this->onlineUserId, $this->onlineEnterpriseId);
        $dbResult = $objMPurchaseGoods->getGoodsByPurchaseIds($allPurchaseIds);

        if (!$dbResult->isSuccess()) {
            return $data;
        }

        $goodsData = $dbResult->getData();

        $allSkuIds = array_column($goodsData, 'skuId');
        //sku信息
        $objMSku = new MSku($this->onlineUserId, $this->onlineEnterpriseId);
        $selectParams = [
            'id' => $allSkuIds,
        ];
        $skuData = [];
        $dbResult = $objMSku->getSkuInfo($selectParams, '*', false);
        if ($dbResult->isSuccess()) {
            $skuData = $dbResult->getData();
        }

        foreach ($skuData as $key => $value) {
            $allSkuData[$value['id']] = $value;
        }

        foreach ($goodsData as $key => &$value) {
            $value['unit'] = isset($allSkuData[$value['skuId']]) ? $allSkuData[$value['skuId']] : '';
            $allGoodsData[$value['purchaseId']][] = $value;
        }

        //查询商户
        $merchantIds = array_column($data,'merchantId');
        if(!empty($merchantIds)){
            $objMMerchant = new MMerchant($this->onlineEnterpriseId, $this->onlineUserId);
            $modelResult = $objMMerchant->selectMerchantData(['id' => $merchantIds]);
            $merchantData = [];
            if($modelResult->isSuccess()){
                $merchantResult = $modelResult->getData();
                foreach($merchantResult as $value){
                    $merchantData[$value['id']] = $value;
                }
            }
        }


        foreach ($data as $key => &$value) {
            //渲染采购入库前缀
            $value['no'] = StatusCode::$noPrefix[2] .'-'. $value['no'];
            $value['goodsData'] = [];
            if (isset($allGoodsData[$value['id']])) {
                $value['goodsData'] = $allGoodsData[$value['id']];
            }
            $value['merchantName'] = isset($merchantData[$value['merchantId']]) ? $merchantData[$value['merchantId']]['name'] : '';
        }

        return $data;
    }

    /**
     * 根据nos数组查询多条采购订单数据
     * @param $nos
     * @return array|ResultWrapper
     */
    public function getAllPurchaseByNos($nos)
    {
        if (empty($nos)) return $nos;
        $dbResult = $this->objDPurchase->select(['no' => $nos]);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDPurchase->error(), ErrorCode::$dberror);
        }
        if (empty($dbResult)) return ResultWrapper::fail('采购订单数据为空', ErrorCode::$paramError);
        $returnData = [];
        foreach ($dbResult as $value) {
            $returnData[$value['no']] = $value;
        }
        return ResultWrapper::success($returnData);
    }

    /**
     * 增加详情es数据
     * @param $data
     * @param $params
     * @param $ids
     * @return ResultWrapper
     */
//    public function addEsData($data, $params, $ids)
//    {
//        foreach ($data as $key => $value) {
//            $value['inStatus'] = StatusCode::$delete;
//            $modelResult = self::updateEsData($value, $params, $ids[$key]);
//            if (!$modelResult->isSuccess()) {
//                return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
//            }
//        }
//        return ResultWrapper::success(true);
//    }

    /**
     * 添加详情es
     * @param $data
     * @param $params
     * @param $id
     * @return ResultWrapper
     */
//    public function updateEsData($data, $params, $id)
//    {
//        $addEsData = [
//            'id'           => $id,
//            'enterpriseId' => $this->onlineEnterpriseId,
//            'no'           => isset($params['no']) ? $params['no'] : false,
//            'supplierId'   => isset($params['supplierId']) ? $params['supplierId'] : false,
//            'supplierName' => isset($params['supplierName']) ? $params['supplierName'] : false,
//            'buyerId'      => isset($params['buyerId']) ? $params['buyerId'] : false,
//            'buyerName'    => isset($params['buyerName']) ? $params['buyerName'] : false,
//            'remark'       => isset($params['remark']) ? $params['remark'] : false,
//            'operatorId'   => isset($params['operatorId']) ? $params['operatorId'] : false,
//            'operatorName' => isset($params['operatorName']) ? $params['operatorName'] : false,
//            'returnStatus' => isset($params['returnStatus']) ? $params['returnStatus'] : false,
//            'inStatus'     => isset($params['inStatus']) ? $params['inStatus'] : false,
//            'auditId'      => isset($params['auditId']) ? $params['auditId'] : false,
//            'auditName'    => isset($params['auditName']) ? $params['auditName'] : false,
//            'auditStatus'  => isset($params['auditStatus']) ? $params['auditStatus'] : false,
//            'auditTime'    => isset($params['auditTime']) ? $params['auditTime'] : false,
//            'deleteStatus' => isset($params['deleteStatus']) ? $params['deleteStatus'] : false,
//            'createTime'   => isset($params['createTime']) ? $params['createTime'] : false,
//            'updateTime'   => isset($params['updateTime']) ? $params['updateTime'] : false,
//
//            'basicGoodsId'        => isset($data['basicGoodsId']) ? $data['basicGoodsId'] : false,
//            'goodsName'           => isset($data['goodsName']) ? $data['goodsName'] : false,
//            'goodsCode'           => isset($data['goodsCode']) ? $data['goodsCode'] : false,
//            'skuId'               => isset($data['skuId']) ? $data['skuId'] : false,
//            'unitName'            => isset($data['unitName']) ? $data['unitName'] : false,
//            'skuName'             => isset($data['skuName']) ? $data['skuName'] : false,
//            'categoryId'          => isset($data['categoryId']) ? $data['categoryId'] : false,
//            'categoryName'        => isset($data['categoryName']) ? $data['categoryName'] : false,
//            'buyerNum'            => isset($data['buyerNum']) ? $data['buyerNum'] : false,
//            'buyerUnitPrice'      => isset($data['buyerUnitPrice']) ? $data['buyerUnitPrice'] : false,
//            'subtotalPrice'       => isset($data['subtotalPrice']) ? $data['subtotalPrice'] : false,
//            'purchaseId'          => isset($data['purchaseId']) ? $data['purchaseId'] : false,
//            'detailsReturnStatus' => isset($data['returnStatus']) ? $data['returnStatus'] : false,
//            'detailsDeleteStatus' => isset($data['deleteStatus']) ? $data['deleteStatus'] : false,
//        ];
//        foreach ($addEsData as $key => $value) {
//            if ($value === false) {
//                return ResultWrapper::fail($key . '---ES字段未设置', ErrorCode::$paramError);
//            }
//        }
//        //创建es id
//        $esId = self::esId($id);
//        $result = $this->objDPurchaseGoods->addUpSearchIndexDocument($addEsData, $esId);
//        if (isset($result['_shards']) && isset($result['_shards']['successful']) && $result['_shards']['successful'] == 1) {
//            return ResultWrapper::success(isset($result['_id']) ? $result['_id'] : false);
//        }
//        return ResultWrapper::fail($result['error']['reason'], ErrorCode::$paramError);
//    }

    /**
     * 拼接详情es id
     * @param $id
     * @return string
     */
//    public function esId($id)
//    {
//        return 'EnterpriseId_' . $this->onlineEnterpriseId . '_PurchaseDetailsId_' . $id;
//    }

    /**
     * Doc: (des="")
     * User: XMing
     * Date: 2020/12/23
     * Time: 10:29 上午
     * @param array $arr
     * @return string
     */
    public static function formatSpecGroup($arr): string
    {
        $str = '';
        if (empty($arr) || !is_array($arr)) {
            return $str;
        }
        foreach ($arr as $item) {
            if (!empty($str)) {
                $str .= '_';
            }
            $str .= $item['specValueName'];
        }
        return $str;
    }

    /**
     * Doc: (des="获取商品的最近采购成本价格")
     * User: XMing
     * Date: 2021/3/11
     * Time: 10:28 上午
     * @param int $materielId
     * @param int $date
     * @return ResultWrapper
     */
    public function getCostPriceSheetByMaterielId(int $materielId,int $date): ResultWrapper
    {
        $sql = 'SELECT buyerUnitPrice,skuId,createTime FROM '.$this->objDPurchaseGoods->get_Table().' WHERE basicGoodsId = '.$materielId;
        $sql .= ' AND createTime <= '.$date;
        $lists = $this->objDPurchaseGoods->query($sql);
        if ($lists === false){
            Logger::logs(E_USER_ERROR,'sql error',__CLASS__,__LINE__,$this->objDPurchaseGoods->error());
            return ResultWrapper::fail($this->objDPurchaseGoods->error(),ErrorCode::$dberror);
        }
        if (empty($lists)){
            return ResultWrapper::success([]);
        }
        $arrayList = [];
        foreach ($lists as $item){
            $arrayList[$item['skuId']][] = [
                'costPrice' => floatval($item['buyerUnitPrice']),
                'createTime' => $item['createTime']
            ];
        }
        return ResultWrapper::success($arrayList);
    }

    /**
     * 采购再次入库
     * @param int $orderId
     * @return ResultWrapper
     */
    public function reStockIn($purchaseId)
    {
        // 获取采购单数据
        $purchaseData = $this->objDPurchase->get($purchaseId);
        if ($purchaseData === false){
            return ResultWrapper::fail($this->objDPurchase->error(),ErrorCode::$dberror);
        }
        if (empty($purchaseData)){
            return ResultWrapper::fail('采购订单数据为空',ErrorCode::$paramError);
        }
        if ($purchaseData['inStatus'] == StatusCode::$standard){
            return ResultWrapper::fail('采购订单已经入库，请不要重复入库',ErrorCode::$paramError);
        }

        // 查询采购订单是否还有未审核的入库单,必须先处理完，再生成新的入库单
        $objMInventoryIn = new MInventoryIn($this->onlineEnterpriseId, $this->onlineUserId);
        $condition = [
            'originId' => $purchaseId,
            'deleteStatus' => StatusCode::$standard,
            'auditStatus'  => StatusCode::$auditStatus['auditing'],
        ];
        $result = $objMInventoryIn->getInventoryInData($condition);
        if (!$result->isSuccess()) {
            return ResultWrapper::fail($result->getData(), ErrorCode::$dberror);
        }
        $inventoryInData = $result->getData();
        if( !empty($inventoryInData) ){
            return ResultWrapper::fail('当前采购订单还有未审核的入库单,单号:'.StatusCode::$noPrefix[3].'-'.$inventoryInData[0]['no'].'，请先处理完成', ErrorCode::$notAllowAccess);
        }

        // 查询采购订单商品数据
        $purchaseGoodsData = $this->objDPurchaseGoods->select(['purchaseId' => $purchaseId,'deleteStatus' => StatusCode::$standard]);
        if ($purchaseGoodsData === false){
            return ResultWrapper::fail($this->objDPurchaseGoods->error(),ErrorCode::$dberror);
        }
        if (empty($purchaseGoodsData)){
            return ResultWrapper::fail('采购订单商品为空',ErrorCode::$paramError);
        }

        // 组装采购入库单数据
        $purchaseInData = [
            'sourceId'       => $purchaseData['id'],
            'sourceNo'       => $purchaseData['no'],
            'originNo'       => $purchaseData['no'],
            'originId'       => $purchaseData['id'],
            'shopId'         => $purchaseData['shopId'],
            'shopName'       => getArrayItem($purchaseData, 'shopName'),
            'amount'         => $purchaseData['purchaseAmount'],
            'operatorId'     => $purchaseData['operatorId'],//操作人id
            'operatorName'   => $purchaseData['operatorName'],//操作人信息
            'warehouseId'    => $purchaseData['warehouseId'],//仓库id
            'warehouseName'  => $purchaseData['warehouseName'],//仓库名称
            'source'         => StatusCode::$orderType['purchaseOrder'],
            'type'           => StatusCode::$orderType['purchaseIn'],
            'remark'         => $purchaseData['remark'],
            'merchantId'     => $purchaseData['merchantId'],//商户id
            'orderGoodsData' => []
        ];
        $purchaseInData['materielNum'] = 0;

        $amount = 0;
        foreach ($purchaseGoodsData as $key => $value) {
            if ($value['inOfNum'] > 0 ){
                $amount += bcmul($value['inOfNum'],$value['buyerUnitPrice'],2);
                $purchaseInData['materielNum']++;
                $purchaseInData['orderGoodsData'][] = [
                    'materielId'   => $value['basicGoodsId'],
                    'materielName' => $value['goodsName'],
                    'materielCode' => $value['goodsCode'],
                    'skuId'        => $value['skuId'],
                    'unitName'     => isset($value['unitName']) ? $value['unitName'] : '',
                    'skuName'      => isset($value['skuName']) ? $value['skuName'] : '',
                    'num'          => $value['inOfNum'],
                    'inNum'        => 0,
                    'otherNum'     => $value['otherNum'],
                    'unitPrice'    => $value['buyerUnitPrice'],
                    'totalPrice'   => bcmul($value['inOfNum'],$value['buyerUnitPrice'],2),
                ];
            }
        }
        $purchaseInData['amount'] = $amount;

        if (empty($purchaseInData['orderGoodsData'])){
            return ResultWrapper::fail('此采购订单没有需要入库的商品',ErrorCode::$paramError);
        }

        // 新增采购入库单
        $dbResult = $objMInventoryIn->addInventoryIn($purchaseInData);
        if (!$dbResult->isSuccess()) {
            return ResultWrapper::fail($dbResult->getData(), ErrorCode::$dberror);
        }
        return ResultWrapper::success($dbResult->getData());
    }


    /**
     * 采购订单直接退款
     */
    public function retMoney($purchaseId)
    {
        $purchaseData = $this->objDPurchase->get($purchaseId);
        if($purchaseData === false){
            return ResultWrapper::fail($this->objDPurchase->error(), ErrorCode::$dberror);
        }
        if(empty($purchaseData)){
            return ResultWrapper::fail('采购订单数据为空', ErrorCode::$contentNotExists);
        }

        $purchaseGoodsData = $this->objDPurchaseGoods->select(['purchaseId' => $purchaseId,'deleteStatus' => StatusCode::$standard]);
        if ($purchaseGoodsData === false){
            return ResultWrapper::fail($this->objDPurchaseGoods->error(),ErrorCode::$dberror);
        }
        if (empty($purchaseGoodsData)){
            return ResultWrapper::fail('采购订单商品为空',ErrorCode::$paramError);
        }

        /*
        $refundMoney = 0;
        foreach ($purchaseGoodsData as $key => $value) {
            if ($value['inOfNum'] > 0 ){
                $refundMoney += bcmul($value['inOfNum'],$value['buyerUnitPrice'],2);
            }
        }

        // 生成财务退款单
        $financeRefundData = [
            'originId'    => getArrayItem($purchaseData,'id',''),
            'originNo'    => getArrayItem($purchaseData,'no',''),
            'sourceNo'    => getArrayItem($purchaseData,'no',''),
            'refundTime'  => time(),
            'createTime'  => time(),
            'unitId'      => getArrayItem($purchaseData,'supplierId',0),
            'unitName'      => getArrayItem($purchaseData,'supplierName',0),
            'currentAccountName' => getArrayItem($purchaseData,'supplierName',''),
            'financeType' => '采购退款',
            'financeTypeId' => 1,
            'payType'       =>'',
            'shopId'      => getArrayItem($purchaseData,'warehouseId',0),
            'shopName'    => getArrayItem($purchaseData,'warehouseName',0),
            'money'       => $refundMoney,
            'operatorId'  => $this->onlineUserId,
            'type'        => StatusCode::$delete,
            'auditStatus' => StatusCode::$auditStatus['auditing'],
        ];

        // 根据订单支付方式规划退款账户
        /*$objMAccount = new MAccount($this->enterpriseId,$this->userCenterId);
        $payType = explode(',', $order['payType']);

        // 包含余额组合支付方式统一返回余额，其他原路返回
        if( in_array(StatusCode::$payType['balance'],$payType) ){
            $financeAccountData = $objMAccount->getDefaultAccount(StatusCode::$payType['balance']);
        }else{
            $financeAccountData = $objMAccount->getDefaultAccount($payType);
        }
        if(!$financeAccountData->isSuccess()){
            $this->objDInventoryOut->rollBack();
            return ResultWrapper::fail($financeAccountData->getData(), $financeAccountData->getErrorCode());
        }
        $financeAccountData = $financeAccountData->getData();

        $financeRefundData['accountList'] = [
            [
                'accountId'     => $financeAccountData['id'],
                'accountNumber' => $financeAccountData['accountNumber'],
                'accountName'   => $financeAccountData['name'],
                'money'         => $InventoryOutData['amount'],
            ]
        ];*/

        $beginTransactionStatus = $this->objDPurchase->beginTransaction();

        // 修改采购单退款标识字段
        $result = $this->objDPurchase->update(['havaRefund'=>StatusCode::$standard,'inStatus'=>StatusCode::$standard,'updateTime'=>time()], $purchaseId);
        if($result === false){
            $this->objDPurchase->rollBack();
            return ResultWrapper::fail($this->objDPurchase->error(), ErrorCode::$dberror);
        }

        // 添加退款单
        /*$financeRefundData['accountList'] = [];
        $objMRefund = new MRefund($this->onlineEnterpriseId,$this->onlineUserId);
        $result = $objMRefund->addRefund($financeRefundData);
        if(!$result->isSuccess()){
            $this->objDPurchase->rollBack();
            return ResultWrapper::fail($result->getData(),$result->getErrorCode());
        }*/

        if($beginTransactionStatus){
            $this->objDPurchase->commit();
        }

        return ResultWrapper::success($result);
    }
    
    /**
     * 采购总汇表导出方法
     * @param $result
     */
    public function exportPurchaseByFields($result)
    {
       
        //导出到本地
        header("Content-type:application/vnd.ms-excel");
        header("Content-Disposition:filename=采购总汇表.csv");
        header('Cache-Control: max-age=0');
        
        $fp = fopen('php://output', 'a');
        
        $head = ['商品类别', '仓库','商品', '商品编码', '规格','数量', '其他单位', '入库状态', '成本', '总成本'];       //定义标题
        
        foreach ($head as $i => $v) {
            $head[$i] = mb_convert_encoding($v, 'GBK', 'utf-8');     //将中文标题转换编码，否则乱码
        }
        
        fputcsv($fp, $head);
        
        $limit = 10000;
        $num = 0;//计数器
        foreach ($result as $value) {//循环数据
            $num++;
            if ($num == $limit) {
                ob_flush();//释放内存
                flush();
            }
            $rows['categoryName'] = isset($value['categoryName']) ? $value['categoryName'] : null;//商品类别
            $rows['warehouseName'] = isset($value['warehouseName']) ? $value['warehouseName'] : null;//仓库
            $rows['materielName'] = isset($value['materielName']) ? $value['materielName'] : null;//商品
            $rows['materielCode'] = isset($value['materielCode']) ? $value['materielCode'] : null;//商品编码
            $rows['unitName'] = isset($value['unitName']) ? $value['unitName'] : null;//规格
            $rows['total'] = isset($value['total']) ? $value['total'] : null;//数量
            $rows['otherNum'] = isset($value['otherNum']) ? $value['otherNum'] : null;//其他单位
            $rows['inStatus'] = isset($v['inStatus']) ? $v['inStatus'] == StatusCode::$standard ? '已入库' : '未入库' : null;//入库状态
            $rows['costPrice'] = isset($value['costPrice']) ? $value['costPrice'] : null;//成本
            $rows['allNum'] = isset($value['allNum']) ? $value['allNum'] : null;//总成本
            
            foreach ($rows as $kk => $vv) {
                $rs[$kk] = mb_convert_encoding($vv, 'GBK', 'utf-8');  //转译编码
            }
            fputcsv($fp, $rs);
            $rows = [];
        }
    }


    /**
     * 智能采购列表
     */
    public function getAllOrderPurchase($selectParams)
    {
        $stockDbName = Factory::config()->get('db.stock.dbname');
        $objDOrder = new DOrder();
        $objDOrderGoods = new DOrderGoods();
        $objDInventoryWarehouse = new DInventoryWarehouse();
        $objDInventoryWarehouse->setTable('qianniao_inventory_warehouse_'.$this->onlineEnterpriseId);

        $orderTableName = $objDOrder->getTableName('qianniao_order_' . $this->onlineEnterpriseId, $this->onlineUserId, $this->cutTable);
        $objDOrder->setTable($orderTableName);

        $orderGoodsTableName = $objDOrderGoods->getTableName('qianniao_order_goods_' . $this->onlineEnterpriseId, $this->onlineUserId, $this->cutTable);
        $objDOrderGoods->setTable($orderGoodsTableName);

        $returnData = [
            'data'  => [],
            'total' => 0,
        ];

        $limit = $selectParams['limit'];
        unset($selectParams['limit']);
        $offset = $selectParams['offset'];
        unset($selectParams['offset']);

        $whereSql = '';
        if (isset($selectParams['no']) && !empty($selectParams['no'])) {
            $where = empty($whereSql) ? ' WHERE ' : ' AND ';
            $whereSql .= $where . ' o.no like "%' . $selectParams['no'] .'%"';
        }
        if (isset($selectParams['customerName']) && !empty($selectParams['customerName'])) {
            $where = empty($whereSql) ? ' WHERE ' : ' AND ';
            $whereSql .= $where . ' o.customerName like "%' . $selectParams['customerName'] .'%"';
        }
        if (isset($selectParams['payStatus']) && !empty($selectParams['payStatus'])) {
            $where = empty($whereSql) ? ' WHERE ' : ' AND ';
            $whereSql .= $where . ' o.payStatus = ' . $selectParams['payStatus'];
        }
        if (isset($selectParams['orderStatus']) && !empty($selectParams['orderStatus'])) {
            $where = empty($whereSql) ? ' WHERE ' : ' AND ';
            $whereSql .= $where . ' o.orderStatus = ' . $selectParams['orderStatus'];
        }
        if (isset($selectParams['auditStatus']) && !empty($selectParams['auditStatus'])) {
            $where = empty($whereSql) ? ' WHERE ' : ' AND ';
            $whereSql .= $where . ' o.auditStatus = ' . $selectParams['auditStatus'];
        }
        if ( (isset($selectParams['start']) && !empty($selectParams['start']))&&(isset($selectParams['end']) && !empty($selectParams['end'])) ) {
            $where = empty($whereSql) ? ' WHERE ' : '  AND ';
            $whereSql .= $where . ' o.createTime BETWEEN ' . $selectParams['start'] . ' AND '. $selectParams['end'];
        }
        $where = empty($whereSql) ? ' WHERE ' : ' AND ';
        $whereSql .= $where . 'g.deleteStatus = ' . StatusCode::$standard;
        $sql = 'SELECT g.*,o.*,sum(g.buyNum) as goodsBuyNum,sum(g.otherNum) as goodsOtherNum, w.inventoryNum as inventoryNum,w.otherNum as warehouseOtherNum FROM ' . $objDOrderGoods->get_Table() .' as g left join '. $objDOrder->get_Table() .' as o on o.id=g.orderId left join `'.$stockDbName.'`.'. $objDInventoryWarehouse->get_Table() .' as w on g.skuId=w.skuId '.$whereSql . ' group by g.skuId ORDER BY o.createTime DESC LIMIT ' . $offset . ' , ' . $limit;
        $dbResult = $objDOrder->query($sql);

        if ($dbResult === false) {
            return ResultWrapper::fail($objDOrder->error(), ErrorCode::$dberror);
        }
        if(empty($dbResult)){
            return ResultWrapper::success($returnData);
        }

        //格式化数据
        foreach ($dbResult as $key => $value){
            if(empty($value['inventoryNum'])){
                $dbResult[$key]['inventoryNum'] = 0;
            }
            if(empty($value['warehouseOtherNum'])){
                $dbResult[$key]['warehouseOtherNum'] = 0;
            }
        }

        $return = [
            'data'  => $dbResult,
            'total' => count($dbResult),
        ];
        return ResultWrapper::success($return);
    }


}