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

namespace JinDouYun\Model\Shop;

use Exception;

use JinDouYun\Controller\Common\Logger;
use JinDouYun\Dao\Department\DStaff;
use JinDouYun\Dao\GoodsManage\DGoodsBasic;
use JinDouYun\Dao\UserCenter\DUserCenter;
use JinDouYun\Model\Common\Location;
use Mall\Framework\Core\ErrorCode;
use Mall\Framework\Core\StatusCode;
use Mall\Framework\Core\ResultWrapper;

use JinDouYun\Dao\Shop\DShop;
use JinDouYun\Dao\Shop\DEnterpriseBindShop;

use Jindouyun\Cache\EnterpriseCache;
use JinDouYun\Cache\RoleAclCache;
use JinDouYun\Cache\ShopCache;
use JinDouYun\Cache\SysAreaChinaCache;
use JinDouYun\Cache\GoodsBasicRelevant;

use JinDouYun\Model\ShopPartner\MShopPartner;
use JinDouYun\Model\Stock\MWarehouse;
use JinDouYun\Model\SysAreaChina\MSysAreaChina;
use JinDouYun\Model\Customer\MCustomer;
use JinDouYun\Model\Enterprise\MEnterprise;
use JinDouYun\Model\Department\MStaff;
use JinDouYun\Model\MBaseModel;
use Monolog\Handler\IFTTTHandler;


class MShop extends MBaseModel
{

    private $objDShop;
    private $objDEnterpriseBindShop;
    private $objSysAreaChinaCache;
    private $cutTable = 250000;
    private $enterpriseId;
    private $userCenterId;
    private $objMShopPartner;
    private $objRoleAclCache;
    private $objShopCache;
    private $objMEnterprise;
    private $objMStaff;

    public function __construct($enterpriseId, $userCenterId = '')
    {
        $this->enterpriseId = $enterpriseId;
        $this->userCenterId = $userCenterId;
        parent::__construct($this->enterpriseId, $this->userCenterId);
        $this->objMShopPartner = new MShopPartner($this->enterpriseId, $this->userCenterId);
        $this->objDShop = new DShop('default');
        $this->objDEnterpriseBindShop = new DEnterpriseBindShop('default');
        $this->objSysAreaChinaCache = new SysAreaChinaCache();
        $this->objRoleAclCache = new RoleAclCache();
        $this->objShopCache = new ShopCache();
        $this->objMEnterprise = new MEnterprise();
        $this->objMStaff = new MStaff($enterpriseId,$userCenterId);

        $tableName = $this->objDShop->getTableName('qianniao_shop', $this->enterpriseId, $this->cutTable);
        $this->objDShop->setTable($tableName);

        $this->objDShop->setSearchIndex('shop_search')->setType('shop');
    }

    /**
     * Doc: (des="添加店铺")
     * User: XMing
     * Date: 2020/7/15
     * Time: 10:42 上午
     * @throws Exception
     * @param array $params
     * @return ResultWrapper
     */
    public function addShop(array $params)
    {
        $params['enterpriseId'] = $this->enterpriseId;

        $objMEnterprise = new MEnterprise();
        $modelResult = $objMEnterprise->createAppid($this->userCenterId);
        $params['token'] = $modelResult['token'];

        //获取仓库
        if(isset($params['warehouseId']) && !empty($params['warehouseId'])){
            if(is_array($params['warehouseId'])){
                $warehouseId = $params['warehouseId'];
                $params['warehouseId'] = implode(',',$params['warehouseId']);
            }else{
                $warehouseId = [$params['warehouseId']];
            }
            $objMWarehouse = new MWarehouse($this->enterpriseId);
            $modelResult = $objMWarehouse->selectWarehouse(['id' => $warehouseId, 'deleteStatus' => StatusCode::$standard]);
            if(!$modelResult->isSuccess()){
                return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
            }
            $warehouseResult = $modelResult->getData();
            unset($modelResult);
            if(empty($warehouseResult)){
                return ResultWrapper::fail('仓库查询失败', ErrorCode::$paramError);
            }
            $selectWarehouseId = array_column($warehouseResult, 'id');
            foreach($warehouseId as $value){
                if(!in_array($value,$selectWarehouseId)){
                    return ResultWrapper::fail($value.'仓库查询失败', ErrorCode::$paramError);
                }
            }
        }


        $beginStatus = $this->objDShop->beginTransaction();
        $ShopId = $this->objDShop->insert($params);
        if ($ShopId === false) {
            $this->objDShop->rollBack();
            return ResultWrapper::fail($this->objDShop->error(), ErrorCode::$dberror);
        }
        //缓存token
        $this->objShopCache->setShopToken($this->enterpriseId, $ShopId, $params['token']);
        unset($params['token']);

        //缓存企业下的销售区域
        self::cacheSalesAreaInEnterprise();
        //增加企业商铺关联表
        $EnterpriseBindShopData = [
            'enterpriseId' => $params['enterpriseId'],
            'shopId'       => $ShopId,
            'updateTime'   => time(),
            'createTime'   => time(),
        ];
        $dbResult = $this->objDEnterpriseBindShop->insert($EnterpriseBindShopData);
        if($dbResult === false){
            $this->objDShop->rollBack();
            return ResultWrapper::fail($this->objDEnterpriseBindShop->error(),ErrorCode::$dberror);
        }

        /*//自动创建仓库
        $wareHouseParam = [
            'warehouseName'  => $params['name'] . '仓库',
            'shopId'         => $ShopId,
            'shopName'       => $params['name'],
            'contactMobile'  => $params['mobile'],
            'provinceCode'   => $params['provinceCode'],
            'cityCode'       => $params['cityCode'],
            'districtCode'   => $params['districtCode'],
            'contactAddress' => $params['address'],
            'updateTime'     => time(),
            'deleteStatus'   => StatusCode::$standard,
            'enableStatus'   => StatusCode::$standard,
        ];

        //添加仓库
        $objMWarehouse = new MWarehouse($this->enterpriseId);
        $warehouseResult = $objMWarehouse->addWarehouse($wareHouseParam);
        if(!$warehouseResult->isSuccess()){
            $this->objDShop->rollBack();
            return ResultWrapper::fail($warehouseResult->getData(),$warehouseResult->getErrorCode());
        }

        $warehouseId =(int) $warehouseResult->getData();
        $this->objDShop->update(['warehouseId' => $warehouseId], $ShopId);
        $objGoodsBasicRelevant = new GoodsBasicRelevant($this->enterpriseId);
        $cacheResult = $objGoodsBasicRelevant->cacheShopIdRelationName($ShopId,
            [
                'name'          => $params['name'],
                'warehouseId'   => $warehouseId,
                'warehouseName' => $wareHouseParam['warehouseName'],
                'costType'      => $params['costType']
            ]);
        if (!$cacheResult->isSuccess()) {
            $this->objDShop->rollBack();
            return ResultWrapper::fail($cacheResult->getData(), $cacheResult->getErrorCode());
        }
        $this->objRoleAclCache->cacheShopIdAndWarehouseId($this->enterpriseId, $ShopId, $warehouseId);
        //修改商铺数据
        $update = [
            'warehouseId' => $warehouseId,
            'updateTime' => time(),
        ];
        $result = $this->objDShop->update($update, ['id' => $ShopId]);
        if($result === false){
            $this->objDShop->rollBack();
            return ResultWrapper::fail($this->objDShop->error(), ErrorCode::$dberror);
        }*/

        //更新ES
        $beginStatus && $this->objDShop->commit();
//        self::updateEsData($params, $ShopId, true);
        return ResultWrapper::success($ShopId);
    }

