<?php
/**
 * 仓库调拨管理Model
 * Created by PhpStorm.
 * User: 小威
 * Date: 2019/11/09
 * Time: 15:00
 */

namespace JinDouYun\Model\Stock;

use Dining\Dao\ShopManage\DTableAdministration;
use Exception;
use JinDouYun\Cache\Stock;
use JinDouYun\Dao\Stock\DInventoryOut;
use JinDouYun\Model\MBaseModel;
use Mall\Framework\Core\ErrorCode;
use Mall\Framework\Core\StatusCode;
use Mall\Framework\Core\ResultWrapper;

use JinDouYun\Dao\Stock\DAllocate;
use JinDouYun\Dao\Stock\DAllocateDetails;

use JinDouYun\Model\Stock\MInventory;
use JinDouYun\Model\Stock\MInventoryOut;

use JinDouYun\Cache\GoodsBasicRelevant;

class MAllocate extends MBaseModel
{
    private $objDAllocateDetails;
    private $objDAllocate;
    private $userCenterId;
    private $enterpriseId;

    public function __construct($enterpriseId, $userCenterId = false)
    {
        $this->enterpriseId = $enterpriseId;
        $this->userCenterId = $userCenterId;
        $this->objDAllocateDetails = new DAllocateDetails('stock');
        $this->objDAllocate = new DAllocate('stock');
        $this->objDAllocateDetails->setTable($this->objDAllocateDetails->get_Table() . '_' . $enterpriseId);
        $this->objDAllocate->setTable($this->objDAllocate->get_Table() . '_' . $enterpriseId);
        //$this->objDAllocateDetails->setSearchIndex('allocate_search')->setType('allocate');

    }

