<?php
/**
 * Created by PhpStorm.
 * User: kang
 * Date: 2021/6/9
 * Time: 17:31
 */

namespace JinDouYun\Model\Stock;

use JinDouYun\Dao\Stock\DReservoirArea;
use Mall\Framework\Core\ErrorCode;
use Mall\Framework\Core\StatusCode;
use Mall\Framework\Core\ResultWrapper;

use JinDouYun\Dao\Stock\DStorageLocation;

use JinDouYun\Model\MBaseModel;

class MStorageLocation extends MBaseModel
{
    
    private $objDStorageLocation;
    private $userCenterId;
    private $enterpriseId;
    
    public function __construct($enterpriseId, $userCenterId = false)
    {
        $this->enterpriseId = $enterpriseId;
        $this->userCenterId = $userCenterId;
        $this->objDStorageLocation = new DStorageLocation('stock');
    }
    
    /**
     * 仓库库位添加
     * @param $params
     * @return ResultWrapper
     * @throws Exception
     */
    public function addStorageLocation($params)
    {
        $params['createTime'] = time();
        $dbResult = $this->objDStorageLocation->insert($params);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDStorageLocation->error(), ErrorCode::$dberror);
        }
        return ResultWrapper::success($dbResult);
    }
    
    /**
     * 仓库库位修改
     * @param $update
     * @param $where
     * @return ResultWrapper
     */
    public function updateStorageLocation($update, $where)
    {
        $update['updateTime'] = time();
        $dbResult = $this->objDStorageLocation->update($update,$where);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDStorageLocation->error(), ErrorCode::$dberror);
        }
        return ResultWrapper::success($dbResult);
    }
    
    /**
     * 仓库库位列表
     * @param $selectParams
     * @return ResultWrapper
     */
    public function getAllStorageLocation($selectParams)
    {
        $limit = $selectParams['limit'];
        unset($selectParams['limit']);
        $offset = $selectParams['offset'];
        unset($selectParams['offset']);
        $where  ='';
        $where .=' where l.deleteStatus ='.StatusCode::$standard . ' and l.enterpriseId = '. $this->enterpriseId;
        if(!empty($selectParams['areaId'])){
            $where .=' and l.areaId ='.$selectParams['areaId'];
        }
        if(!empty($selectParams['enableStatus'])){
            $where .=' and l.enableStatus ='.$selectParams['enableStatus'];
        }
        if(!empty($selectParams['warehouseId'])){
            $where .=' and a.warehouseId ='.$selectParams['warehouseId'];
        }
        $sql = 'SELECT l.*,a.warehouseId,a.code as areaCode FROM qianniao_storage_Location as l  LEFT JOIN   qianniao_reservoir_area as a on a.id = l.areaId'.$where.' order by l.createTime desc limit '.$offset.','.$limit;
        $dbResult = $this->objDStorageLocation->query($sql);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDStorageLocation->error(), ErrorCode::$dberror);
        }
        $sql = 'SELECT count(*) as total ,a.warehouseId,a.code as areaCode FROM qianniao_storage_Location as l  LEFT JOIN   qianniao_reservoir_area as a on a.id = l.areaId'.$where;
        $count = $this->objDStorageLocation->query($sql);
        if ($count === false) {
            return ResultWrapper::fail($this->objDStorageLocation->error(), ErrorCode::$dberror);
        }
        $total = 0;
        foreach ($count as $key => $value){
          $total  = $count[$key]['total'];
        }
        $data = self::format($dbResult);
        if(!$data->isSuccess()){
            return ResultWrapper::fail($this->objDStorageLocation->error(), ErrorCode::$dberror);
        }
        $data = $data->getData();
        $return = [
            'data' => $data,
            'total' => $total ? $total : 0,
        ];
        return ResultWrapper::success($return);
    }
    
    /**
     * 仓库库位列表(不分页)
     * @param $selectParams
     * @return ResultWrapper
     */
    public function getListStorageLocation($selectParams)
    {
        $selectParams['deleteStatus'] = StatusCode::$standard;
        $dbResult = $this->objDStorageLocation->select($selectParams, '*', 'createTime desc');
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDStorageLocation->error(), ErrorCode::$dberror);
        }
        foreach($dbResult as &$value){
            $value['reservoirName'] = $value['name'].'('.$value['code'].')';
        }
        unset($value);
        return ResultWrapper::success($dbResult);
    }
    
    /**
     * 仓库库位详情
     * @param $where
     * @return ResultWrapper
     */
    public function getStorageLocationInfo($where)
    {
        $dbResult = $this->objDStorageLocation->get($where);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDStorageLocation->error(), ErrorCode::$dberror);
        }
        $data = self::format([$dbResult]);
        if(!$data->isSuccess()){
            return ResultWrapper::fail($this->objDStorageLocation->error(), ErrorCode::$dberror);
        }
       $data = $data->getData();
        return ResultWrapper::success(array_pop($data));
    }
    
    /**
     * 格式化
     * @return array
     */
    public function format($data)
    {
        // 根据库区id格式化库区名称
        $areaIdBindName = [];
        $areaIds = [];
        foreach ($data as $k => $v){
            if(!empty($v['areaId'])){
                $areaIds[] = $v['areaId'];
            }
        }
        if(!empty($areaIds)){
            $objDReservoirArea = new DReservoirArea();
            $areaData = $objDReservoirArea->select($areaIds, 'id,name');
            if($areaData === false){
                return ResultWrapper::fail($objDReservoirArea->error(), ErrorCode::$dberror);
            }
            if(!empty($areaData)){
                foreach ($areaData as $k => $v){
                    $areaIdBindName[$v['id']] = $v['name'];
                }
            }
            // 循环主数据，进行对应的字段映射操作
            foreach ($data as $key => $value){
                $data[$key]['areaName'] = isset($areaIdBindName[$value['areaId']]) ? $areaIdBindName[$value['areaId']] :'';
            }
        }
        return  ResultWrapper::success($data);
    }
    
    
}