<?php
/**
 * 商品基础数据分类模型
 * Created by PhpStorm.
 * User: XiaoMing
 * Date: 2019/10/30
 * Time: 17:15
 */

namespace JinDouYun\Model\GoodsCategory;

use JinDouYun\Controller\Common\Logger;
use JinDouYun\Model\Customer\MCustomer;
use Mall\Framework\Core\ErrorCode;
use Mall\Framework\Core\ResultWrapper;
use Mall\Framework\Core\StatusCode;

use JinDouYun\Cache\GoodsBasicRelevant;
use JinDouYun\Cache\OverviewCache;
use JinDouYun\Dao\GoodsCategory\DGoodsCategory;
use JinDouYun\Model\GoodsManage\MGoodsBasic;

class MGoodsCategory
{
    private $objDGoodsCategory;

    private $onlineUserId;

    private $onlineEnterpriseId;

    private $objGoodsBasicRelevantCache;
    private $objOverviewCache;

    /**
     * MGoodsCategory constructor.
     * @param $onlineUserId
     * @param $onlineEnterpriseId
     * @throws \Exception
     */
    public function __construct($onlineUserId, $onlineEnterpriseId)
    {
        $this->onlineUserId = $onlineUserId;
        $this->onlineEnterpriseId = $onlineEnterpriseId;
        $this->objDGoodsCategory = new  DGoodsCategory('default');
        $this->objOverviewCache = new  OverviewCache();
        $this->objGoodsBasicRelevantCache = new GoodsBasicRelevant($this->onlineEnterpriseId);
        $this->objDGoodsCategory->setTable($this->objDGoodsCategory->get_Table() . '_' . $onlineEnterpriseId);
    }

