<?php
/**
 * 商铺管理模块
 * Created by PhpStorm.
 * User: wxj
 * Date: 2019/10/31
 * Time: 15:02
 */
namespace JinDouYun\Controller\Stock;

use JinDouYun\Dao\Stock\DInventoryIn;
use JinDouYun\Dao\Stock\DInventoryInDetails;
use JinDouYun\Dao\Stock\DInventoryOutDetails;
use JinDouYun\Dao\Stock\DInventoryWarehouse;
use JinDouYun\Dao\Stock\DInventory;
use JinDouYun\Dao\GoodsManage\DGoodsBasic;
use JinDouYun\Dao\UserCenter\DUserCenter;
use JinDouYun\Model\Shop\MShop;
use JinDouYun\Model\Stock\MConsume;
use JinDouYun\Model\Stock\MInventory;
use Mall\Framework\Core\ErrorCode;
use Mall\Framework\Core\ResultWrapper;
use Mall\Framework\Core\StatusCode;

use JinDouYun\Dao\Stock\DInventoryOut;
use JinDouYun\Cache\ShopCache;
use JinDouYun\Controller\BaseController;
use JinDouYun\Cache\TempSaveCache;

class Consume extends BaseController
{
    private $obj;
    private $objShopCache;
    private $objTempSaveCache;
    private $objin;
    private $objshop;
    private $objinvin;

    public function __construct($isCheckAcl = true, $isMustLogin = true)
    {
        parent::__construct($isCheckAcl, $isMustLogin);
        $this->obj = new MConsume($this->onlineEnterpriseId, $this->onlineUserId);
        $this->objin =  new DInventoryWarehouse('stock');
        $this->objinv =  new DInventory('stock');
        $this->objinvin =  new DInventoryInDetails('stock');
        $this->objGoog = new DGoodsBasic('default');


        $this->objin->setTable('qianniao_inventory_warehouse_'.$this->onlineEnterpriseId);
        $this->objGoog->setTable('qianniao_goods_basic_'.$this->onlineEnterpriseId);
        $this->objinv->setTable('qianniao_inventory_'.$this->onlineEnterpriseId);
        $this->objinvin->setTable('qianniao_inventory_in_details_'.$this->onlineEnterpriseId);
        $this->user = new DUserCenter('default');
        $this->objshop = new MShop($this->onlineEnterpriseId);
    }

    /**
     * 添加和编辑商铺管理公共字段处理方法
     *
     * @return array
     */
    public function commonFieldFilter(){

        $params = $this->request->getRawJson();
        if( empty($params) ){
            $this->sendOutput('参数为空', ErrorCode::$paramError );
        }

        $shopData = [
//            'shopId' => isset($params['shopId']) ? $params['shopId'] : '',
            'id' => isset($params['id']) ? $params['id'] : '',
            'number' => isset($params['number']) ? $params['number'] : '',
        ];

        //非暂存则验空
        if (!isset($params['tempSave']) || $params['tempSave'] == false) {
            foreach($shopData as $key => $value){
                if(empty($value) && $value !== 0){
                    $this->sendOutput($key.'参数错误', ErrorCode::$paramError );
                }
            }
        }
        return $shopData;
    }

    /**
     * 列表
     */
    public function list()
    {
        $params = $this->request->getRawJson();
        $pageParams = pageToOffset($params['page'] ?: 1, $params['pageSize'] ?: 10);
        $selectParams['limit'] = $pageParams['limit'];
        $selectParams['offset'] = $pageParams['offset'];

        //uid
        if(isset($params['status']) && !empty($params['status'])){
            if ($params['status'] == 1){
                $selectParams['status'] = 1;
            }
            if ($params['status'] == 2){
                $selectParams['status'] = 2;
            }
        }

        if ($this->shopId){
            $selectParams['shopId'] = $this->shopId;
        }

        if (isset($params['shopId']) and !empty($params['shopId'])){
            $selectParams['shopId'] = $params['shopId'];
        }

        if ($params['name']){
            $selectParams['name'] = $params['name'];
        }

        if ($params['mobile']){
            $selectParams['mobile'] = $params['mobile'];
        }

        if ($params['write_mobile']){
            $selectParams['write_mobile'] = $params['write_mobile'];
        }

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

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

        $result = $this->obj->list($selectParams);
        if ($result->isSuccess()) {
            $returnData = $result->getData();
            $pageData = [
                'pageIndex' => $params['page'],
                'pageSize' => $params['pageSize'],
                'pageTotal' => $returnData['total'],
            ];
            parent::sendOutput($returnData['data'], 0, $pageData);
        } else {
            parent::sendOutput($result->getData(), ErrorCode::$dberror);
        }
    }


