<?php
/**
 * 商品品牌数据模型
 * Created by PhpStorm.
 * User: XiaoMing
 * Date: 2019/11/5
 * Time: 11:21
 */

namespace JinDouYun\Model\GoodsManage;

use JinDouYun\Controller\Common\Logger;
use JinDouYun\Dao\GoodsManage\DGoodsBasic;
use Mall\Framework\Core\ErrorCode;

use JinDouYun\Cache\GoodsBasicRelevant;
use JinDouYun\Model\Purchase\MSupplier;
use JinDouYun\Cache\GoodsBasicCache;
use JinDouYun\Dao\GoodsManage\DGoodsBrand;
use Mall\Framework\Core\ResultWrapper;
use Mall\Framework\Core\StatusCode;

class MGoodsBrand
{
    private $objDGoodsBrand;

    private $onlineUserId;

    private $onlineEnterpriseId;

    private $objGoodsBasicRelevantCache;


    /**
     * MGoodsBrand constructor.
     * @param $onlineUserId
     * @param $onlineEnterpriseId
     * @throws \Exception
     */
    public function __construct($onlineUserId, $onlineEnterpriseId)
    {
        $this->onlineUserId = $onlineUserId;
        $this->onlineEnterpriseId = $onlineEnterpriseId;

        $this->objDGoodsBrand = new DGoodsBrand('default');
        $this->objDGoodsBrand->setTable($this->objDGoodsBrand->get_Table() . '_' . $onlineEnterpriseId);

        $this->objGoodsBasicRelevantCache = new GoodsBasicRelevant($this->onlineEnterpriseId);
    }

    /**
     * @param $id (企业id)
     * @throws \Exception
     */
    public function goodsBrandSubTable($id)
    {
        $this->objDGoodsBrand->setTable('qianniao_goods_brand_' . $id);
    }

    /**
     * 添加品牌
     * @param $params
     * @return ResultWrapper
     * @throws \Exception
     */
    public function addBrand($params)
    {
        $this->objDGoodsBrand->beginTransaction();
        $dbResult = $this->objDGoodsBrand->insert($params);
        if ($dbResult === false) {
            $this->objDGoodsBrand->rollBack();
            return ResultWrapper::fail($this->objDGoodsBrand->error(), ErrorCode::$dberror);
        }
        $code = createCode(StatusCode::$code['brand']['prefix'], $dbResult, StatusCode::$code['brand']['length']);
        $dbResult = $this->objDGoodsBrand->update(['code'=>$code],$dbResult);
        if ($dbResult === false){
            $this->objDGoodsBrand->rollBack();
            return ResultWrapper::fail($this->objDGoodsBrand->error(), ErrorCode::$dberror);
        }

        $this->objGoodsBasicRelevantCache->cacheBrandIdRelationName($params['title'], $dbResult);
        $this->objDGoodsBrand->commit();
        return ResultWrapper::success($dbResult);

    }

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

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

        $dbResult = $this->objDGoodsBrand->update($params, $updateBrandId);

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