    /**
     * 添加分类
     * @param $params
     * @return ResultWrapper
     * @throws \Exception
     */
    public function addCategory($params)
    {
        //验证分类名称唯一
         /*$cacheResult = $this->objGoodsBasicRelevantCache->getCategoryIdByName($params['title']);
        if ($cacheResult) {
            return ResultWrapper::fail('分类名称已存在', ErrorCode::$paramError);
        }*/
        $dbResult = $this->objDGoodsCategory->insert($params);

        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDGoodsCategory->error(), ErrorCode::$dberror);
        }
        $this->objGoodsBasicRelevantCache->cacheCategoryIdRelationName($params['title'], $dbResult);
        return ResultWrapper::success($dbResult);
    }

    /**
     * 获取指定id分类的详细信息
     * @param $id
     * @return ResultWrapper
     * @throws \Exception
     */
    public function getCategoryInfoById($id)
    {
        $dbResult = $this->objDGoodsCategory->get_by('id', $id);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDGoodsCategory->error(), ErrorCode::$dberror);
        }
        $pid = $dbResult['pid'];
        $sql = 'select title as ptitle from qianniao_goods_category_'.$this->onlineEnterpriseId.' WHERE id = '.$pid;
        $ptitle = $this->objDGoodsCategory->query($sql);
        if ($ptitle === false) {
            return ResultWrapper::fail($this->objDGoodsCategory->error(), ErrorCode::$dberror);
        }
        foreach ($ptitle as $key => $vlue){
            $dbResult['ptitle'] = array_shift($vlue);
        }
        return ResultWrapper::success($dbResult);
    }

    /**
     * 编辑分类信息
     * @param $params
     * @return ResultWrapper
     * @throws \Exception
     */
    public function editCategory($params)
    {
        if (empty($params['id'])) {
            return ResultWrapper::fail('没有指定要修改分类id', ErrorCode::$paramError);
        }

        $updateCategoryId = $params['id'];
        unset($params['id']);

        if (in_array($updateCategoryId, explode(',', $params['link']))) {
            return ResultWrapper::fail('请选择其他分类', ErrorCode::$paramError);
        }

        $dbResult = $this->objDGoodsCategory->update($params, $updateCategoryId);

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

        $this->objGoodsBasicRelevantCache->deleteCategoryKeyById($updateCategoryId);
        $this->objGoodsBasicRelevantCache->cacheCategoryIdRelationName($params['title'], $updateCategoryId);
        return ResultWrapper::success($dbResult);
    }

    /**
     * 分类的显示和隐藏
     * @param $params
     * @return ResultWrapper
     * @throws \Exception
     */
    public function updateCategoryStatus($params)
    {
        $dbResult = $this->objDGoodsCategory->update(['enableStatus' => $params['enableStatus']], $params['id']);

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

    /**
     * 获取所有基础商品分类的列表
     * @param $selectParams
     * @param $fields
     * @return ResultWrapper
     * @throws \Exception
     */
    public function getAllCategory($selectParams = [], $fields = '*')
    {
        $selectParams['deleteStatus'] = StatusCode::$standard;
        //分配屏蔽客户类型
        if(isset($selectParams['userCenterId']) && !empty($selectParams['userCenterId'])){
            //查询当前登录客户类型
            $objMCustomer = new MCustomer($this->onlineEnterpriseId, $this->onlineUserId);
            $modelResult = $objMCustomer->getCustomerData(['userCenterId' => $selectParams['userCenterId']],'type',true);
            if(!$modelResult->isSuccess()){
                return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
            }
            $customer = $modelResult->getData();
            unset($modelResult);
            if(!empty($customer) && !empty($customer['type'])){
                $selectParams['notCustomerType'] = $customer['type'];
            }
        }
        unset($selectParams['userCenterId']);

        $whereSql = '';
        foreach($selectParams as $key => $value){
            if($key == 'notCustomerType'){
                $whereSql .= (empty($whereSql) ? '' : ' and ').'( not FIND_IN_SET('.$value.','.$key.') or '.$key.' is null)';
            }else{
                $whereSql .= (empty($whereSql) ? '' : ' and ').$key.' = '.$value;
            }
        }

        //添加select条件
        $dbResult = $this->objDGoodsCategory->select($whereSql, $fields, 'sort DESC,createTime desc');
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDGoodsCategory->error(), ErrorCode::$dberror);
        }

        $return = [
            'data' => arr2tree(self::formatBasicNum($dbResult)),
        ];

        return ResultWrapper::success($return);
    }


    /**
     * 获取所有基础商品分类的列表(小程序)
     * @param $selectParams
     * @param $fields
     * @return ResultWrapper
     * @throws \Exception
     * sql select * FROM qianniao_goods_category_64 where id in (SELECT DISTINCT b.categoryPath as goodsIds from qianniao_goods_64 as g LEFT JOIN qianniao_goods_basic_64 as b on g.basicGoodsId=b.id where b.deleteStatus = 5 and b.enableStatus = 5 and g.enableStatus = 5 and g.deleteStatus = 5) and enableStatus = 5 and deleteStatus = 5 and ( not FIND_IN_SET(1,notCustomerType) or notCustomerType is null) ORDER BY sort DESC,createTime desc
     */
    public function apiGetAllCategory($selectParams = [], $fields = '*')
    {
        $selectParams['deleteStatus'] = StatusCode::$standard;
        //分配屏蔽客户类型
        if(isset($selectParams['userCenterId']) && !empty($selectParams['userCenterId'])){
            //查询当前登录客户类型
            $objMCustomer = new MCustomer($this->onlineEnterpriseId, $this->onlineUserId);
            $modelResult = $objMCustomer->getCustomerData(['userCenterId' => $selectParams['userCenterId']],'type',true);
            if(!$modelResult->isSuccess()){
                return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
            }
            $customer = $modelResult->getData();
            unset($modelResult);
            if(!empty($customer) && !empty($customer['type'])){
                $selectParams['notCustomerType'] = $customer['type'];
            }
        }
        unset($selectParams['userCenterId']);

        $whereSql = '';
        foreach($selectParams as $key => $value){
            if($key == 'notCustomerType'){
                $whereSql .= (empty($whereSql) ? '' : ' and ').'( not FIND_IN_SET('.$value.','.$key.') or '.$key.' is null)';
            }else{
                $whereSql .= (empty($whereSql) ? '' : ' and ').$key.' = '.$value;
            }
        }
        $sql = 'select id,pid,sort,createTime FROM '.$this->objDGoodsCategory->get_Table().' where id in (SELECT DISTINCT b.categoryId as goodsIds from qianniao_goods_'.$this->onlineEnterpriseId.' as g LEFT JOIN qianniao_goods_basic_'.$this->onlineEnterpriseId.' as b on g.basicGoodsId=b.id where b.deleteStatus = '.StatusCode::$standard.' and b.enableStatus = '.StatusCode::$standard.' and g.enableStatus = '.StatusCode::$standard.' and g.deleteStatus = '.StatusCode::$standard.') and '.$whereSql;
        //添加select条件
        $dbResult = $this->objDGoodsCategory->query($sql);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDGoodsCategory->error(), ErrorCode::$dberror);
        }
        if( empty($dbResult) ){
           return ResultWrapper::success(['data'=>[]]); 
        }

        $categoryIds = [];
        foreach ($dbResult as $categoryIdsKey => $categoryIdsValue){
            array_push($categoryIds,$dbResult[$categoryIdsKey]['id']);
            array_push($categoryIds,$dbResult[$categoryIdsKey]['pid']);
        }
        unset($dbResult);
        $categoryIds = implode(',',$categoryIds);
        $categoryIdsSql = 'select * from '.$this->objDGoodsCategory->get_Table().' where id in ('.$categoryIds.')'.' ORDER BY sort DESC,createTime desc';
        $dbResult = $this->objDGoodsCategory->query($categoryIdsSql);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDGoodsCategory->error(), ErrorCode::$dberror);
        }

        $return = [
            'data' => arr2tree(self::formatBasicNum($dbResult)),
        ];

        return ResultWrapper::success($return);
    }


    /**
     * 删除分类
     * @param $id
     * @return ResultWrapper
     * @throws \Exception
     */
    public function delCategory($id)
    {
        if (empty($id)) {
            return ResultWrapper::fail('参数错误', ErrorCode::$paramError);
        }

        $dbResult = $this->objDGoodsCategory->count(['pid' => $id, 'deleteStatus' => StatusCode::$standard]);
        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDGoodsCategory->error(), ErrorCode::$dberror);
        }

        if ($dbResult > 0) {
            return ResultWrapper::fail("分类下有子分类", ErrorCode::$dberror);
        }

        $dbResult = $this->objDGoodsCategory->update(['deleteStatus' => StatusCode::$delete], $id);

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

        foreach ($id as $categoryId) {
            $this->objGoodsBasicRelevantCache->deleteCategoryKeyById($categoryId);
        }

        return ResultWrapper::success($dbResult);

    }


    /**
     * 根据分类id获取分类名称
     * @param $selectParams
     * @return ResultWrapper
     * @throws \Exception
     */
    public function getCategoryTitleByIds($selectParams)
    {
        $dbResult = $this->objDGoodsCategory->select($selectParams, 'id,title','sort desc,createTime desc');
        if ($dbResult === false) {
            Logger::logs(E_USER_ERROR,'sql error',__CLASS__,__LINE__,$this->objDGoodsCategory->error());
            return ResultWrapper::fail($this->objDGoodsCategory->error(), ErrorCode::$dberror);
        }
        return ResultWrapper::success($dbResult);
    }

    /**
     * 统计分类下的商品数量
     * @param $data
     * @return mixed
     * @throws \Exception
     */
    private function formatBasicNum($data)
    {
        $objMGoodsBasic = new MGoodsBasic($this->onlineUserId, $this->onlineEnterpriseId);

        foreach ($data as $key => &$val) {
            $val['code'] = createCode(StatusCode::$code['category']['prefix'], $val['id'], StatusCode::$code['brand']['length']);
            $dbResult = $objMGoodsBasic->getBasicTotalByIds($val['id']);
            if (!$dbResult->isSuccess()) {
                return $data;
            }
            $goodsBasicData = $dbResult->getData();
            if (isset($goodsBasicData['num'])) {
                $val['goodsBasicTotal'] = $goodsBasicData['num'];
            } else {
                $val['goodsBasicTotal'] = 0;
            }
        }
        return $data;
    }


    public function todayCategoryRanking($ranking = 1, $shopId = null)
    {
        if ($ranking == 1) {
            $result = $this->objOverviewCache->getRanking($this->onlineEnterpriseId, 'categoryRanking', $shopId);
        } else {
            $result = $this->objOverviewCache->getSalesMoneyRanking($this->onlineEnterpriseId, 'categoryRanking', $shopId);
        }
        if (empty($result)) {
            return [];
        }
       
        $total = array_sum($result);
        //拼接categoryId
        $categoryIds = [];
        $i = 1;
        foreach ($result as $categoryId => $v) {
            $categoryIds[] = $categoryId;
            $i++;
            if ($i >= 8) {
                break;
            }
        }
        
        $categoryResult = self::getCategoryTitleByIds($categoryIds);
        $categoryNameData = [];
        if ($categoryResult->isSuccess()) {
            $categoryResult = $categoryResult->getData();
            foreach ($categoryResult as $categoryData) {
                $categoryNameData[$categoryData['id']] = $categoryData['title'];
            }
        }
        //拼接返回数据
        $return = [];
        $i = 1;
        foreach ($result as $categoryId => $v) {
            $rank = [];
            $rank['id'] = $i;
            $rank['categoryName'] = isset($categoryNameData[$categoryId]) ? $categoryNameData[$categoryId] : '';
            $rank['numberOrMoney'] = $v;
            $rank['percent'] = $v ? (float)bcmul(bcdiv($v, $total), 100, 2)  : 0;
            $return[] = $rank;

            $i++;
            if ($i >= 8) {
                break;
            }
        }
        return $return;
    }
}