    /**
     * 仓库调拨记录添加
     * @param $params
     * @return ResultWrapper
     * @throws Exception
     */
    public function addAllocate($params)
    {
        $details = $params['details'];
        unset($params['details']);
        unset($params['deleteArray']);
        $this->objDAllocate->beginTransaction();
        // 生成编号
        $dbResult =  $this->objDAllocate->get('createTime >='.strtotime(date('Ymd'.'0:0:0')), 'no', 'createTime desc');
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDAllocate->error(), ErrorCode::$dberror);
        }
        if(empty($dbResult)){
            $params['no'] = createSerialNumberByDate('');
        }else{
            $params['no'] = createSerialNumberByDate($dbResult['no']);
        }
        $params['deleteStatus'] = StatusCode::$standard;
        $params['auditStatus'] = StatusCode::$auditStatus['auditing'];
        $params['auditId'] = 0;
        $params['auditName'] = '';
        $params['auditTime'] = 0;
        $params['createTime'] = time();
        $params['updateTime'] = time();
        //增加调拨记录

        $dbResult = $this->objDAllocate->insert($params);
        if ($dbResult === false) {
            $this->objDAllocate->rollBack();
            return ResultWrapper::fail($this->objDAllocate->error(), ErrorCode::$dberror);
        }
        $returnData = $dbResult;
        unset($dbResult);

        $batchParams = [];
        foreach ($details as &$value) {
            $value['linkId'] = $returnData;
            $value['linkNo'] = $params['no'];
            //查询批次
            $batchParams[] = [
                'warehouseId' => $params['warehouseId'],
                'materielId' => $value['materielId'],
                'num' => $value['num'],
                'otherNum' => $value['otherNum'],
            ];
        }
        unset($value);

        //获取批次数据
        $objMInventory = new MInventory($this->enterpriseId, $this->userCenterId);
        $modelResult = $objMInventory->getBatchByInventoryOut($batchParams, true);
        if (!$modelResult->isSuccess()) {
            $this->objDAllocate->rollBack();
            return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
        }
        $batchData = $modelResult->getData();
        unset($modelResult);
        foreach ($details as &$value) {
            $value['createTime'] = time();
            $value['updateTime'] = time();
            $mdKey = md5($params['warehouseId'] . $value['materielId']);
            $value['batch'] = json_encode($batchData[$mdKey]);
        }
        unset($value);
        $dbResult = $this->objDAllocateDetails->insert($details, true);
        if ($dbResult === false) {
            $this->objDAllocate->rollBack();
            return ResultWrapper::fail($this->objDAllocateDetails->error(), ErrorCode::$dberror);
        }
        $detailsId = $dbResult;
        unset($dbResult);

        //增加es搜索
        /*foreach ($details as $key => $value) {
            $modelResult = self::updateEsData($value, $params, $detailsId[$key], true);
            if (!$modelResult->isSuccess()) {
                $this->objDAllocate->rollBack();
                return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
            }
        }*/

        $this->objDAllocate->commit();
        return ResultWrapper::success($returnData);
    }

    /**
     * 仓库调拨记录删除
     * @param $where
     * @return ResultWrapper
     */
    public function deleteAllocate($where)
    {
        $params = [
            'deleteStatus' => StatusCode::$delete,
            'updateTime' => time(),
        ];
        $dbResult = $this->objDAllocate->update($params, $where);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDAllocate->error(), ErrorCode::$dberror);
        }
        $returnData = $dbResult;
        unset($dbResult);
        $dbResult = $this->objDAllocateDetails->select(['linkId' => $where['id']], 'id');
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDAllocate->error(), ErrorCode::$dberror);
        }
        $detailsIds = $dbResult;
        unset($dbResult);
        /*foreach ($detailsIds as $value) {
            //修改es
            $esId = parent::setEsId($this->enterpriseId, 'allocateId', $value);
            $esResult = $this->objDAllocateDetails->esupdateTypeFieldVaule(['deleteStatus' => StatusCode::$delete, 'updateTime' => time()], $esId);
            if (!$esResult) {
                return ResultWrapper::fail($esResult, ErrorCode::$paramError);
            }
        }*/
        return ResultWrapper::success($returnData);
    }


    /**
     * 仓库调拨审核
     * @param $updateData
     * @return ResultWrapper
     * @throws Exception
     */
    public function auditAllocate($updateData)
    {
        $where['id'] = $updateData['id'];
        unset($updateData['id']);
        $updateData['auditStatus'] = StatusCode::$auditStatus['auditPass'];
        $updateData['auditTime'] = time();
        $beginStatus = $this->objDAllocate->beginTransaction();
        //查询调拨信息
        $dbResult = $this->objDAllocate->get($where);
        if ($dbResult === false) {
            $this->objDAllocate->rollBack();
            return ResultWrapper::fail($this->objDAllocate->error(), ErrorCode::$dberror);
        }
        if (empty($dbResult)) {
            $this->objDAllocate->rollBack();
            return ResultWrapper::fail('调拨信息为空', ErrorCode::$dberror);
        }
        $AllocateData = $dbResult;
        unset($dbResult);
        if ($AllocateData['auditStatus'] == StatusCode::$auditStatus['auditPass']) {
            $this->objDAllocate->rollBack();
            return ResultWrapper::fail('该单据已审核', ErrorCode::$paramError);
        }

        // 查询调拨单详情数据
        $condition = [
            'linkId' => $where['id'],
            'deleteStatus' => StatusCode::$standard
        ];
        $dbResult = $this->objDAllocateDetails->select($condition);
        if ($dbResult === false) {
            $this->objDAllocate->rollBack();
            return ResultWrapper::fail($this->objDAllocateDetails->error(), ErrorCode::$dberror);
        }
        $AllocateData['details'] = $dbResult;
        unset($dbResult);



        $AllocateData = array_merge($AllocateData, $updateData);

        // 组装调拨出库单数据
        $outInventoryData = [
            'originId' => $AllocateData['id'],
            'originNo' => $AllocateData['no'],
            'sourceId' => $AllocateData['id'],
            'sourceNo' => $AllocateData['no'],
            'materielNum' => 0,
            'operatorId' => $this->userCenterId,
            'operatorName' => $updateData['auditName'],
            'remark' => $AllocateData['remark'],
            'source' => StatusCode::$orderType['allocate'],
            'type' => StatusCode::$orderType['allocateOut'],
        ];
        $outInventoryData['amount'] = 0;
        $outInventoryData['orderGoodsData'] = [];
        foreach ($AllocateData['details'] as $value) {
            $outInventoryData['materielNum']++;
            $outInventoryData['amount'] = bcadd($outInventoryData['amount'], bcmul($value['costUnitPrice'], $value['num']));
            $details = [
                'materielId' => $value['materielId'],
                'materielName' => $value['materielName'],
                'materielCode' => $value['materielCode'],
                'outWarehouse' => json_encode([['warehouseId' => $AllocateData['warehouseId'],'num' => $value['num']]]),
                'skuId' => $value['skuId'],
                'unitName' => isset($value['unitName']) ? $value['unitName'] : '',
                'skuName' => isset($value['skuName']) ? $value['skuName'] : '',
                'num' => 0,
                'outNum' => $value['num'],
                'otherNum' => $value['otherNum'],
                'total' => $value['num'],
                'unitPrice' => $value['costUnitPrice'],
                'totalPrice' => bcmul($value['costUnitPrice'], $value['num']),
                'isEq' => isset($value['isEq']) ? $value['isEq'] : 4
            ];
            $outInventoryData['orderGoodsData'][] = $details;

            //修改es
            /*$esId = parent::setEsId($this->enterpriseId, 'allocateId', $value['id']);
            $esResult = $this->objDAllocateDetails->esupdateTypeFieldVaule($updateData, $esId);
            if (!$esResult) {
                $this->objDAllocate->rollBack();
                return ResultWrapper::fail($esResult, ErrorCode::$paramError);
            }*/
        }

        // 新增调拨出库单
        $objMInventoryOut = new MInventoryOut($this->enterpriseId, $this->userCenterId);
        $modelResult = $objMInventoryOut->addInventoryOut($outInventoryData);
        if (!$modelResult->isSuccess()) {
            $this->objDAllocate->rollBack();
            return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
        }

        //更改审核状态
        $dbResult = $this->objDAllocate->update($updateData, $where);
        if ($dbResult === false) {
            $this->objDAllocate->rollBack();
            return ResultWrapper::fail($this->objDAllocate->error(), ErrorCode::$dberror);
        }
        $returnData = $dbResult;
        unset($dbResult);

        $beginStatus && $this->objDAllocate->commit();
        return ResultWrapper::success($returnData);
    }

    /**
     * 仓库调配记录修改
     * @param $updateData
     * @return ResultWrapper
     */
    public function updateAllocate($updateData)
    {
        $where['id'] = $updateData['id'];
        unset($updateData['id']);
        $details = $updateData['details'];
        unset($updateData['details']);
        $deleteArray = $updateData['deleteArray'];
        unset($updateData['deleteArray']);
        unset($updateData['no']);
        $this->objDAllocate->beginTransaction();
        if (isset($updateData['extend'])) unset($updateData['extend']);
        //查询要修改的单据
        $dbResult = $this->objDAllocate->get($where);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDAllocate->error(), ErrorCode::$paramError);
        }
        $allocateData = $dbResult;
        unset($dbResult);

        $dbResult = $this->objDAllocate->update($updateData, $where);
        if ($dbResult === false) {
            $this->objDAllocate->rollBack();
            return ResultWrapper::fail($this->objDAllocate->error(), ErrorCode::$dberror);
        }
        $returnData = $dbResult;
        unset($dbResult);
        $addDetailsData = [];
        foreach ($details as &$value) {
            $id = isset($value['id']) && !empty($value['id']) ? $value['id'] : 0;
            unset($value['id']);
            isset($value['batch']) && $value['batch'] = json_encode($value['batch']);
            if ($id) {
                //修改
                $dbResult = $this->objDAllocateDetails->update($value, ['id' => $id]);
                if ($dbResult === false) {
                    $this->objDAllocate->rollBack();
                    return ResultWrapper::fail($this->objDAllocateDetails->error(), ErrorCode::$dberror);
                }
                unset($dbResult);
                //修改es
                /*$esId = parent::setEsId($this->enterpriseId, 'allocateId', $id);
                $esResult = $this->objDAllocateDetails->esupdateTypeFieldVaule($updateData, $esId);
                if (!$esResult) {
                    $this->objDAllocate->rollBack();
                    return ResultWrapper::fail($esResult, ErrorCode::$paramError);
                }*/
            } else {
                //新增
                $addDetails = [
                    'linkId' => $where['id'],
                    'linkNo' => $updateData['no'],
                    'materielId' => $value['materielId'],
                    'materielName' => $value['materielName'],
                    'materielCode' => $value['materielCode'],
                    'skuId' => $value['skuId'],
                    'num' => $value['num'],
                    'otherNum' => $value['otherNum'],

                    'inAreaId' => isset($value['inAreaId']) ? $value['inAreaId'] : 0,
                    'inAreaName' => isset($value['inAreaName']) ? $value['inAreaName'] : '',
                    'inAreaCode' => isset($value['inAreaCode']) ? $value['inAreaCode'] : '',
                    'inStorageLocationId' => isset($value['inStorageLocationId']) ? $value['inStorageLocationId'] : 0,
                    'inStorageLocationName' => isset($value['inStorageLocationName']) ? $value['inStorageLocationName'] : '',
                    'inStorageLocationCode' => isset($value['inStorageLocationCode']) ? $value['inStorageLocationCode'] : '',
                    'outAreaId' => isset($value['outAreaId']) ? $value['outAreaId'] : 0,
                    'outAreaName' => isset($value['outAreaName']) ? $value['outAreaName'] : '',
                    'outAreaCode' => isset($value['outAreaCode']) ? $value['outAreaCode'] : '',
                    'outStorageLocationId' => isset($value['outStorageLocationId']) ? $value['outStorageLocationId'] : 0,
                    'outStorageLocationName' => isset($value['outStorageLocationName']) ? $value['outStorageLocationName'] : '',
                    'outStorageLocationCode' => isset($value['outStorageLocationCode']) ? $value['outStorageLocationCode'] : '',
                    
                    'costUnitPrice' => $value['costUnitPrice'],
                    'deleteStatus' => StatusCode::$standard,
                    'createTime' => time(),
                    'updateTime' => time(),
                    'isEq'       => $value['isEq'],
                ];
                isset($value['batch']) && $addDetails['batch'] = $value['batch'];
                $addDetailsData[] = $addDetails;
            }
        }
        //删除
        if ($deleteArray) {
            $dbResult = $this->objDAllocateDetails->update(['deleteStatus' => StatusCode::$delete, 'updateTime' => time()], ['id' => $deleteArray]);
            if ($dbResult === false) {
                $this->objDAllocate->rollBack();
                return ResultWrapper::fail($this->objDAllocateDetails->error(), ErrorCode::$dberror);
            }
            //es删除
            /*foreach ($deleteArray as $value) {
                $esResult = $this->objDAllocateDetails->esupdateTypeFieldVaule(['deleteStats' => StatusCode::$delete, 'updateTime' => time()], $value);
                if (!$esResult) {
                    return ResultWrapper::fail($esResult, ErrorCode::$paramError);
                }
            }*/
        }

        //新增
        if ($addDetailsData) {
            $dbResult = $this->objDAllocateDetails->insert($addDetailsData, true);
            if ($dbResult === false) {
                return ResultWrapper::fail($this->objDAllocateDetails->error(), ErrorCode::$dberror);
            }
            $detailsIds = $dbResult;
            unset($dbResult);
            //新增es
            /*foreach ($addDetailsData as $key => $value) {
                $modelResult = self::updateEsData($value, $allocateData, $detailsIds[$key], true);
                if (!$modelResult->isSuccess()) {
                    $this->objDAllocate->rollBack();
                    return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
                }
            }*/
        }

        $this->objDAllocate->commit();
        return ResultWrapper::success($returnData);
    }


    /**
     * 仓库调配记录列表
     * @param $selectParams
     * @param $export
     * @return ResultWrapper
     * @throws Exception
     */
    public function getAllAllocate($selectParams,$export = 0)
    {

        /*
         *             'warehouseId' => isset($params['warehouseId']) ? $params['warehouseId'] : '',
            'inWarehouseId' => isset($params['inWarehouseId']) ? $params['inWarehouseId'] : '',
            'auditStatus' => isset($params['auditStatus']) ? $params['auditStatus'] : '',
            'start' => isset($params['start']) ? $params['start'] : '',
            'end' => isset($params['end']) ? $params['end'] : '',
            'search' => isset($params['search']) ? $params['search'] : '',
         */


      
        $limit = $selectParams['limit'];
        unset($selectParams['limit']);
        $offset = $selectParams['offset'];
        unset($selectParams['offset']);
      
        $sql = "select a.*,d.materielId,d.materielCode,d.materielName,d.num,d.skuId,d.costUnitPrice,d.batch,d.skuId,d.otherNum from " . $this->objDAllocate->get_Table() . " a left join " . $this->objDAllocateDetails->get_Table() . " d on a.id = d.linkId";
        $whereSql = ' where a.deleteStatus = ' . StatusCode::$standard.' and d.deleteStatus = '.StatusCode::$standard;
        if(isset($selectParams['search']) && !empty($selectParams['search'])){
            if (strstr($selectParams['search'],StatusCode::$noPrefix['32'])){
                $selectParams['search'] = substr($selectParams['search'],strlen(StatusCode::$noPrefix['32'])+1);
            }
            $whereSql .= ' and (a.no like "%'.$selectParams['search'].'%" or d.materielName like "%'.$selectParams['search'].'%")';
        }
        if(isset($selectParams['warehouseId']) && !empty($selectParams['warehouseId'])){
            $whereSql .= ' and a.warehouseId = '.$selectParams['warehouseId'];
        }
        if(isset($selectParams['inWarehouseId']) && !empty($selectParams['inWarehouseId'])){
            $whereSql .= ' and a.inWarehouseId = '.$selectParams['inWarehouseId'];
        }
        if(isset($selectParams['start']) && isset($selectParams['end']) && !empty($selectParams['start']) && !empty($selectParams['end'])){
            $whereSql .= ' and (a.createTime between '.$selectParams['start'].' and '.$selectParams['end'].')';
        }
        if(isset($selectParams['auditStatus']) && !empty($selectParams['auditStatus'])){
            $whereSql .= ' and a.auditStatus = '.$selectParams['auditStatus'];
        }
        $orderSql = ' ORDER BY a.createTime desc';
        $limitSql = ' limit '. $offset . "," . $limit;
        if($export){
            $limitSql = '';
        }
        $dbResult = $this->objDAllocate->query($sql.$whereSql.$orderSql.$limitSql);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDAllocate->error(), ErrorCode::$dberror);
        }

        $sql = "select count(d.id) as num from " . $this->objDAllocate->get_Table() . " a left join " . $this->objDAllocateDetails->get_Table() . " d on a.id = d.linkId";
        $dbDAllocateResult = $this->objDAllocate->query($sql.$whereSql);
        if ($dbDAllocateResult === false) {
            return ResultWrapper::fail($this->objDAllocate->error(), ErrorCode::$dberror);
        }
        $DAllocate = array_shift($dbDAllocateResult);
        $total = $DAllocate['num'];
        foreach ($dbResult as &$value) {
            $value['batch'] = json_decode($value['batch'], true);
        }
        $formatData = parent::formatOrderMan($this->enterpriseId, $dbResult);
        foreach ($formatData as $key => $val){
            if( isset($val['no']) && !empty($val['no']) ){
                $formatData[$key]['no'] = StatusCode::$noPrefix['32'].'-'.$val['no'];
            }
        }
        //仓库库存导出
        if($export){
            self::exportAllocate($formatData);
            exit;
        }
        $return = [
            'data' => $formatData,
            'total' => ($total) ? intval($total) : 0,
        ];
        return ResultWrapper::success($return);
    }

    /**
     * 调拨搜索
     * @param $params
     * @return ResultWrapper
     * @throws Exception
     */
    public function searchAllocate($params)
    {
        $defaultDSL = ['from' => $params['offset'], 'size' => $params['limit'], 'sort' => ['createTime' => ['order' => 'desc']]];
        $selectParams = [];
        $selectParams[] = ['term' => ['enterpriseId' => $this->enterpriseId]];
        !empty($params['warehouseId']) && $selectParams[] = ['term' => ['warehouseId' => $params['warehouseId']]];
        !empty($params['inWarehouseId']) && $selectParams[] = ['term' => ['inWarehouseId' => $params['inWarehouseId']]];
        !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' => ['no', 'materielName'], 'query' => $params['search'], 'fuzziness' => 'AUTO']];
        $dsl = [];
        !empty($selectParams) && $dsl['query']['bool']['must'][] = $selectParams;
        $dsl = array_merge($defaultDSL, $dsl);
        $dbResult = $this->objDAllocateDetails->getSearchQueryDsl($dsl);
        if (isset($dbResult['error'])) {
            return ResultWrapper::fail($dbResult, ErrorCode::$dberror);
        }
        $returnData = parent::formatEsSelectData($dbResult, $this->enterpriseId);
        return ResultWrapper::success($returnData);
    }

    /**
     * 仓库调拨详情
     * @param $params
     * @return ResultWrapper
     * @throws Exception
     */
    public function getAllocateInfo($params)
    {
        $params['deleteStatus'] = StatusCode::$standard;
        $dbResult = $this->objDAllocate->get($params);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDAllocate->error(), ErrorCode::$dberror);
        }
        $returnData = $dbResult;
        unset($dbResult);
        $dbResult = $this->objDAllocateDetails->select(['linkId' => $params['id'], 'deleteStatus' => StatusCode::$standard]);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDAllocateDetails->error(), ErrorCode::$dberror);
        }
        $returnData['details'] = $dbResult;
        unset($dbResult);

        $skuIds = [];
        foreach ($returnData['details'] as &$value) {
            $value['batch'] = json_decode($value['batch'], true);
            $skuIds[] = $value['skuId'];
        }
        unset($value);

        $objMInventory = new MInventory($this->enterpriseId, $this->userCenterId);
        $modelResult = $objMInventory->getWarehouseInventoryData($returnData['warehouseId'], $skuIds);
        if (!$modelResult->isSuccess()) {
            return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
        }
        $inventoryData = $modelResult->getData();
        unset($modelResult);

        foreach ($returnData['details'] as &$value) {
            $value['inventoryNum'] = isset($inventoryData[$value['skuId']]) ? $inventoryData[$value['skuId']]['num'] : 0;
        }

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

    /**
     * 查询调拨单数据
     * @param $where
     * @return ResultWrapper
     */
    public function getAllocateData($where)
    {
        $where['deleteStatus'] = StatusCode::$standard;
        $dbResult = $this->objDAllocate->select($where);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDAllocate->error(), ErrorCode::$dberror);
        }
        return ResultWrapper::success($dbResult);
    }

    /**
     * 查询调拨主单据数据
     * @param $where
     * @return ResultWrapper
     */
    public function getAllocate($where)
    {
        $dbResult = $this->objDAllocate->get($where);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDAllocate->error(), ErrorCode::$dberror);
        }
        return ResultWrapper::success($dbResult);
    }

    /**
     * 添加es
     * @param $data
     * @param $params
     * @param $id
     * @param bool $type
     * @return ResultWrapper
     */
    public function updateEsData($data, $params, $id, $type = false)
    {
        $addEsData = [
            'id' => $id,
            'enterpriseId' => $this->enterpriseId,
            'no' => isset($params['no']) ? $params['no'] : false,
            'warehouseId' => isset($params['warehouseId']) ? $params['warehouseId'] : false,
            'inWarehouseId' => isset($params['inWarehouseId']) ? $params['inWarehouseId'] : false,
            'operatorId' => isset($params['operatorId']) ? $params['operatorId'] : false,
            'operatorName' => isset($params['operatorName']) ? $params['operatorName'] : false,
            'auditId' => isset($params['auditId']) ? $params['auditId'] : null,
            'auditName' => isset($params['auditName']) ? $params['auditName'] : null,
            'remark' => isset($params['remark']) ? $params['remark'] : false,
            'deleteStatus' => isset($params['deleteStatus']) ? $params['deleteStatus'] : false,
            'auditStatus' => isset($params['auditStatus']) ? $params['auditStatus'] : null,
            'auditTime' => isset($params['auditTime']) ? $params['auditTime'] : null,
            'createTime' => isset($params['createTime']) ? $params['createTime'] : false,
            'updateTime' => isset($params['updateTime']) ? $params['updateTime'] : false,
            'linkId' => isset($data['linkId']) ? $data['linkId'] : false,
            'materielId' => isset($data['materielId']) ? $data['materielId'] : false,
            'materielName' => isset($data['materielName']) ? $data['materielName'] : false,
            'materielCode' => isset($data['materielCode']) ? $data['materielCode'] : false,
            'skuId' => isset($data['skuId']) ? $data['skuId'] : false,
            'unitName' => isset($data['unitName']) ? $data['unitName'] : false,
            'skuName' => isset($data['skuName']) ? $data['skuName'] : false,
            'num' => isset($data['num']) ? $data['num'] : false,
            'batch' => isset($data['batch']) ? json_decode($data['batch'], true) : null,
            'costUnitPrice' => isset($data['costUnitPrice']) ? $data['costUnitPrice'] : false,
        ];

        foreach ($addEsData as $key => $value) {
            if ($value === false) {
                if ($type) {
                    return ResultWrapper::fail($key . '字段未设置ES', ErrorCode::$paramError);
                } else {
                    unset($addEsData[$key]);
                }
            }
        }

        //创建es id
        $esId = self::esId($id);
        $result = $this->objDAllocateDetails->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->enterpriseId . '_allocateId_' . $id;
    }
    
    /**
     * 调拨单导出方法
     * @param $result
     * @return void
     * @throws Exception
     */
    public function exportAllocate($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['no'] = isset($v['materielCode']) ? $v['materielCode'] : '';//单号
            $rows['materielCode'] = isset($v['materielCode']) ? $v['materielCode'] : '';//商品编码
            $rows['materielName'] = isset($v['materielName']) ? $v['materielName'] : '';//商品名称
            $rows['unitName'] = isset($v['unitName']) ? $v['unitName'] : '';//规格
            $rows['warehouseName'] = isset($v['warehouseName']) ? $v['warehouseName'] : '';//调出仓库
            $rows['inWarehouseName'] = isset($v['inWarehouseName']) ? $v['inWarehouseName'] : '';//调入仓库
            $rows['num'] = isset($v['num']) ? $v['num'] : '';//数量
            $rows['otherNum'] = isset($v['otherNum']) ? $v['otherNum'] : '';//其他单位
            $rows['costUnitPrice'] = isset($v['costUnitPrice']) ? $v['costUnitPrice'] : '';//单价
            $rows['costUnitTotal'] = bcmul($rows['num'],$rows['costUnitPrice'],2);//金额
            $rows['operatorName'] = isset($v['operatorName']) ? $v['operatorName'] : '';//操作人
            foreach ($rows as $kk => $vv) {
                $rs[$kk] = mb_convert_encoding($vv, 'GBK', 'utf-8');  //转译编码
            }
            fputcsv($fp, $rs);
            
            $rows = [];
        }
    }
    /**
     * 查询调拨仓库
     */
    public function getAllocateInfoByWarehouseName($params)
    {
       $originIds = [];
       foreach ($params as $k => $v){
           if(!empty($v['originId'])){
               $originIds[]= $v['originId'];
           }
       }
        $where =['id' => $originIds];
        $originIdBindWarehouseName = [];
        $originIdBindWarehouseId =[];
        $originIdBindinWarehouseId =[];
        $originIdBindinWarehouseName =[];
        if(!empty($originIds)){
            $allocateData = $this->objDAllocate->select($where,'id,warehouseId,warehouseName,inWarehouseId,inWarehouseName');
            if ($allocateData === false) {
                return ResultWrapper::fail($this->objDAllocate->error(), ErrorCode::$dberror);
            }
            if(!empty($allocateData)){
                foreach ($allocateData as $k => $v){
                    $originIdBindWarehouseId[$v['id']] = $v['warehouseId'];
                    $originIdBindWarehouseName[$v['id']] = $v['warehouseName'];
                    $originIdBindinWarehouseId[$v['id']] = $v['inWarehouseId'];
                    $originIdBindinWarehouseName[$v['id']] = $v['inWarehouseName'];
                }
            }
            // 循环主数据，进行对应的字段映射操作
            foreach ($params as $key => $value){
                $params[$key]['warehouseId'] = isset($originIdBindWarehouseId[$value['originId']]) ? $originIdBindWarehouseId[$value['originId']] :'';
                $params[$key]['warehouseName'] = isset($originIdBindWarehouseName[$value['originId']]) ? $originIdBindWarehouseName[$value['originId']] :'';
                $params[$key]['inWarehouseId'] = isset($originIdBindinWarehouseId[$value['originId']]) ? $originIdBindinWarehouseId[$value['originId']] :'';
                $params[$key]['inWarehouseName'] = isset($originIdBindinWarehouseName[$value['originId']]) ? $originIdBindinWarehouseName[$value['originId']] :'';
            }
        }
        return  ResultWrapper::success($params);
    }
    
}