    /**
     * 获取指定id的品牌信息
     * @param $params
     * @return ResultWrapper
     * @throws \Exception
     */
    public function getBrandInfoById($id)
    {
        $dbResult = $this->objDGoodsBrand->get_by('id', $id);

        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDGoodsBrand->error(), ErrorCode::$dberror);
        } else {
            $formatResult = self::formatSupplier($dbResult);
            if (!empty($formatResult)) {
                $dbResult = $formatResult[0];
            }
            return ResultWrapper::success($dbResult);
        }
    }

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

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

    /**
     * 获取所有品牌列表
     * @param $selectParams
     * @return ResultWrapper
     * @throws \Exception
     */
    public function getAllBrand($selectParams)
    {
        $limit = $selectParams['limit'];
        unset($selectParams['limit']);
        $offset = $selectParams['offset'];
        unset($selectParams['offset']);

        $whereSql = ' WHERE deleteStatus = ' . StatusCode::$standard;
        if (isset($selectParams['keyword']) && !empty($selectParams['keyword'])) {
            $whereSql .= ' AND (title LIKE "%' . $selectParams['keyword'] . '%" OR code LIKE "%'.$selectParams['keyword'].'%")';
        }
        if (isset($selectParams['categoryId']) && !empty($selectParams['categoryId'])) {
            $whereSql .= ' AND id in (SELECT brandId from qianniao_goods_basic_'.$this->onlineEnterpriseId.' where FIND_IN_SET('.$selectParams['categoryId'].',categoryPath) and brandid != 0)';
        }
        $sql = 'SELECT * FROM '.$this->objDGoodsBrand->get_Table().$whereSql.' ORDER BY sort DESC LIMIT '.$offset.' , '.$limit;
        $totalSql = 'SELECT COUNT(1) as count FROM '.$this->objDGoodsBrand->get_Table().$whereSql;
//        $where = 'deleteStatus=' . StatusCode::$standard;
//        if (isset($selectParams['keyword'])) {
//            $where .= ' AND (title LIKE "%' . $selectParams['keyword'] . '%" OR code LIKE "%'.$selectParams['keyword'].'%")';
//        }

        $dbResult = $this->objDGoodsBrand->query($sql);
        $dbTotalResult = $this->objDGoodsBrand->query($totalSql);

        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDGoodsBrand->error(), ErrorCode::$dberror);
        }
        if ($dbTotalResult === false) {
            return ResultWrapper::fail($this->objDGoodsBrand->error(), ErrorCode::$dberror);
        }