    /**
     * 添加
     * @throws \Exception
     */
    public function allocation()
    {
        $addStaffData = $this->commonFieldFilter();
        $this->objin->beginTransaction();
        $in = $this->objin->get(['id' => $addStaffData['id']]);

        $good = $this->objinvin->get(['linkId' => $in['materielId']]);
        if ($in['inventoryNum'] < $addStaffData['number'])  parent::sendOutput('库存不足', ErrorCode::$dberror);
        $goods = $this->objGoog->get(['id' => $in['materielId']]);
        $id = $addStaffData['id'];

        $addStaffData['name'] = $goods['title'];
        $addStaffData['image'] = json_decode($goods['images'])[0];

        $addStaffData['shopId'] = $this->shopId;
        $addStaffData['enterpriseId'] = $this->onlineEnterpriseId;
        $addStaffData['userCenterId'] = $this->onlineUserId;
        $addStaffData['warehouseId'] = $in['warehouseId'];
        unset($addStaffData['id']);
        $result = $this->obj->insert($addStaffData);

        if ($result->isSuccess()) {
            $number = $in['inventoryNum'] - $addStaffData['number'];
            $this->objin->update(['inventoryNum' => $number], $in['id']);
            $this->objinv->update(['inventoryNum' => $number], $in['id']);

            $orderId = date('Ymd-'.rand(1000, 9999));
            $shop = $this->objshop->getShopData(['id' => $this->shopId])->getData()[0];
            $data = [
                'no' => $orderId,
                'sourceId' => $this->shopId,
                'sourceNo' => $orderId,
                'originNo' => $orderId,
                'originId' => $id,
                'materielNum' => $addStaffData['number'],
                'shopId' => $this->shopId,
                'shopName' => $shop['name'],
                'operatorId' => $this->onlineUserId,
                'operatorName' => '员工',
                'remark' => '消耗品调拨',
                'source' => 1,
                'deliveryType' => 2,
                'type' => 16,
                'deleteStatus' => 5,
                'outStatus' => 2,
                'auditStatus' => 2,
                'createTime' => time(),
                'auditTime' => time(),
                'updateTime' => time(),
                'serialNum' => $orderId
            ];


            $db = new DInventoryOut('stock');
            $db->setTable($db->get_Table() . '_' . $this->onlineEnterpriseId);
            $res = $db->insert($data);
            $ins = [
                'linkId' => $res,
                'linkNo' => $orderId,
                'outWarehouse' => json_encode([[
                    'num' => $addStaffData['number'],
                    'otherNum' => '0.00000000',
                    'warehouseId' => $in['warehouseId']
                ]]),
                'materielId' => $good['materielId'],
                'materielName' => $good['materielName'],
                'materielCode' => $good['materielCode'],
                'unitName' => $good['unitName'],
                'skuId' => $good['skuId'],
                'skuName' => $good['skuName'],
                'num' => 0,
                'outNum' => $addStaffData['number'],
                'otherNum' => 0,
                'total' => $addStaffData['number'],
                'unitPrice' => 0,
                'totalPrice' => 0,
                'createTime' => time(),
                'updateTime' => time(),
                'isEq' => 4,
                'extend' => 'null',
            ];

            $dbs = new DInventoryOutDetails('stock');
            $dbs->setTable($dbs->get_Table() . '_' . $this->onlineEnterpriseId);
            $dbs->insert($ins);

            $this->objin->commit();
            parent::sendOutput('成功');
        } else {
            $this->objin->rollBack();
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }
    }


    /**
     * 详情
     * @return void
     */
    public function details()
    {
        $where = [];
        $id = $this->request->param('id');
        if(!empty($id)){
            $where['id'] = $id;
        }
        $result = $this->obj->details($where);
        if ($result->isSuccess()) {
            parent::sendOutput($result->getData());
        } else {
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }

    }

    /**
     * 修改
     * @return void
     */
    public function write_off()
    {
        $id['id'] = $this->request->param('id');
        if (empty($id['id'])) {
            $this->sendOutput('参数为空', ErrorCode::$paramError);
        }
        $params['status'] = 2;
        $params['write'] = $this->onlineUserId;
        $params['writeTime'] = time();
        $result = $this->obj->update($params, $id);
        if ($result->isSuccess()) {
            parent::sendOutput($result->getData());
        } else {
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }
    }

    public function delete()
    {

        $id['id'] = $this->request->param('id');
        if (empty($id['id'])) {
            $this->sendOutput('参数为空', ErrorCode::$paramError);
        }


        $result = $this->obj->delete($id);
        if ($result->isSuccess()) {
            parent::sendOutput($result->getData());
        } else {
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }

    }

}