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

use JinDouYun\Model\Enterprise\MEnterprise;
use Mall\Framework\Core\ErrorCode;
use Mall\Framework\Core\ResultWrapper;
use Mall\Framework\Core\StatusCode;

use JinDouYun\Cache\ShopCache;
use JinDouYun\Controller\BaseController;
use JinDouYun\Model\Shop\MShop;
use JinDouYun\Cache\TempSaveCache;

class Shop extends BaseController
{
    private $objMShop;
    private $objShopCache;
    private $objTempSaveCache;

    public function __construct($isCheckAcl = true, $isMustLogin = true)
    {
        parent::__construct($isCheckAcl, $isMustLogin);
        $this->objMShop = new MShop($this->onlineEnterpriseId, $this->onlineUserId);
        $this->objShopCache = new ShopCache();
        $this->objTempSaveCache = new TempSaveCache();
    }

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

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

        $shopData = [
            'logo' => isset($params['logo']) ? $params['logo'] : '',
            'shopType' => isset($params['shopType']) ? $params['shopType'] : '',
            'name' => isset($params['name']) ? $params['name'] : '',
            'openTime' => isset($params['openTime']) ? $params['openTime'] : '',
            'contactName' => isset($params['contactName']) ? $params['contactName'] : '',//联系人
            'mobile' => isset($params['mobile']) ? $params['mobile'] : '',//联系电话
            //'shopPartnerId' => isset($params['shopPartnerId']) ? $params['shopPartnerId'] : '',//合伙人Id
            //'partnerName' => isset($params['partnerName']) ? $params['partnerName'] : '',//负责人名称
            'salesArea'     => isset($params['salesArea']) ? $params['salesArea'] : '',//接json值
            //'isAllCountry'     => isset($params['isAllCountry']) ? $params['isAllCountry'] : 2,//是否是全国销售  1是全国  2部分
        ];

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

        //处理是否全国销售
        /*$shopData['salesArea'] = json_decode($shopData['salesArea'],true);
        if ($shopData['isAllCountry']==1 && !in_array('100000-0-0', $shopData['salesArea'])) {
            $shopData['salesArea'][] = '100000-0-0';
        }
        if ($shopData['isAllCountry']==2 && in_array('100000-0-0', $shopData['salesArea'])) {
            $pos = array_search('100000-0-0', $shopData['salesArea']);
            unset($shopData['salesArea'][$pos]);
        }
        $shopData['salesArea'] = json_encode($shopData['salesArea']);
        unset($shopData['isAllCountry']);*/
        $shopData['tempSave']= isset($params['tempSave']) ? $params['tempSave'] : false;
        $shopData['area']= isset($params['area']) ? $params['area'] : [];
        $shopData['provinceCode'] = isset($params['provinceCode']) ? $params['provinceCode'] : '';//商铺地址
        $shopData['cityCode'] = isset($params['cityCode']) ? $params['cityCode'] : '';
        $shopData['districtCode'] = isset($params['districtCode']) ? $params['districtCode'] : '';
        $shopData['address'] = isset($params['address']) ? $params['address'] : '';
        $shopData['warehouseId'] = isset($params['warehouseId']) ? $params['warehouseId'] : '';

        $shopData['longitude'] = isset($params['longitude']) ? $params['longitude'] : 0;//商铺坐标
        $shopData['latitude'] = isset($params['latitude']) ? $params['latitude'] : 0;