//        $total = $this->objDGoodsBrand->count($where);

        $return = [
            'data'  => self::formatSupplier(self::format($dbResult)),
            'total' => $dbTotalResult[0]['count'],
        ];

        return ResultWrapper::success($return);
    }

    /**
     * 获取所有品牌列表(小程序)
     * @param $selectParams
     * @return ResultWrapper
     * @throws \Exception
     * sql     SELECT * FROM qianniao_goods_brand_64 WHERE deleteStatus = 5 AND id in (select b.brandId from qianniao_goods_basic_64 as b LEFT JOIN qianniao_goods_64 as g on b.id=g.basicGoodsId where b.enableStatus = 5 and FIND_IN_SET(1,b.categoryPath) and b.brandid != 0) ORDER BY sort DESC LIMIT 0 , 10
     */
    public function apiGetAllBrand($selectParams)
    {
        $limit = $selectParams['limit'];
        unset($selectParams['limit']);
        $offset = $selectParams['offset'];
        unset($selectParams['offset']);

        $whereSql = ' WHERE deleteStatus = ' . StatusCode::$standard;
        if (isset($selectParams['keyword']) && !empty($selectParams['keyword'])) {
            $whereSql .= ' AND (title LIKE "%' . $selectParams['keyword'] . '%" OR code LIKE "%'.$selectParams['keyword'].'%")';
        }
        if (isset($selectParams['categoryId']) && !empty($selectParams['categoryId'])) {
            $whereSql .= ' AND id in (select b.brandId from qianniao_goods_basic_'.$this->onlineEnterpriseId.' as b LEFT JOIN qianniao_goods_'.$this->onlineEnterpriseId.' as g on b.id=g.basicGoodsId where g.enableStatus = '.StatusCode::$standard.' and b.enableStatus = '.StatusCode::$standard.' and FIND_IN_SET('.$selectParams['categoryId'].',b.categoryPath) and b.brandid != 0)';
        }
        $sql = 'SELECT * FROM '.$this->objDGoodsBrand->get_Table().$whereSql.' ORDER BY sort DESC LIMIT '.$offset.' , '.$limit;
        $totalSql = 'SELECT COUNT(1) as count FROM '.$this->objDGoodsBrand->get_Table().$whereSql;
//        $where = 'deleteStatus=' . StatusCode::$standard;
//        if (isset($selectParams['keyword'])) {
//            $where .= ' AND (title LIKE "%' . $selectParams['keyword'] . '%" OR code LIKE "%'.$selectParams['keyword'].'%")';
//        }

        $dbResult = $this->objDGoodsBrand->query($sql);
        $dbTotalResult = $this->objDGoodsBrand->query($totalSql);

        if ($dbResult === false) {
            return ResultWrapper::fail($this->objDGoodsBrand->error(), ErrorCode::$dberror);
        }
        if ($dbTotalResult === false) {
            return ResultWrapper::fail($this->objDGoodsBrand->error(), ErrorCode::$dberror);
        }
//        $total = $this->objDGoodsBrand->count($where);

        $return = [
            'data'  => self::formatSupplier(self::format($dbResult)),
            'total' => $dbTotalResult[0]['count'],
        ];

        return ResultWrapper::success($return);
    }

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

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

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

        foreach ($id as $brandId) {
            $this->objGoodsBasicRelevantCache->deleteBrandKeyById($brandId);
        }

        return ResultWrapper::success($dbResult);

    }

    /**
     * 格式化数据
     * @param $data
     * @param $enterpriseId
     * @return mixed
     * @throws \Exception
     */
    public function format($data)
    {
        //$objGoodsBasicCache = new GoodsBasicCache($this->onlineEnterpriseId);
        $allBrandMap = self::getBrandBasicTotal(array_column($data,'id'));

        foreach ($data as $key => $value) {
            //$data[$key]['goodsBasicTotal'] = $objGoodsBasicCache->getBrandGoodsBasicNum($value['id']);
            $data[$key]['goodsBasicTotal'] = isset($allBrandMap[$value['id']]) ? $allBrandMap[$value['id']] : 0;
            $data[$key]['code'] = createCode(StatusCode::$code['brand']['prefix'], $value['id'], StatusCode::$code['brand']['length']);
        }
        return $data;
    }

    /**
     * Doc: (des="")
     * User: XMing
     * Date: 2020/7/24
     * Time: 11:25 上午
     * @param array $ids
     * @return array
     */
    public function getBrandBasicTotal(array $ids)
    {
        $sql = 'SELECT count(id) as num,brandId FROM qianniao_goods_basic_'.$this->onlineEnterpriseId.' WHERE deleteStatus = '.StatusCode::$standard.' GROUP BY brandId';
        $dbResult = $this->objDGoodsBrand->query($sql);
        if ($dbResult === false){
            return [];
        }
        $map = [];
        foreach ($dbResult as $row){
            $map[$row['brandId']] = $row['num'];
        }
        return $map;
    }

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

    /**
     * 格式化数据
     * @param $data
     * @return array
     * @throws \Exception
     */
    private function formatSupplier($data)
    {
        if (isset($data['id'])) {
            $dimension = $data;
            unset($data);
            $data[] = $dimension;
        }

        $allSupplierIds = [];
        foreach ($data as $key => $val) {
            if (strlen($val['supplier']) > 1) {
                foreach (explode(',', $val['supplier']) as $k => $v) {
                    $allSupplierIds[] = $v;
                }
            } else {
                $allSupplierIds[] = $val['supplier'];
            }
        }

        $allSupplierIds = array_values(array_unique($allSupplierIds));

        $objMSupplier = new MSupplier($this->onlineUserId, $this->onlineEnterpriseId);
        $dbResult = $objMSupplier->getSupplierNameByIds($allSupplierIds);

        if (!$dbResult->isSuccess()) {
            return $data;
        }

        $supplierData = $dbResult->getData();
        //创建映射关系
        foreach ($supplierData as $key => $value) {
            $allSupplierData[$value['id']] = $value;
        }

        foreach ($data as $key => $value) {
            if (strlen($value['supplier']) > 1) {
                foreach (explode(',', $value['supplier']) as $k => $v) {
                    $data[$key]['supplierTitle'][] = isset($allSupplierData[$v]['title']) ? $allSupplierData[$v]['title'] : 0;
                }
            } else {
                $data[$key]['supplierTitle'][] = isset($allSupplierData[$value['id']]['title']) ? $allSupplierData[$value['id']]['title'] : 0;
            }
        }

        return $data;
    }

    public function getBrandNameByIds($ids): ResultWrapper
    {
        if (empty($ids)){
            return ResultWrapper::success([]);
        }
        $lists = $this->objDGoodsBrand->select(['id' => array_values($ids)],'id,title');
        if ($lists === false){
            return ResultWrapper::fail($this->objDGoodsBrand->error,ErrorCode::$dberror);
        }
        $map = [];
        foreach ($lists as $list){
            $map[$list['id']] = $list['title'];
        }
        return ResultWrapper::success($map);
    }
}