<?php
/**
 * Created by PhpStorm.
 * User: Gss
 * Date: 2021/6/10 0010
 * Time: 16:52
 */

namespace JinDouYun\Model\Stock;


use JinDouYun\Dao\GoodsManage\DGoodsBasic;
use JinDouYun\Dao\GoodsManage\DSku;
use JinDouYun\Dao\Stock\DInventoryArea;
use JinDouYun\Dao\Stock\DWarehouse;
use JinDouYun\Model\GoodsManage\MSku;
use JinDouYun\Model\MBaseModel;
use Mall\Framework\Core\ErrorCode;
use Mall\Framework\Core\ResultWrapper;
use Mall\Framework\Core\StatusCode;

class MInventoryArea extends MBaseModel
{
    private $objDInventoryArea;
    private $objDSku;
    private $objDWarehouse;
    private $objDGoodsBasic;
    private $userCenterId;
    private $enterpriseId;

    public function __construct($enterpriseId, $userCenterId = false)
    {
        $this->enterpriseId = $enterpriseId;
        $this->userCenterId = $userCenterId;
        $this->objDInventoryArea = new DInventoryArea('stock');
        $this->objDInventoryArea->setTable('qianniao_inventory_area_' . $enterpriseId);
        //查询主单位
        $this->objDSku = new DSku('default');
        $this->objDSku->setTable('qianniao_sku_'.$this->enterpriseId);
        // 查询仓库表
        $this->objDWarehouse = new DWarehouse('stock');
        $this->objDWarehouse->setTable('qianniao_warehouse_'.$enterpriseId);
        // 查询商品表
        $this->objDGoodsBasic = new DGoodsBasic();
        $this->objDGoodsBasic->setTable('qianniao_goods_basic_'.$enterpriseId);
    }