    private function createEsDocumentId($shopId)
    {
        return 'EnterpriseId_' . $this->enterpriseId . '_ShopId_' . $shopId;
    }

    public function getShopTable() {
        return $this->objDShop->get_Table();
    }

    public function updateEsData($params, $shopId, $insert = false)
    {
        $objMSysAreaChina = new MSysAreaChina();
        if (isset($params['provinceCode']) && isset($params['cityCode']) && isset($params['districtCode'])) {
            $areaName = $objMSysAreaChina->getNameByCode([
                $params['provinceCode'],
                $params['cityCode'],
                $params['districtCode']
            ]);
            $params['provinceName'] = isset($areaName[$params['provinceCode']]) ? $areaName[$params['provinceCode']] : '';
            $params['cityName'] = isset($areaName[$params['cityCode']]) ? $areaName[$params['cityCode']] : '';
            $params['districtName'] = isset($areaName[$params['districtCode']]) ? $areaName[$params['districtCode']] : '';
        }
        if (!empty($params['latitude']) && !empty($params['longitude'])) {
            $params['shoplocation'] = [
                'lat' => $params['latitude'],
                'lon' => $params['longitude']
            ];
        }
        unset($params['latitude']);
        unset($params['longitude']);
        unset($params['openTime']);
        if(isset($params['salesArea']) && !empty($params['salesArea'])){
            $params['salesArea'] = json_decode($params['salesArea'], true);
            $params['salesArea'] = implode(',', $params['salesArea']);
        }
        $params['id'] = $shopId;
        $params['enterpriseId'] = $this->enterpriseId;
        $_id = self::createEsDocumentId($shopId);
        $result = $this->objDShop->addUpSearchIndexDocument($params, $_id);
        //print_r($result);
        if (isset($result['_shards']) && isset($result['_shards']['successful']) && $result['_shards']['successful'] == 1) {
            //echo "es操作成功";die;
        }
        //echo "es操作失败";

    }