        $shopData['deleteStatus']= StatusCode::$standard;
        $shopData['enableStatus']= isset($params['enableStatus']) ? $params['enableStatus'] : StatusCode::$standard;
        $shopData['createTime'] = time();
        $shopData['updateTime'] = time();
        $shopData['modelType'] = getArrayItem($params,'modelType',0);
        $shopData['describe'] = isset($params['describe']) ? $params['describe'] : '';
        return $shopData;
    }

    /**
     * 添加商铺
     * @throws \Exception
     */
    public function addShop()
    {
        $dbResult = $this->objMShop->checkAllowAddShop($this->onlineEnterpriseId);
        if (!$dbResult->isSuccess()){
            parent::sendOutput($dbResult->getData(),$dbResult->getErrorCode());
        }

        $shopData = $this->commonFieldFilter();

        if ($shopData['tempSave']) {
            $this->objTempSaveCache->saveShop($this->onlineEnterpriseId, $this->onlineUserId, $shopData);
            parent::sendOutput('暂存成功');
        }

        unset($shopData['tempSave']);
        unset($shopData['area']);
        $shopData['openTime'] = json_encode($shopData['openTime']);
        $shopData['salesArea'] = json_encode($shopData['salesArea']);
        $result = $this->objMShop ->addShop($shopData);
        if($result->isSuccess()){
            //清除redis 企业和商铺关联key
            $this->objShopCache->cleanUserRelationEnterprise($this->onlineEnterpriseId);
            //删除暂存数据
            $this->objTempSaveCache->delShop($this->onlineEnterpriseId, $this->onlineUserId);
            parent::sendOutput($result->getData());
        }else{
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }

    }

    /**
     * 获取暂存信息
     */
    public function getTempData()
    {
        $salesArea = $this->objMShop->getSalesAreaInEnterprise();
        $result = $this->objTempSaveCache->getShop($this->onlineEnterpriseId, $this->onlineUserId);
        if (!empty($result['salesArea'])) {
            foreach ($result['salesArea'] as $key => &$area) {
                if (in_array($area, $salesArea)) {
                    unset($result['salesArea'][$key]);
                }
            }
        }
        $this->sendOutput($result);
    }

    /**
     * 获取指定商铺信息
     */
    public function getShopInfo()
    {
        $params['id']  = $this->request->param('request_id');
        if ( !$params['id'] ) {
            $this->sendOutput('参数错误', ErrorCode::$paramError );
        }
        $result = $this->objMShop->getShopInfo($params);

        if($result->isSuccess()){
            $this->sendOutput($result->getData());
        }else{
            $this->sendOutput($result->getData(), $result->getErrorCode());
        }
    }

    /**
     * 编辑商铺
     */
    public function editShop()
    {
        $shopId  = $this->request->param('request_id');
        if(empty($shopId)){
            $this->sendOutput('参数错误', ErrorCode::$paramError);
        }
        $shopData = $this->commonFieldFilter();
        $shopData['id'] = $shopId;
        unset($shopData['createTime']);
        unset($shopData['tempSave']);
        unset($shopData['area']);
        $shopData['openTime'] = json_encode($shopData['openTime']);
        $shopData['salesArea'] = json_encode($shopData['salesArea']);
        $shopData['warehouseId'] = array_unique($shopData['warehouseId']);
        $result = $this->objMShop->editShop($shopData);
        if($result->isSuccess()){
            parent::sendOutput($result->getData());
        }else{
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }

    }

    /**
     * 删除商铺
     */
    public function delShop()
    {
        $params['id']  = $this->request->param('request_id');
        if(!$params['id']){
            $this->sendOutput('参数错误', ErrorCode::$paramError);
        }

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

    /**
     * 商铺启用和禁用
     */
    public function updateShopStatus()
    {
        $paramsData = $this->request->getRawJson();
        if (empty($paramsData)) {
            $this->sendOutput('参数为空', ErrorCode::$paramError);
        }
        $params = [
            'id'           => isset($paramsData['id']) ? $paramsData['id'] : '',
            'enableStatus' => isset($paramsData['enableStatus']) ? $paramsData['enableStatus'] : '',
        ];
        foreach ($params as $key => $value) {
            if (empty($value) && $value !== 0) {
                $this->sendOutput($key . '参数错误', ErrorCode::$paramError);
            }
        }

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


    /**
     * 后台所有商铺列表
     */
    public function getAllShop()
    {
        $params = $this->request->getRawJson();
        if( empty($params) ){
            $this->sendOutput('参数为空', ErrorCode::$paramError );
        }

        if(isset($params['enableStatus']) && !empty($params['enableStatus'])) {
            $selectParams['enableStatus'] = $params['enableStatus'];
        }
        $pageParams = pageToOffset($params['page']?:1, $params['pageSize']?:10);
        $selectParams['limit'] = $pageParams['limit'];
        $selectParams['offset'] = $pageParams['offset'];
        isset($params['action']) && $selectParams['action'] = $params['action'];
        isset($params['materielId']) && $selectParams['materielId'] = $params['materielId'];
        $result = $this->objMShop->getAllShop($selectParams);

        if($result->isSuccess()){
            $returnData = $result->getData();
            $pageData = [
                'pageIndex' => $params['page'],
                'pageSize' => $params['pageSize'],
                'pageTotal' => $returnData['total'],
            ];
            //使用redis存入企业id下所有的商铺id
            $this->objShopCache->cacheEnterpriseAndShop($this->onlineEnterpriseId, $returnData['data']);
            parent::sendOutput($returnData['data'], 0, $pageData);
        }else{
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }
    }

    /**
     * 后台商铺搜索
     */
    public function search()
    {
        $params = $this->request->getRawJson();
        if( empty($params) ){
            $this->sendOutput('参数为空', ErrorCode::$paramError );
        }

        $selectParams = [
            'name' => isset($params['name']) ? $params['name'] : '',
            'shopPartnerId' => isset($params['shopPartnerId']) ? $params['shopPartnerId'] : '',
            'shopType' => isset($params['shopType']) ? $params['shopType'] : '',
            'enableStatus' => isset($params['enableStatus']) ? $params['enableStatus'] : '',
        ];
        $pageParams = pageToOffset($params['page']?:1, $params['pageSize']?:10);
        $selectParams['limit'] = $pageParams['limit'];
        $selectParams['offset'] = $pageParams['offset'];

        $result = $this->objMShop->search($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(), $result->getErrorCode());
        }
    }

    /**
     * 更换负责人
     */
    public function changeManagerForShop() {
        $params = $this->request->getRawJson();
        if(empty($params)){
            $this->sendOutput('参数为空', ErrorCode::$paramError );
        }

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

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

        $result = $this->objMShop->changeManagerForShop($shopData);
        if($result->isSuccess()){
            parent::sendOutput($result->getData());
        }else{
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }

    }

    /**
     * 获取当前企业下已有的销售区域
     */
    public function getSalesAreaInEnterprise() {
        $result = $this->objMShop->getSalesAreaInEnterprise();
        parent::sendOutput($result, 0, ['pageTotal'=>0]);
    }


    /**
     * 获取员工所在商铺列表
     */
    public function getShopByStaff() {
        $params = $this->request->getRawJson();
        if( empty($params) ){
            $this->sendOutput('参数为空', ErrorCode::$paramError );
        }
        $pageParams = pageToOffset($params['page']?:1, $params['pageSize']?:10);
        $selectParams['limit'] = $pageParams['limit'];
        $selectParams['offset'] = $pageParams['offset'];
        $result = $this->objMShop->getShopByStaff($selectParams);
        if(!$result->isSuccess()){
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }
        $returnData = $result->getData();
        $pageData = [
            'pageIndex' => $params['page'],
            'pageSize' => $params['pageSize'],
            'pageTotal' => $returnData['total'],
        ];
        parent::sendOutput($returnData['data'], 0, $pageData);

    }

    /**
     * 格式化商铺token
     * @return ResultWrapper
     */
    public function formatShopToken()
    {
        $result = $this->objMShop->formatShopToken();
        if(!$result->isSuccess()){
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }
        parent::sendOutput($result->getData());
    }

    /**
     * 设置总店
     * @return ResultWrapper
     */
    public function setTopShop()
    {
        $id = $this->request->param('request_id');
        if(empty($id)){
            parent::sendOutput('id参数错误', ErrorCode::$paramError);
        }
        $result = $this->objMShop->setTopShop(['id' => $id]);
        if(!$result->isSuccess()){
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }
        parent::sendOutput($result->getData());
    }

    /**
     * 设置店长
     * @throws \Exception
     */
    public function setStaffType()
    {
        $params = $this->request->getRawJson();
        if (empty($params)) {
            $this->sendOutput('参数为空', ErrorCode::$paramError);
        }
        $data = [
            "id" => isset($params['id']) ? $params['id'] : '',
            "shopId" => isset($params['shopId']) ? $params['shopId'] : '',
        ];
        foreach($data as $key => $value){
            if(empty($value)){
                parent::sendOutput($key.'参数错误', ErrorCode::$paramError);
            }
        }
        $data['enterpriseId'] = $this->onlineEnterpriseId;
        $modelResult = $this->objMShop->setStaffType($data);
        if(!$modelResult->isSuccess()){
            parent::sendOutput($modelResult->getData(), $modelResult->getErrorCode());
        }
        parent::sendOutput($modelResult->getData());
    }

    /**
     * 删除店长
     * @throws \Exception
     */
    public function delManager()
    {
        $params = $this->request->getRawJson();
        if (empty($params)) {
            $this->sendOutput('参数为空', ErrorCode::$paramError);
        }
        $data = [
            "shopId" => isset($params['shopId']) ? $params['shopId'] : '',
        ];
        foreach($data as $key => $value){
            if(empty($value)){
                parent::sendOutput($key.'参数错误', ErrorCode::$paramError);
            }
        }
        $data['enterpriseId'] = $this->onlineEnterpriseId;
        $modelResult = $this->objMShop->delManager($data);
        if(!$modelResult->isSuccess()){
            parent::sendOutput($modelResult->getData(), $modelResult->getErrorCode());
        }
        parent::sendOutput($modelResult->getData());
    }


    /**
     * 获取指定店铺绑定的所有仓库数据
     */
    public function getShopBindWarehouse()
    {
        $shopId = $this->request->param('request_id');
        if(empty($shopId)){
            parent::sendOutput('shopId参数错误', ErrorCode::$paramError);
        }
        $result = $this->objMShop->getShopBindWarehouse($shopId);
        if(!$result->isSuccess()){
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }
        parent::sendOutput($result->getData());
    }
}