    /**
     * 加减库区库位
     */
    public function updateInventoryArea($params)
    {
        if(empty($params['warehouseId'])){
            return ResultWrapper::fail('仓库数据为空',ErrorCode::$notAllowAccess);
        }
        $areaDate = [
            'warehouseId'=>         $params['warehouseId'],
            'materielId'=>          $params['materielId'],
            'merchantId'=>          getArrayItem($params, 'merchantId', 0),
            'areaId'=>              $params['areaId'],
            'areaName'=>            $params['areaName'],
            'areaCode'=>            $params['areaCode'],
            'storageLocationId'=>   $params['storageLocationId'],
            'storageLocationName'=> $params['storageLocationName'],
            'storageLocationCode'=> $params['storageLocationCode'],
            'skuId'=>               $params['skuId'],
            'unitName'=>            $params['unitName'],
            'skuName'=>             $params['skuName'],
        ];
        $type = $params['type'];
        unset($params['type']);
        $beginTransactionStatus = $this->objDInventoryArea->beginTransaction();

        $condition = [
            'warehouseId'=>$params['warehouseId'],
            'areaId'=>$params['areaId'],
            'storageLocationId'=>$params['storageLocationId'],
            'skuId'=>$params['skuId'],
            'materielId' => $params['materielId'],
            //'merchantId' =>  getArrayItem($params, 'merchantId', 0),  // 目前入库库存都和商户绑定，出库和商户无关，按照skuid出库，这个地方临时注释
        ];
        $dbResult = $this->objDInventoryArea->get($condition);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDInventoryArea->error(), ErrorCode::$dberror);
        }

        //根据type区分加减 5加，4减
        if($type == StatusCode::$standard){
            if(empty($dbResult)){ //没查到是新增
                $areaDate['num'] = $params['num'];
                $Result = $this->objDInventoryArea->insert($areaDate);
                if($Result === false){
                    return ResultWrapper::fail($this->objDInventoryArea->error(), ErrorCode::$dberror);
                }
                return ResultWrapper::success($Result);
            }else{
                $num = $dbResult['num'];
                $areaDate['num'] = bcadd($num,$params['num'],8);
            }
        }

        if($type == StatusCode::$delete){//减
            if(empty($dbResult)){
                return ResultWrapper::fail("skuId:{$condition['skuId']} 在库位{$condition['storageLocationId']}下没有库存",ErrorCode::$notAllowAccess);
            }
            $num = $dbResult['num'];
            $areaDate['num'] = bcsub($num,$params['num'],8);
        }

        $Result = $this->objDInventoryArea->update($areaDate, $condition);
        if($Result === false){
            $this->objDInventoryArea->rollBack();
            return ResultWrapper::fail($this->objDInventoryArea->error(), ErrorCode::$dberror);
        }

        if($beginTransactionStatus){
            $this->objDInventoryArea->commit();
        }
        return ResultWrapper::success($Result);
    }

    /**
     * 根据skuId获取库区数量
     */
    public function getAreaDateBySkuId($params)
    {
        $date = [];
        // 有仓库id查询所有的,没有查询单个
        if(isset($params['warehouseId']) && !empty($params['warehouseId'])){
            $skuDate = $this->objDSku->get($params['skuId']);
            if($skuDate === false){
                return ResultWrapper::fail($this->objDSku->error(), ErrorCode::$dberror);
            }
            if(empty($skuDate)){
                return ResultWrapper::fail('sku数据为空',ErrorCode::$notAllowAccess);
            }

            // 用主单位skuid去查询
            if($skuDate['isMaster'] == StatusCode::$standard){
                $conditon = [
                    'warehouseId' => $params['warehouseId'],
                    'skuId'         => $params['skuId'],
                ];
                $dbResult = $this->objDInventoryArea->select($conditon);
                if($dbResult === false){
                    return ResultWrapper::fail($this->objDInventoryArea->error(), ErrorCode::$dberror);
                }
            }else{
                $conditon = [
                    'warehouseId'   => $params['warehouseId'],
                    'materielId'    => $params['basicGoodsId'],
                ];
                $dbResult = $this->objDInventoryArea->select($conditon);
                if($dbResult === false){
                    return ResultWrapper::fail($this->objDInventoryArea->error(), ErrorCode::$dberror);
                }

                foreach ($dbResult as $key => $value){
                    $dbResult[$key]['num'] = floor(bcdiv($value['num'],$skuDate['conversion'], 8));
                }
            }
        }else{
            $dbResult = $this->objDInventoryArea->select(['skuId'=>$params['skuId']]);
            if($dbResult === false){
                return ResultWrapper::fail($this->objDInventoryArea->error(), ErrorCode::$dberror);
            }
        }

        $date = self::formatAreaDate($dbResult);
        return ResultWrapper::success(array_values($date));
    }

    public function formatAreaDate($areaDate)
    {
        $date = [];
        if(!empty($areaDate)){
            //格式化数据
            //数据归组
            foreach ($areaDate as $key => $value){
                if( !isset($date[$value['warehouseId']]) ){
                    //查询仓库名称
                    $warehouseName = $this->objDWarehouse->get_field('warehouseName',['id'=>$value['warehouseId']]);
                    if($warehouseName === false){
                        return ResultWrapper::fail($this->objDInventoryArea->error(), ErrorCode::$dberror);
                    }
                    $date[$value['warehouseId']] = [
                        'warehouseId'=>$value['warehouseId'],
                        'warehouseName'=>$warehouseName,
                    ];
                }
//                    if( !isset($date[$value['warehouseId']]['areaDate'][$value['areaId']]) ){
//                        $date[$value['warehouseId']]['areaDate'][$value['areaId']] = [
//                            'areaId'=>$value['areaId'],
//                            'areaName'=>$value['areaName'],
//                        ];
//                    }
                if(!isset($date[$value['warehouseId']]['areaDate'][$value['areaId']][$value['storageLocationId']])){
                    $goodsName = $this->objDGoodsBasic->get_field('title',['id'=>$value['materielId']]);
                    if($goodsName === false){
                        return ResultWrapper::fail($this->objDInventoryArea->error(), ErrorCode::$dberror);
                    }
                    $date[$value['warehouseId']]['areaDate'][] = [
                        'unitName'=>$value['unitName'],
                        'skuName'=>$value['skuName'],
                        'materielName'=>$goodsName,
//                        'merchantName'=>$value['merchantName'],
                        'areaId'=>$value['areaId'],
                        'areaName'=>$value['areaName'],
                        'areaCode'=>$value['areaCode'],
                        'storageLocationId'=>$value['storageLocationId'],
                        'storageLocationName'=>$value['storageLocationName'],
                        'storageLocationCode'=>$value['storageLocationCode'],
                        'num'=>$value['num'],
                    ];
                }
            }

        }
        return $date;
    }
}