<?php
/**
 * 出库管理Controller
 * Created by PhpStorm.
 * User: 小威
 * Date: 2019/11/11
 * Time: 16:00
 */

namespace JinDouYun\Controller\Stock;

use Exception;
use Jindouyun\Cache\EnterpriseCache;
use Mall\Framework\Core\ErrorCode;
use Mall\Framework\Core\StatusCode;

use JinDouYun\Controller\BaseController;

use JinDouYun\Model\Stock\MInventoryOut;

class InventoryOut extends BaseController
{
    private $objMInventoryOut;

    public function __construct($isCheckAcl = true, $isMustLogin = true)
    {
        parent::__construct($isCheckAcl, $isMustLogin);
        $this->objMInventoryOut = new MInventoryOut($this->onlineEnterpriseId, $this->onlineUserId);
    }

    /**
     * 出库审核
     * @throws Exception
     */
    public function updateInventoryOutStatus()
    {
        $paramsData = $this->request->getRawJson();
        if (empty($paramsData)) {
            $this->sendOutput('参数为空', ErrorCode::$paramError);
        }
        $params = [
            'id'        => isset($paramsData['id']) ? $paramsData['id'] : '',//出库id
            'auditId'   => $this->onlineUserId,//操作人id
            'auditName' => isset($paramsData['auditName']) ? $paramsData['auditName'] : '',//操作人姓名
            'outWarehouseData' => isset($paramsData['outWarehouseData']) ? $paramsData['outWarehouseData'] : [],
        ];
        foreach ($params as $key => $value) {
            if (empty($value) && $value !== 0) {
                $this->sendOutput($key . '参数错误', ErrorCode::$paramError);
            }
        }

        $objEnterpriseCache = new EnterpriseCache();
        $enterSettingData = $objEnterpriseCache->getEnterpriseSetting($this->onlineEnterpriseId);
        // 判断负库存是否允许出库
//        foreach ($params['outWarehouseData'] as $k => $v){
//            foreach ($v['details'] as $k1 => $v1){
//                if( $enterSettingData['distributionExamine'] == StatusCode::$delete && $v1['isDistribution'] == StatusCode::$standard && $v1['warehouseInventoryNum'] < $v1['num'] ){ //不开启，不允许负库存出库
//                    $this->sendOutput($v1['materielName'] . '库存不足，不允许出库', ErrorCode::$notAllowAccess);
//                }
//            }
//        }

        $params['logisticsData'] = isset($paramsData['logisticsData']) ? $paramsData['logisticsData'] : null;
        $params['deliveryNo'] = isset($paramsData['deliveryNo']) ? $paramsData['deliveryNo'] : '';
        $params['expressName'] = isset($paramsData['expressName']) ? $paramsData['expressName'] : '';
        $params['expressId'] = isset($paramsData['expressId']) ? $paramsData['expressId'] : 0;
        $params['UnassignedSkuData'] = isset($paramsData['UnassignedSkuData']) ? $paramsData['UnassignedSkuData'] : [];
        $params['autoAudit'] = StatusCode::$delete;
        $result = $this->objMInventoryOut->updateInventoryOutStatus($params);
        if ($result->isSuccess()) {
            parent::sendOutput($result->getData());
        }
        parent::sendOutput($result->getData(), $result->getErrorCode());
    }

    /**
     * 出库单分配仓库
     */
    public function saveOutInventory()
    {
        $id = $this->request->param('request_id');
        if (empty($id)) {
            $this->sendOutput('id参数为空', ErrorCode::$paramError);
        }
        $params = $this->request->getRawJson();
        if (empty($params)) {
            $this->sendOutput('参数为空', ErrorCode::$paramError);
        }
        $data = [
            'outWarehouseData' => isset($params['outWarehouseData']) ? $params['outWarehouseData'] : [],
            'UnassignedSkuData' => isset($params['UnassignedSkuData']) ? $params['UnassignedSkuData'] : [],
        ];
        $result = $this->objMInventoryOut->saveOutInventory($data, ['id' => $id]);
        if (!$result->isSuccess()) {
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }
        parent::sendOutput($result->getData());
    }

    /**
     * 出库列表
     */
    public function getAllInventoryOut()
    {
        $params = $this->request->getRawJson();

        $pageParams = pageToOffset($params['page'] ?: 1, $params['pageSize'] ?: 10);
        $selectParams['limit'] = $pageParams['limit'];
        $selectParams['offset'] = $pageParams['offset'];

        (isset($params['auditStatus']) && !empty($params['auditStatus'])) && $selectParams['auditStatus'] = $params['auditStatus'];
        if(isset($params['type']) && !empty($params['type'])){
            $selectParams['type'] = $params['type'];
        }
        if(isset($params['start']) && !empty($params['start']) && isset($params['end']) && !empty($params['end'])){
            $selectParams['createTime'] = ['start' => $params['start'], 'end' => $params['end']];
        }

        if(isset($params['search']) && !empty($params['search'])){
            $selectParams['search']['no'] = $params['search'];
            $selectParams['search']['auditName'] = $params['search'];
        }

        if(!empty($this->shopId)){
            $selectParams['shopId'] = $this->shopId;
        }else{
            if(isset($params['shopId']) && !empty($params['shopId'])){
                $selectParams['shopId'] = $params['shopId'];
            }
        }
        $export = isset($params['export']) ? $params['export'] : 0;
        $result = $this->objMInventoryOut->getAllInventoryOut($selectParams,$export);
        if ($result->isSuccess()) {
            $returnData = $result->getData();
            $pageData = [
                'pageIndex' => $params['page'],
                'pageSize'  => $params['pageSize'],
                'pageTotal' => $returnData['total'],
            ];
            parent::sendOutput($returnData['data'], 0, $pageData);
        }
        parent::sendOutput($result->getData(), ErrorCode::$dberror);
    }