    /**
     * 获取指定商铺信息
     * @param $params
     * @return ResultWrapper
     * @throws Exception
     */
    public function getShopInfo($params)
    {
        $dbResult = $this->objDShop->get($params);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDShop->error(), ErrorCode::$dberror);
        } else {
            $dbResult = $this->format([$dbResult]);
            $dbResult = array_shift($dbResult);
            return ResultWrapper::success($dbResult);
        }
    }


    /**
     * 编辑商铺
     * @param int|array $params 修改商铺的数据
     * @return ResultWrapper
     * @throws Exception
     */
    public function editShop($params)
    {
        if (empty($params['id'])) {
            return ResultWrapper::fail('没有指定要修改的商铺id', ErrorCode::$paramError);
        }
        $shopInfo = $this->objDShop->get(['id' => $params['id']], 'id,warehouseId');
        if ($shopInfo === false) {
            return ResultWrapper::fail($this->objDShop->error(), ErrorCode::$paramError);
        }
        $updateShopId = $params['id'];
        unset($params['id']);
        $shopPartnerId = isset($params['shopPartnerId']) ? $params['shopPartnerId'] : '';
        unset($params['shopPartnerId']);
        unset($params['partnerName']);

        //获取仓库
        if(isset($params['warehouseId']) && !empty($params['warehouseId'])){
            if(is_array($params['warehouseId'])){
                $warehouseId = $params['warehouseId'];
                $params['warehouseId'] = implode(',',$params['warehouseId']);
            }else{
                $warehouseId = [$params['warehouseId']];
            }
            $objMWarehouse = new MWarehouse($this->enterpriseId);
            $modelResult = $objMWarehouse->selectWarehouse(['id' => $warehouseId, 'deleteStatus' => StatusCode::$standard]);
            if(!$modelResult->isSuccess()){
                return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
            }
            $warehouseResult = $modelResult->getData();
            unset($modelResult);
            if(empty($warehouseResult)){
                return ResultWrapper::fail('仓库查询失败', ErrorCode::$paramError);
            }
            $selectWarehouseId = array_column($warehouseResult, 'id');
            foreach($warehouseId as $value){
                if(!in_array($value,$selectWarehouseId)){
                    return ResultWrapper::fail($value.'仓库查询失败', ErrorCode::$paramError);
                }
            }
        }


        $dbResult = $this->objDShop->update($params, $updateShopId);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDShop->error(), ErrorCode::$dberror);
        }

        if ($shopPartnerId) {
            self::changeManagerForShop(['id'=>$updateShopId,'shopPartnerId'=>$shopPartnerId]);
        }
        //查出企业的店铺下所有的销售区域，缓存到redis
        self::cacheSalesAreaInEnterprise();

        $objGoodsBasicRelevant = new GoodsBasicRelevant($this->enterpriseId);
        $objGoodsBasicRelevant->cacheShopIdRelationName($updateShopId,
            [
                'name'          => $params['name'],
                'warehouseId'   => isset($params['warehouseId']) ? $params['warehouseId'] :$shopInfo['warehouseId'],
                'warehouseName' => isset($params['warehouseName']) ? $params['warehouseName'] : $params['name'] . '仓库',
                'costType'      => $params['costType']
            ]);

        //更新ES
        //self::updateEsData($params, $updateShopId);
        return ResultWrapper::success($dbResult);
    }

    /**
     * 更换负责人
     * @param int|array $params 修改商铺的数据
     *
     * @return ResultWrapper
     * @throws Exception
     */
    public function changeManagerForShop($params)
    {
        if (empty($params['id'])) {
            return ResultWrapper::fail('没有指定要修改的商铺id', ErrorCode::$paramError);
        }

        $shopPartnerId = isset($params['shopPartnerId']) ? $params['shopPartnerId'] : '';

        //修改原来负责人的商铺数据
        $shopPartnerInfo = $this->objMShopPartner->getShopPartnerInfo($shopPartnerId);
        if($shopPartnerInfo->isSuccess() == false) {
            return ResultWrapper::fail($shopPartnerInfo->getData(), $shopPartnerInfo->getErrorCode());
        }
        $shopPartnerInfo = $shopPartnerInfo->getData();
        $shopIds = explode(',', $shopPartnerInfo['shopId']);
        foreach($shopIds as $k => $shopId) {
            if($shopId == $params['id']) {
                unset($shopIds[$k]);
            }
        }
        $result = $this->objMShopPartner->updateShopIds(trim(implode(',',$shopIds),','),$shopPartnerId);
        if($result->isSuccess() == false) {
            return ResultWrapper::fail($result->getData(), $result->getErrorCode());
        }

        //更改商铺的合伙人
        $result = self::updateShopPartnerId(['id'=>$params['id'], 'shopPartnerId'=>$shopPartnerId]);
        if($result->isSuccess() == false) {
            return ResultWrapper::fail($result->getData(), $result->getErrorCode());
        }

        //更改合伙人的商铺
        //查出该合伙人管理的所有商铺
        $shopIds = $this->objMShopPartner->getShopIdsByPartnerId($shopPartnerId);
        $dbResult = $this->objMShopPartner->updateShopIds(trim(implode(',', array_filter(array_merge($shopIds, [$params['id']]))),","), $shopPartnerId);

        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDShop->error(), ErrorCode::$dberror);
        } else {
            return ResultWrapper::success($dbResult);
        }
    }

    /**
     * 删除商铺
     * @param array $params
     * @return ResultWrapper
     */
    public function delShop($params)
    {
        if (empty($params)) {
            return ResultWrapper::fail('参数错误', ErrorCode::$paramError);
        }
        $dbResult = $this->objDShop->update(['deleteStatus' => StatusCode::$delete], $params);

        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDShop->error(), ErrorCode::$dberror);
        } else {
            //在ES删除
            //$_id = self::createEsDocumentId($params['id']);
            //$this->objDShop->esdeleteTypeDocument($_id);
            return ResultWrapper::success($dbResult);
        }
    }

    /**
     * 商铺启用和禁用
     * @param array $params
     * @return ResultWrapper
     */
    public function updateShopStatus($params)
    {
        $dbResult = $this->objDShop->update(['enableStatus' => $params['enableStatus']], $params['id']);

        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDShop->error(), ErrorCode::$dberror);
        } else {
            /*$_id = self::createEsDocumentId($params['id']);
            $result = $this->objDShop->esupdateTypeFieldVaule(['enableStatus' => $params['enableStatus']], $_id);*/
            return ResultWrapper::success($dbResult);
        }
    }

    public function updateShopPartnerId($params)
    {
        $dbResult = $this->objDShop->update(['shopPartnerId' => $params['shopPartnerId']], $params['id']);

        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDShop->error(), ErrorCode::$dberror);
        } else {
            return ResultWrapper::success($dbResult);
        }
    }

    /*
     * 处理搜索条件
     */
    public function search($params)
    {
        $limit = $params['limit'];
        unset($params['limit']);
        $offset = $params['offset'];
        unset($params['offset']);

        $condition = 'deleteStatus = ' . StatusCode::$standard.' AND enterpriseId='.$this->enterpriseId;
        if ($params['name']) {
            $condition .= " AND name like '%" . $params['name'] . "%'";
        }
        if ($params['shopPartnerId']) {
            $condition .= " AND shopPartnerId = " . $params['shopPartnerId'];
        }

        if ($params['shopType']) {
            $condition .= " AND shopType = " . $params['shopType'];
        }

        if ($params['enableStatus']) {
            $condition .= " AND enableStatus = " . $params['enableStatus'];
        }

        $dbResult = $this->objDShop->select($condition, '*', 'createTime desc', $limit, $offset);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDShop->error(), ErrorCode::$dberror);
        }
        $dbResult = self::format($dbResult);

        $return = [
            'data'  => $dbResult,
            'total' => $this->getShopTotal($condition)
        ];

        return ResultWrapper::success($return);

    }

    /**
     * 获取所有商铺数据
     * @param array $selectParams 过滤条件
     * @param string $fields 查询的字段
     * @return ResultWrapper
     * @throws Exception
     */
    public function getAllShop($selectParams, $fields = '*')
    {

        $fields = ' * ';
        $countField = ' COUNT(id) as total ';
        $where = '';
        if (isset($selectParams['enableStatus']) && !empty($selectParams['enableStatus'])){
            $where .= '  AND enableStatus = '.$selectParams['enableStatus'];
        }

        if (isset($selectParams['action']) && $selectParams['action'] == 1){
            //基础资料详情页面用来过滤禁止销售店铺
            if (isset($selectParamsp['materielId']) && !empty($selectParams['materielId'])){
                $objDGoodsBasic = new DGoodsBasic();
                $objDGoodsBasic->setTable('qianniao_goods_basic_'.$this->enterpriseId);
                $row = $objDGoodsBasic->get($selectParams['materielId']);
                if ($row === false){
                    return ResultWrapper::fail($objDGoodsBasic->error(),ErrorCode::$dberror);
                }
                $noSaleShopIds = '';
                if (isset($row['noSalesShop']) && !empty($row['noSalesShop'])){
                    $noSaleShopIds = trim(explode($row['noSalesShop'],','),',');
                }
                if (!empty($noSaleShopIds)){
                    $where .= ' AND id NOT IN('.$noSaleShopIds.')';
                }
            }
        }

        $sql  = 'SELECT '.$fields.' FROM qianniao_shop_1 WHERE enterpriseId = '.$this->enterpriseId.' AND deleteStatus = '.StatusCode::$standard.' AND merchantId IS NULL '.$where;

        $countSql  = 'SELECT '.$countField.' FROM qianniao_shop_1 WHERE enterpriseId = '.$this->enterpriseId.' AND deleteStatus = '.StatusCode::$standard.' AND merchantId IS NULL '.$where;

        if (isset($selectParams['limit']) && !empty($selectParams['limit'])){
            $sql .= ' LIMIT '.$selectParams['offset'].','.$selectParams['limit'];
        }
        $dbResult = $this->objDShop->query($sql);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDShop->error(), ErrorCode::$dberror);
        }

        $dbResult = self::format($dbResult);
        $count = $this->objDShop->query($countSql);
        if ($count === false){
            return ResultWrapper::fail($this->objDShop->error(), ErrorCode::$dberror);
        }
        $return = [
            'data'  => $dbResult,
            'total' => isset($count[0]['total']) ? $count[0]['total'] : 0,
        ];

        return ResultWrapper::success($return);

    }

    /**
     * 获取商品总数
     * @param $where mixed
     * @return int
     */
    public function getShopTotal($where)
    {
        $total = $this->objDShop->count($where);
        return ($total) ? intval($total) : 0;
    }

    /**
     * 处理开业时间 和省市区
     * @param $data
     * @return mixed
     */
    public function format($data)
    {
        $objMSysAreaChina = new MSysAreaChina();
        $managerIds = [];
        $warehouseIds = [];
        foreach ($data as $key => $shop) {
            $data[$key]['openTime'] = isset($shop['openTime']) ? (array)json_decode($shop['openTime'], true) : '';
            $data[$key]['shopCode'] = createCode(StatusCode::$code['shop']['prefix'], $shop['id'], StatusCode::$code['shop']['length']);
            if (isset($shop['provinceCode']) && isset($shop['cityCode']) && isset($shop['districtCode'])) {
                $areaName = $objMSysAreaChina->getNameByCode([
                    $shop['provinceCode'],
                    $shop['cityCode'],
                    $shop['districtCode']
                ]);
                $data[$key]['area']['provinceName'] = isset($areaName[$shop['provinceCode']]) ? $areaName[$shop['provinceCode']] : '';
                $data[$key]['area']['cityName'] = isset($areaName[$shop['cityCode']]) ? $areaName[$shop['cityCode']] : '';
                $data[$key]['area']['districtName'] = isset($areaName[$shop['districtCode']]) ? $areaName[$shop['districtCode']] : '';
                $data[$key]['area']['address'] = $shop['address'];
            }
            if(!empty($shop['managerId'])) {
                $managerIds[] = $shop['managerId'];
            }
            if(!empty($shop['warehouseId'])) {
                if (strpos($shop['warehouseId'], ',')) {
                    $warehouseIds = array_merge($warehouseIds, explode(',', $shop['warehouseId']));
                } else {
                    $warehouseIds[] = $shop['warehouseId'];
                }
            }
            if (!isset($shop['meters'])){
                $data[$key]['meters'] = null;
            }
        }
        $staff = [];
        if (!empty($managerIds)) {
            //查出商铺的所有店长
            $where = [
                'shopId' => 0,
                'userCenterId' => $managerIds,
                'deleteStatus' => StatusCode::$standard
            ];
            $modelResult = $this->objMStaff->getAllStaffData($where);
            if(!$modelResult->isSuccess()){
                return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
            }
            $staffResult = $modelResult->getData();
            unset($modelResult);
            foreach($staffResult as $value){
                $staff[$value['userCenterId']] = $value;
            }

        }
        $warehouseData = [];
        if (isset($warehouseIds) && $warehouseIds) {
            //查出仓库信息
            $objMWarehouse = new MWarehouse($this->enterpriseId);
            $warehouseResult = $objMWarehouse->getNameByIds($warehouseIds);
            if ($warehouseResult->isSuccess()) {
                $warehouseData = $warehouseResult->getData();
            }
        }

        foreach ($data as &$shop) {
            $shop['warehouseData'] = [];
            $shop['managerName'] = isset($staff[$shop['managerId']]) ? $staff[$shop['managerId']]['staffName'] : '';//店长名称

            $shop['salesArea'] = !empty($shop['salesArea']) ? json_decode($shop['salesArea'], true) : [];
            /*if (in_array('100000-0-0', $shop['salesArea'])) {
                $pos = array_search('100000-0-0', $shop['salesArea']);
                unset($shop['salesArea'][$pos]);
                $shop['isAllCountry'] = 1;
            }else {
                $shop['isAllCountry'] = 2;
            }*/
            if (!empty($shop['warehouseId'])) {
                if(strpos($shop['warehouseId'],',')){
                    $wid = explode(',', $shop['warehouseId']);
                }else{
                    $wid = [$shop['warehouseId']];
                }
                foreach($wid as $v){
                    if(isset($warehouseData[$v])){
                        $shop['warehouseData'][$v] = [
                            'warehouseId' => $v,
                            'warehouseCode' => createCode(StatusCode::$code['warehouse']['prefix'], $v, StatusCode::$code['warehouse']['length']),
                            'warehouseName' => $warehouseData[$v]['warehouseName']
                        ];
                    }
                }
            }
        }

        //$data['warehouseData'] = array_values($data['warehouseData']);
        return $data;
    }

    /**
     * Doc: (des="")
     * User: XMing
     * Date: 2021/3/4
     * Time: 12:10 下午
     * @param array $shopIds
     * @param string $field
     * @return ResultWrapper
     */
    public function getShopByIds(array $shopIds,string $field = "*"): ResultWrapper
    {
        if (empty($shopIds)){
            return ResultWrapper::success([]);
        }
        $dbResult = $this->objDShop->select(array_values($shopIds), $field);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDShop->error(),ErrorCode::$dberror);
        }
        return ResultWrapper::success($dbResult);
    }


    /**
     * 获取指定商铺信息
     * @param $shopIds
     * @param string $field
     * @return array
     * @deprecated
     */
    public function getShopName($shopIds, $field = "*")
    {
        $return = [];
        if (!$shopIds) {
            return $return;
        }

        $dbResult = $this->objDShop->select(array_values($shopIds), $field);
        if ($dbResult === false) {
            return $return;
        }

        foreach ($dbResult as $shop) {
            $return[$shop['id']] = $shop;
        }
        return $return;
    }

    /**
     * 单个商铺Id查询商铺名称
     * @param $shopId
     * @return string
     */
    public function getShopNameById($shopId)
    {
        $return = '';
        if (empty($shopId)) {
            return $return;
        }

        $dbResult = $this->objDShop->get($shopId, 'name');
        if ($dbResult === false || empty($dbResult)) {
            return $return;
        }
        return isset($dbResult['name']) ? $dbResult['name'] : $return;
    }

    /**
     * 会员所在地区销售商品的店铺
     * @param $userCenterId
     * @param $areaCode
     * @return ResultWrapper
     * @throws Exception
     */
    public function getShopIdsByArea($userCenterId, $areaCode='')
    {

        $defaultDSL = [
            'sort' => [
                'createTime' => [
                    'order' => 'desc'
                ],
            ],
        ];

        $dsl = [];
        $dsl['query']['bool']['must'][] = [
           'term' => ['enterpriseId' => $this->enterpriseId],
       ];
       $dsl['query']['bool']['must'][] = [
           'term' => ['enableStatus' => StatusCode::$standard],
       ];

        if (!empty($areaCode)) {
            $dsl['query']['bool']['must'][] = [
                'term' => [
                    'salesArea' => $areaCode
                ],
            ];
        } elseif ($userCenterId){
            //查出当前用户的省市区
            $objMCustomer = new MCustomer($this->enterpriseId, $this->userCenterId);
            $customerData = $objMCustomer->getCustomerInfoByUserCenterId($userCenterId);
            if ($customerData->isSuccess()) {
                $customerInfo = $customerData->getData();
                $provinceCode = isset($customerInfo['provinceCode']) ? $customerInfo['provinceCode'] : 0;
                $cityCode = isset($customerInfo['cityCode']) ? $customerInfo['cityCode'] : 0;
                $districtCode = isset($customerInfo['districtCode']) ? $customerInfo['districtCode'] : 0;
                //V($provinceCode.'-'.$cityCode.'-'.$districtCode);
                $dsl['query']['bool']['must'][] = [
                    'term' => [
                        'salesArea' => $provinceCode . '-' . $cityCode . '-' . $districtCode
                    ],
                ];
                /*
                 * 处理全国销售
                 * $dsl['query']['bool']['should'][] = [
                    'term' => [
                        'salesArea' => '100000-0-0'
                    ],
                ];
                $dsl['query']['bool']['minimum_should_match'] = 1;*/
            }
        }else {
            return ResultWrapper::success([]);
        }


        //V($dsl);
        $dsl = array_merge($defaultDSL, $dsl);
        $result = $this->objDShop->getSearchQueryDsl($dsl);
        if (isset($result['status']) && $result['status'] == 400) {
            file_put_contents('/www/wwwroot/logs/api.junhailan.com/elasticsearch.log',date('Y-m-d H:i:s').'获取商铺失败，错误原因'.var_export($result,true).PHP_EOL,FILE_APPEND);
            if ($result['error']['reason'] == 'all shards failed') {
                return ResultWrapper::success([]);
            }
            return ResultWrapper::fail('获取商铺数据失败' . $result['error']['reason'], ErrorCode::$apiNotResult);
        }

        if (!isset($result['hits']) || $result['hits']['total'] == 0) {
            return ResultWrapper::success([]);
        }
        $dbResult = $result['hits']['hits'];

        $list = [];
        foreach ($dbResult as $key => &$value) {
            $data = [];
            $data = $value['_source'];
            //$data['id'] = $value['_id'];
            $list[] = $data['id'];
        }
        return ResultWrapper::success($list);
    }

    /**
     * 根据省市区获取商铺
     * @param $params
     * @return ResultWrapper
     * @throws Exception
     */
    public function getShopIdByArea($params)
    {
        $defaultDSL = [
            'sort' => [
                'createTime' => [
                    'order' => 'desc'
                ],
            ],
        ];

        $dsl = [];
        $dsl['query']['bool']['must'][] = [
            'term' => ['enterpriseId' => $this->enterpriseId],
        ];
        $dsl['query']['bool']['must'][] = [
            'term' => ['enableStatus' => StatusCode::$standard],
        ];

        $provinceCode = isset($params['provinceCode']) ? $params['provinceCode'] : 0;
        $cityCode = isset($params['cityCode']) ? $params['cityCode'] : 0;
        $districtCode = isset($params['districtCode']) ? $params['districtCode'] : 0;
        $dsl['query']['bool']['must'][] = [
            'term' => [
                'salesArea' => $provinceCode . '-' . $cityCode . '-' . $districtCode
            ]
        ];

        $dsl = array_merge($defaultDSL, $dsl);
        $result = $this->objDShop->getSearchQueryDsl($dsl);

        if (isset($result['status']) && $result['status'] == 400) {
            return '';
            /*if($result['error']['reason'] == 'all shards failed') {
                return ResultWrapper::success('');
            }
            return ResultWrapper::fail('获取商铺数据失败' . $result['error']['reason'], ErrorCode::$apiNotResult);*/
        }

        if (!isset($result['hits']) || $result['hits']['total'] == 0) {
            return '';
        }
        $dbResult = $result['hits']['hits'];

        $list = [];
        foreach ($dbResult as $key => &$value) {
            $data = [];
            $data = $value['_source'];
            $list[] = $data['id'];
        }
        return array_shift($list);
    }


    /**
     * 获取当前企业下的销售区域
     */
    public function getSalesAreaInEnterprise()
    {
        $salesArea = $this->objShopCache->getEnterpriseSalesArea($this->enterpriseId);
        return !empty($salesArea) ? array_values(json_decode($salesArea, true)) : [];
    }

    /**
     * sql查询企业下的所有商铺销售区域
     */
    public function cacheSalesAreaInEnterprise() {
        $selectParams['enterpriseId'] = $this->enterpriseId;
        $selectParams['deleteStatus'] = StatusCode::$standard;
        $dbResult = $this->objDShop->select($selectParams, 'salesArea');

        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDShop->error(), ErrorCode::$dberror);
        }
        $allAreaByEnterprise = [];
        foreach ($dbResult as $area) {
            $salesArea = !empty($area['salesArea']) ? json_decode($area['salesArea'], true) : [];
            if($salesArea) {
                $allAreaByEnterprise = array_merge($allAreaByEnterprise, $salesArea);
            }
        }
        $this->objShopCache->cacheEnterpriseSalesArea($this->enterpriseId, $allAreaByEnterprise);
    }

    /**
     * 获取企业下商铺总数
     * @param $enterpriseId
     * @return ResultWrapper
     */
    public function getShopTotalByEnterpriseId($enterpriseId)
    {
        if(empty($enterpriseId)) return ResultWrapper::fail('参数为空', ErrorCode::$paramError);
        $cacheEnterpriseCache = new EnterpriseCache();
        $cacheResult = $cacheEnterpriseCache->delShopTotalByEnterpriseId($enterpriseId);

        unset($cacheResult);
        $cacheResult = $cacheEnterpriseCache->getShopTotalByEnterpriseId($enterpriseId);
        if($cacheResult){
            return ResultWrapper::success($cacheResult);
        }
        $dbResult = $this->objDShop->count(['enterpriseId' => $enterpriseId, 'deleteStatus' => StatusCode::$standard]);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDShop->error(), ErrorCode::$dberror);
        }
        if(empty($dbResult)){
            $returnData = 0;
        }else{
            $returnData = $dbResult;
        }
        unset($cacheResult);
        $cacheResult = $cacheEnterpriseCache->setShopTotalByEnterpriseId($enterpriseId, $returnData);

        return ResultWrapper::success($returnData);
    }

    /**
     * @param $enterpriseId
     * @return ResultWrapper
     * @throws Exception
     */
    public function checkAllowAddShop($enterpriseId)
    {
        $enterpriseResult = $this->objMEnterprise->getEnterpriseDataByEnterpriseId($enterpriseId);
        if (!$enterpriseResult->isSuccess()){
            return ResultWrapper::fail($enterpriseResult->getData(),$enterpriseResult->getErrorCode());
        }
        $enterprise = $enterpriseResult->getData();
        if ($enterprise['scope'] == StatusCode::$standard){
            //多店铺,不限制创建数量
            return ResultWrapper::success($enterprise['scope']);
        }

        //单店铺，查询已创建数量
        $shopResult = self::getShopTotalByEnterpriseId($enterpriseId);
        if (!$shopResult->isSuccess()){
            return ResultWrapper::fail($shopResult->getData(),$shopResult->getErrorCode());
        }
        $shopNum =(int) $shopResult->getData();
        if ($shopNum == 0){
            return ResultWrapper::success($enterprise['scope']);
        }

        return ResultWrapper::fail('您已经创建过店铺了',ErrorCode::$paramError);
    }

    /**
     * @param int $enterpriseId
     * @param string $fields
     * @return ResultWrapper
     */
    public function getScopeShopInfo(int $enterpriseId, string $fields)
    {
        $dbResult = $this->objDShop->get(['enterpriseId' => $enterpriseId,'deleteStatus'=>StatusCode::$standard],$fields);
        if ($dbResult === false){
            return ResultWrapper::fail($this->objDShop->error(),ErrorCode::$dberror);
        }
        return ResultWrapper::success($dbResult);
    }

    /**
     * 根据shopIds获取商铺数据
     * @param $shopIds
     * @return ResultWrapper
     */
    public function getShopDataByShopIds($shopIds)
    {
        if(empty($shopIds)) return ResultWrapper::fail('shopIds参数错误', ErrorCode::$paramError);
        $dbResult = $this->objDShop->select(['id' => $shopIds]);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDShop->error(), ErrorCode::$dberror);
        }
        if(empty($dbResult)){
            return ResultWrapper::fail('商铺不存在', ErrorCode::$dberror);
        }

        $objGoodsBasicRelevant = new GoodsBasicRelevant($this->enterpriseId);
        $formatData = [];
        foreach($dbResult as $value){
            if(isset($value['warehouseId']) && !empty($value['warehouseId'])){
                $value['warehouseName'] = '';
                if(!isset($value['warehouseName']) || empty($value['warehouseName'])){
                    $value['warehouseName'] = $objGoodsBasicRelevant->getNameByWarehouseId($value['warehouseId']);
                }
            }
            $formatData[$value['id']] = $value;
        }
        return ResultWrapper::success($formatData);
    }

    /**
     * 获取员工所在商铺列表
     * @param $params
     * @return ResultWrapper
     */
    public function getShopByStaff($params)
    {
        //1.判断当前登录人角色  区分是否返回所有商铺列表
        $modelResult = $this->objMEnterprise->getEnterpriseDataByEnterpriseId($this->enterpriseId);
        if(!$modelResult->isSuccess()){
            return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
        }
        $enterprise = $modelResult->getData();

        unset($modelResult);
        //如果是管理员返回所有商铺列表
        if($enterprise['userCenterId'] == $this->userCenterId){
            $modelResult = self::getAllShop($params);
            if(!$modelResult->isSuccess()){
                return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
            }
            return ResultWrapper::success($modelResult->getData());
        }

        //如果不是管理员  则返回该用户绑定的商铺列表
        $sql = 'select * from qianniao_user_bind_enterprise where userCenterId = '.$this->userCenterId.' and enterpriseId = '.$this->enterpriseId;
        $dbResult = $this->objDShop->query($sql);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDShop->error(), ErrorCode::$dberror);
        }
        $shopIds = [];
        foreach($dbResult as $value){
            !empty($value['shopId']) && $shopIds[] = $value['shopId'];
        }
        unset($dbResult);

        $whereSql = ' WHERE deleteStatus = '.StatusCode::$standard.' and enterpriseId = '.$this->enterpriseId;
        if (!empty($shopIds)){
            $whereSql .= ' AND id in ('.implode(',',$shopIds).') ';
        }
        $sql = 'select * from qianniao_shop_1 '.$whereSql.' order by createTime ASC limit '.$params['offset'].','.$params['limit'];
        $dbResult = $this->objDShop->query($sql);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDShop->error(), ErrorCode::$dberror);
        }
        $data = $dbResult;
        unset($dbResult);

        $countSql = 'select count(*) as count from qianniao_shop_1 '.$whereSql;
        $dbResult = $this->objDShop->query($countSql);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDShop->error(), ErrorCode::$dberror);
        }
        $count = array_shift($dbResult)['count'];
        $return = [
            'data' => self::format($data),
            'total' => $count
        ];
        return ResultWrapper::success($return);
    }

    /**
     * 格式化商铺token
     * @return ResultWrapper
     */
    public function formatShopToken()
    {
        $dbResult = $this->objDShop->select();
        if($dbResult === false){
            return ResultWrapper::fail($this->objDShop->error(), ErrorCode::$dberror);
        }
        $objMEnterprise = new MEnterprise();
        foreach($dbResult as $value){
            $data = $objMEnterprise->createAppid($value['enterpriseId']);
            $this->objDShop->update(['token' => $data['token']], ['id' => $value['id']]);
            $this->objShopCache->setShopToken($value['enterpriseId'], $value['id'], $data['token']);
        }
        return ResultWrapper::success('操作成功');
    }

    /**
     * 设置总店
     * @param $params
     * @return ResultWrapper
     */
    public function setTopShop($params)
    {
        $dbResult = $this->objDShop->get(['id' => $params['id'], 'deleteStatus' => StatusCode::$standard]);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDShop->error(), ErrorCode::$dberror);
        }
        if(empty($dbResult)){
            return ResultWrapper::fail('商铺不存在', ErrorCode::$dberror);
        }
        if($dbResult['isMaster'] == StatusCode::$standard){
            return ResultWrapper::fail('已经是总店了', ErrorCode::$dberror);
        }
        $dbResult = $this->objDShop->update(['enterpriseId' => $this->enterpriseId, 'isMaster' => StatusCode::$delete, 'updateTime' => time()]);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDShop->error(), ErrorCode::$dberror);
        }
        $dbResult = $this->objDShop->update(['isMaster' => StatusCode::$standard, 'updateTime' => time()], ['id' => $params['id']]);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDShop->error(), ErrorCode::$dberror);
        }
        return ResultWrapper::success($dbResult);
    }

    /**
     * 设置店长
     * @param $params
     * @return ResultWrapper
     */
    public function setStaffType($params)
    {
        //1.判断员工是否存在
        $modelResult = $this->objMStaff->getStaffData(['id' => $params['id'], 'deleteStatus' => StatusCode::$standard]);
        if(!$modelResult->isSuccess()){
            return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
        }
        $staff = $modelResult->getData();
        $userCenterId = getArrayItem($staff,'userCenterId',0);
        unset($modelResult);
        if(empty($staff)){
            return ResultWrapper::fail('员工不存在', ErrorCode::$paramError);
        }
        //2.判断该店铺是否已经有店长
        $dbResult = $this->objDShop->get(['id' => $params['shopId'], 'deleteStatus' => StatusCode::$standard]);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDShop->error(), ErrorCode::$dberror);
        }
        $shop = $dbResult;
        unset($dbResult);
        if(empty($shop)){
            return ResultWrapper::fail('商铺不存在', ErrorCode::$paramError);
        }
        if(!empty($shop['managerId'])){
            return ResultWrapper::fail('该店铺已有店长', ErrorCode::$paramError);
        }
        //3.如果该店铺下没有这个员工的话 把该员工添加到该商铺
        $modelResult = $this->objMStaff->getStaffData(['userCenterId' => $userCenterId, 'shopId' => $params['shopId'], 'deleteStatus' => StatusCode::$standard]);
        if(!$modelResult->isSuccess()){
            return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
        }
        $staffBindShop = $modelResult->getData();
        unset($modelResult);
        if(empty($staffBindShop)){
            $objDUserCenter = new DUserCenter();
            $dbResult = $objDUserCenter->get(['id' => $staff['userCenterId']]);
            if($dbResult === false){
                return ResultWrapper::fail($objDUserCenter->error(), ErrorCode::$dberror);
            }
            $staff['mobile'] = $dbResult['mobile'];
            $staff['shopId'] = $params['shopId'];
            unset($staff['id']);
            unset($dbResult);
            $modelResult = $this->objMStaff->addStaff($staff);
            if(!$modelResult->isSuccess()){
                return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
            }
        }

        //4.添加店长
        $update = [
            'managerId' => $userCenterId,
            'updateTime' => time(),
        ];

        $dbResult = $this->objDShop->update($update, ['id' => $params['shopId']]);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDShop->error(), ErrorCode::$dberror);
        }
        return ResultWrapper::success($userCenterId);
    }

    /**
     * 删除店长
     */
    public function delManager($params)
    {
        $where = [
            'id' => $params['shopId'],
            'enterpriseId' => $params['enterpriseId']
        ];
        $dbResult = $this->objDShop->get($where);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDShop->error(), ErrorCode::$dberror);
        }
        $shop = $dbResult;
        unset($dbResult);
        if(empty($shop)){
            return ResultWrapper::fail('商铺不存在', ErrorCode::$paramError);
        }
        if(empty($shop['managerId'])){
            return ResultWrapper::fail('店长不存在', ErrorCode::$paramError);
        }
        //1.删除员工 userCenter与店铺绑定关系
        $delWhere = [
            'userCenterId' => $shop['managerId'],
            'shopId' => $shop['id']
        ];
        $modelResult = $this->objMStaff->deleteStaff($delWhere);
        if(!$modelResult->isSuccess()){
            return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
        }

        $update = [
            'managerId' => NULL,
            'updateTime' => time(),
        ];
        $dbResult = $this->objDShop->update($update,$where);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDShop->error(), ErrorCode::$dberror);
        }
        return ResultWrapper::success($dbResult);
    }

    /**
     * Doc: (des="组装距离计算sql")
     * User: XMing
     * Date: 2020/12/10
     * Time: 10:15 上午
     * @param string $lon1 用户当前经度
     * @param string $lat1 用户当前纬度
     * @param string $lon2 数据库经度的字段名
     * @param string $lat2 数据库纬度的字段名
     * @return string
     */
    public static function buildDistanceSql($lon1='',$lat1='',$lon2='longitude',$lat2='latitude'): string
    {
        $PI = PI;
        $sql = "ROUND(6378.138 * 2 * ASIN( SQRT(POW(SIN( ({$lat1} * $PI / 180 - {$lat2} * $PI / 180 ) / 2 ),2) + COS({$lat1} * $PI / 180) * COS({$lat2} * $PI / 180) * POW(SIN( ({$lon1} * $PI / 180 - {$lon2} * $PI / 180 ) / 2) ,2)) ) * 1000) / 1000 ";
        return $sql;
    }


    /**
     * Doc: (des="获取附近商家列表-按照距离排序-sql")
     * User: XMing
     * Date: 2020/12/10
     * Time: 10:23 上午
     * @param array $data
     * @param $lon1
     * @param $lat1
     * @return ResultWrapper
     */
    public function nearbyLists(array $data,$lon1,$lat1): ResultWrapper
    {
        //$lon1 = '108.978695';
        //$lat1 = '34.321583';
        $map = [];
        $noLocalMap = [];
        foreach ($data as $value){
            if (!empty($value['longitude']) && !empty($value['latitude'])){
                $map[] = $value;
                continue;
            }
            $noLocalMap[] = $value;
        }
        $objLocation = new Location();
        foreach ($map as &$value){
            $sub = $objLocation->get_distance_by_geo($lat1,$lon1,$value['latitude'],$value['longitude']);
            $value['sub'] = $sub;
        }
        unset($value);
        $subColl = array_column($map,'sub');
        array_multisort($subColl,SORT_ASC,$map);

        foreach ($map as &$value){
            $value['meters'] = Location::toMeters($value['sub']);
        }
        unset($value);

        foreach ($noLocalMap as &$value){
            $value['meters'] = null;
        }
        unset($value);

        $map = array_merge($map,$noLocalMap);
        return ResultWrapper::success($map);
    }

    /**
     * Doc: (des="根据企业id获取企业下总店")
     * User: XMing
     * Date: 2020/12/17
     * Time: 4:50 下午
     * @param int $enterpriseId
     * @return ResultWrapper
     */
    public function getCenterShopByEnterprise(int $enterpriseId): ResultWrapper
    {
        $shop = $this->objDShop->get(['enterpriseId' => $enterpriseId,'isMaster' => StatusCode::$standard],'id,name');
        if ($shop === false){
            return ResultWrapper::fail($this->objDShop->error(),ErrorCode::$dberror);
        }
        return ResultWrapper::success($shop);
    }

    /**
     * Doc: (des="")
     * User: XMing
     * Date: 2020/12/30
     * Time: 5:03 下午
     * @param $ids
     * @return ResultWrapper
     */
    public function getShopIdByMerchantIds($ids): ResultWrapper
    {
        if (empty($ids)){
            return ResultWrapper::success([]);
        }
        $lists = $this->objDShop->select(['merchantId'=>$ids],'*');
        if ($lists === false){
            return ResultWrapper::fail($this->objDShop->error(),ErrorCode::$dberror);
        }
        $map = [];
        foreach ($lists as $list) {
            $map[$list['merchantId']] = $list;
        }
        return ResultWrapper::success($map);
    }

    /**
     * Doc: (des="")
     * User: XMing
     * Date: 2021/1/22
     * Time: 6:31 下午
     * @param int $id
     * @return ResultWrapper
     */
    public function getShopById(int $id): ResultWrapper
    {
        $result = $this->objDShop->get($id);
        if ($result === false){
            return ResultWrapper::fail($this->objDShop->error(),ErrorCode::$dberror);
        }
        return ResultWrapper::success($result);
    }

    /**
     * Doc: (des="")
     * User: XMing
     * Date: 2021/1/28
     * Time: 3:58 下午
     * @param array $selectParams
     * @return ResultWrapper
     * @throws Exception
     */
    public function getAll(array $selectParams): ResultWrapper
    {

        //获取用户的客户类型
        $selectParams['modelType'] = StatusCode::$modelType['B2C'];
        if (!empty($this->userCenterId)){
            $objMCustomer = new MCustomer($this->enterpriseId,$this->userCenterId);
            $customerResult = $objMCustomer->getCustomerInfoByUserCenterId($this->userCenterId);
            if (!$customerResult->isSuccess()){
                return ResultWrapper::fail($customerResult->getData(),$customerResult->getErrorCode());
            }
            $customer = $customerResult->getData();
            $modelType = $customer['modelType'];
            if (empty($modelType)){
                $modelType = StatusCode::$modelType['B2C'];
            }
            $selectParams['modelType'] = $modelType;
        }

        $buildSql = self::buildSqlByParams($selectParams);
        $dbResult = $this->objDShop->query($buildSql['sql']);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDShop->error(), ErrorCode::$dberror);
        }
        //按照距离进行排序
        if ( isset($selectParams['longitude']) && !empty($selectParams['longitude']) &&
            isset($selectParams['latitude']) && !empty($selectParams['latitude']) ){
            $nearResult = self::nearbyLists($dbResult,$selectParams['longitude'],$selectParams['latitude']);
            if (!$nearResult->isSuccess()){
                return ResultWrapper::fail($nearResult->getData(),$nearResult->getErrorCode());
            }
            $dbResult = $nearResult->getData();
        }
        $dbResult = self::format($dbResult);
        $count = $this->objDShop->query($buildSql['countSql']);
        $return = [
            'data'  => $dbResult,
            'total' => isset($count[0]['total']) ? $count[0]['total'] : 0
        ];
        return ResultWrapper::success($return);
    }

    /**
     * Doc: (des="")
     * User: XMing
     * Date: 2021/1/30
     * Time: 12:18 下午
     * @param array $selectParams
     * @return array
     */
    public function buildSqlByParams(array $selectParams): array
    {
        $tableName = 'qianniao_shop_1';
        $fields = ' * ';
        $countField = ' COUNT(id) as total ';

        $whereSql = '';

        if (isset($selectParams['modelType']) && !empty($selectParams['modelType'])){
            $modelType = explode(',',$selectParams['modelType']);
            $str = '';
            foreach ($modelType as $type){
                if (!empty($str)){
                    $str .= ' OR ';
                }
                $str .= ' FIND_IN_SET('.$type.',`modelType`) ';
            }
            $whereSql .= ' AND ('.$str .')';
        }
        $countSql = 'SELECT '.$countField.' FROM '.$tableName.' WHERE enterpriseId = '.$this->enterpriseId.' and deleteStatus = '.StatusCode::$standard.' AND merchantId IS NULL and enableStatus = '.StatusCode::$standard.' AND extends IS NULL '.$whereSql;

        $whereSql .= ' ORDER BY createTime DESC ';
        if (isset($selectParams['limit']) && !empty($selectParams['limit'])){
            $whereSql .= ' LIMIT '.$selectParams['offset'].','.$selectParams['limit'];
        }



        $sql = 'SELECT '.$fields.' FROM '.$tableName.' WHERE enterpriseId = '.$this->enterpriseId.' and deleteStatus = '.StatusCode::$standard.' AND merchantId IS NULL and enableStatus = '.StatusCode::$standard.' AND extends IS NULL '.$whereSql;

        Logger::logs(E_USER_ERROR,'sql',__CLASS__,__LINE__,$sql);
        return [
            'countSql' => $countSql,
            'sql' => $sql
        ];
    }

    /**
     * 获取商铺绑定仓库
     */
    public function getShopBindWarehouse($shopId)
    {
        $dbResult = $this->objDShop->get(['id' => $shopId]);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDShop->error(), ErrorCode::$dberror);
        }
        $shop = $dbResult;
        if(empty($shop)){
            return ResultWrapper::fail('查询商铺失败', ErrorCode::$paramError);
        }
        $warehouseId = [];
        $warehouseData = [];
        if(!empty($shop['warehouseId'])){
            $warehouseIds = explode(',',$shop['warehouseId']);
            $objMWarehouse = new MWarehouse($this->enterpriseId);
            $modelResult = $objMWarehouse->selectWarehouse(['id' => $warehouseIds, 'deleteStatus' => StatusCode::$standard]);
            if(!$modelResult->isSuccess()){
                return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
            }
            $warehouse = $modelResult->getData();
            unset($modelResult);
            $warehouseId = [];
            $warehouseData = [];
            foreach($warehouse as $value){
                $warehouseId[] = $value['id'];
                $warehouseData[$value['id']] = $value;
            }
        }

        $return['shopId'] = $shopId;
        $return['warehouseId'] = $warehouseId;
        $return['warehouseData'] = $warehouseData;
        return ResultWrapper::success($return);
    }

    /**
     * 获取店铺绑定的仓库id
     */
     public function getWarehouseIdsByShopId($shopId)
     {
         $warehouseIds = [];

         $dbResult = $this->objDShop->get(['id' => $shopId]);
         if($dbResult === false){
             return ResultWrapper::fail($this->objDShop->error(), ErrorCode::$dberror);
         }
         if(empty($dbResult)){
             return ResultWrapper::success($warehouseIds);
         }

         if(!empty($dbResult['warehouseId'])){
             $warehouseIds = explode(',',$dbResult['warehouseId']);
         }

         return ResultWrapper::success($warehouseIds);
     }

    /**
     * 获取商铺信息
     */
    public function getShopData($where)
    {
        $dbResult = $this->objDShop->select($where);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDShop->error(), ErrorCode::$dberror);
        }
        return ResultWrapper::success($dbResult);
    }

    /**
     * 修改商铺
     * @param $update
     * @param $where
     * @return ResultWrapper
     */
    public function updateShopData($update, $where)
    {
        $dbResult = $this->objDShop->update($update, $where);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDShop->error(), ErrorCode::$dberror);
        }
        return ResultWrapper::success($dbResult);
    }
    /**
     * 多个店铺Id查询店铺名称
     * @param $departmentIds
     * @return ResultWrapper
     */

    public function getShopNameByIds(array $ids)
    {
        //查询所有 id 店铺名称
        $where = [
            'id' => array_values($ids),
            'deleteStatus' => StatusCode::$standard,
        ];
        $fields = 'id,name';
        $shopData = $this->objDShop->select($where, $fields);

        if($shopData === false){
            return ResultWrapper::fail($this->objDShop->error(), ErrorCode::$dberror);
        }
        return $shopData;
    }

//    根据实体企业id和token获取商铺id
    public function getShopid($enterpriseId,$token)
    {
        //查询所有 id 店铺名称
        $where = [
            'enterpriseId' =>$enterpriseId,
            'token' =>$token,
        ];
        $fields = 'id,name';
        $shopData = $this->objDShop->select($where, $fields);

        if($shopData === false){
            return ResultWrapper::fail($this->objDShop->error(), ErrorCode::$dberror);
        }
        return $shopData;
    }
}