    /**
     * 出库列表搜索
     */
    public function searchAllInventoryOut()
    {
        $params = $this->request->getRawJson();
        if (empty($params)) {
            $this->sendOutput('参数为空', ErrorCode::$paramError);
        }

        $selectParams = [
            'warehouseId' => isset($params['warehouseId']) ? $params['warehouseId'] : '',
            'type'        => isset($params['type']) ? $params['type'] : '',
            'auditStatus' => isset($params['auditStatus']) ? $params['auditStatus'] : '',
            'start'       => isset($params['start']) ? $params['start'] : '',
            'end'         => isset($params['end']) ? $params['end'] : '',
            'search'      => isset($params['search']) ? $params['search'] : '',
        ];
        $pageParams = pageToOffset($params['page'] ?: 1, $params['pageSize'] ?: 10);
        $selectParams['limit'] = $pageParams['limit'];
        $selectParams['offset'] = $pageParams['offset'];

        $selectParams['shopId'] = $this->shopId;
        $result = $this->objMInventoryOut->searchAllInventoryOut($selectParams);
        if ($result->isSuccess()) {
            $returnData = $result->getData();
            $pageData = [
                'pageIndex' => $params['page'],
                'pageSize'  => $params['pageSize'],
                'pageTotal' => $returnData['total'],
            ];
            parent::sendOutput($returnData['data'], 0, $pageData);
        }
        parent::sendOutput($result->getData(), $result->getErrorCode());
    }

    /**
     * 出库统计
     * @throws Exception
     */
    public function statisticsAllInventoryOut()
    {
        $params = $this->request->getRawJson();
        if (empty($params)) {
            parent::sendOutput('参数为空', ErrorCode::$paramError);
        }
        $type = $params['type'];
        $modelResult = $this->objMInventoryOut->statisticsAllInventoryOut($type, $this->shopId);
        if (!$modelResult->isSuccess()) {
            parent::sendOutput($modelResult->getData(), $modelResult->getErrorCode());
        }
        parent::sendOutput($modelResult->getData());

    }

    /**
     * 出库详情
     * @throws Exception
     */
    public function getInventoryOutInfo()
    {
        $params['id'] = $this->request->param('request_id');

        $data = $this->request->getRawJson();
        $params['originId'] = isset($data['originId']) ? $data['originId'] : '';
        $params['source'] = isset($data['source']) ? $data['source'] : '';
        $where = [];
        if(isset($params['id']) && !empty($params['id'])){
            $where['id'] = $params['id'];
        }else{
            if(isset($params['originId']) && !empty($params['originId'])){
                $where['originId'] = $params['originId'];
                if(isset($params['source']) && !empty($params['source'])){
                    $where['source'] = $params['source'];
                }else{
                    $this->sendOutput('source参数为空', ErrorCode::$paramError);
                }
            }
        }
        if (empty($where)) {
            $this->sendOutput('参数为空', ErrorCode::$paramError);
        }


        $result = $this->objMInventoryOut->getInventoryOutInfo($where);
        if ($result->isSuccess()) {
            parent::sendOutput($result->getData());
        }
        parent::sendOutput($result->getData(), $result->getErrorCode());
    }

    /**
     * 出库详情
     * @throws Exception
     */
    public function getInventoryOutByOriginId()
    {
        $data = $this->request->getRawJson();
        $result = $this->objMInventoryOut->getInventoryOutByOriginId($data['originId'], StatusCode::$orderType['saleOrder']);
        if ($result->isSuccess()) {
            parent::sendOutput($result->getData());
        }
        parent::sendOutput($result->getData(), $result->getErrorCode());
    }

    /**
     * 格式化出库es
     */
    public function formatInventoryOutEsData()
    {
        $params = $this->request->getRawJson();
        if (!isset($params['key']) || md5('123456123456') != $params['key']) {
            $this->sendOutput('参数校验失败', ErrorCode::$paramError);
        }

        $result = $this->objMInventoryOut->formatInventoryOutEsData();
        if ($result->isSuccess()) {
            parent::sendOutput($result->getData(),$result->getErrorCode());
        }
        parent::sendOutput($result->getData());
    }
    
    /**
     * 设置物流信息
     */
    public function addLogistics()
    {
        $params = $this->request->getRawJson();
        if( empty($params) ){
            parent::sendOutput('请求参数错误', ErrorCode::$paramError);
        }

        $result = $this->objMInventoryOut->addLogistics($params);
        if ($result->isSuccess()) {
            parent::sendOutput($result->getData(),$result->getErrorCode());
        }
        parent::sendOutput($result->getData());
    }

    /**
     * 扫条码加载出库单商品数据
     */
    public function getDetailByGoodsCode()
    {
        $params = $this->request->getRawJson();
        if( empty($params) ){
            parent::sendOutput('参数为空', ErrorCode::$paramError);
        }

        $selectParams = [
            'id'       => getArrayItem($params, 'id'),
            'barCode'  => getArrayItem($params, 'barCode'),
        ];

        //必填项
        foreach ($selectParams as $key => $value) {
            if (empty($value) && $value !== 0) {
                $this->sendOutput($key . '参数错误', ErrorCode::$paramError);
            }
        }

        $result = $this->objMInventoryOut->getDetailByGoodsCode($selectParams);
        if ($result->isSuccess()) {
            parent::sendOutput($result->getData(),$result->getErrorCode());
        }
        parent::sendOutput($result->getData());
    }
}