<?php

/**
 * 分销商等级Model
 * Created by PhpStorm.
 * User: haoren
 * Date: 2020/07/22
 * Time: 15:00
 */

namespace JinDouYun\Model\Commission;

use Exception;
use Mall\Framework\Core\ErrorCode;
use Mall\Framework\Core\StatusCode;
use Mall\Framework\Core\ResultWrapper;

use JinDouYun\Cache\CommissionCache;

use JinDouYun\Dao\Commission\DCommissionGrade;
use JinDouYun\Dao\Commission\DCommissionGradeCondition;

use JinDouYun\Model\MBaseModel;

class MCommissionGrade extends MBaseModel
{
    private $objDCommissionGrade;
    private $objDCommissionGradeCondition;
    private $objCommissionCache;
    private $userCenterId;
    private $enterpriseId;

    public function __construct($enterpriseId, $userCenterId)
    {
        $this->enterpriseId = $enterpriseId;
        $this->userCenterId = $userCenterId;
        $this->objCommissionCache = new CommissionCache($enterpriseId, $userCenterId);
        $this->objDCommissionGrade = new DCommissionGrade();
        $this->objDCommissionGradeCondition = new DCommissionGradeCondition();
        self::insertGrade();
    }

    public function insertGrade()
    {
        $dbResult = $this->objDCommissionGrade->get(['enterpriseId' => $this->enterpriseId,'grade' => 0]);
        if($dbResult === false){
            return false;
        }
        if(empty($dbResult)){
            //添加分销商默认等级
            $insertGrade = [
                'name' => '默认等级',
                'grade' => 0,
                'oneRate' => 30.00,
                'twoRate' => 20.00,
                'threeRate' => 10.00,
                'upgradeMode' => 5,
            ];
            $modelResult = self::addGrade($insertGrade);
            if(!$modelResult->isSuccess()){
                return false;
            }
            unset($modelResult);
        }
        return true;
    }

    /**
     * 新增等级
     * @param $params
     * @return ResultWrapper
     */
    public function addGrade($params)
    {
        $dbResult = $this->objDCommissionGrade->select(['enterpriseId' => $this->enterpriseId, 'grade' => $params['grade'], 'deleteStatus' => StatusCode::$standard]);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDCommissionGrade->error(), ErrorCode::$dberror);
        }
        if(!empty($dbResult)){
            return ResultWrapper::fail('等级已存在', ErrorCode::$contentNotExists);
        }
        unset($dbResult);
        $params['enterpriseId'] = $this->enterpriseId;
        $params['deleteStatus'] = StatusCode::$standard;
        $params['createTime'] = time();
        $params['updateTime'] = time();
        $params['enableStatus'] = StatusCode::$standard;

        isset($params['upgradeCondition']) && $params['upgradeCondition'] = json_encode($params['upgradeCondition']);

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

    /**
     * 修改等级
     * @param $update
     * @param $where
     * @return ResultWrapper
     */
    public function updateGrade($update, $where = [])
    {
        $where['enterpriseId'] = $this->enterpriseId;
        unset($update['enterpriseId']);

        if(isset($update['grade'])){
            $dbResult = $this->objDCommissionGrade->select(['enterpriseId' => $this->enterpriseId, 'grade' => $update['grade'], 'deleteStatus' => StatusCode::$standard]);
            if($dbResult === false){
                return ResultWrapper::fail($this->objDCommissionGrade->error(), ErrorCode::$dberror);
            }
            if(!empty($dbResult)){
                $grade = array_shift($dbResult);
                if($grade['id'] != $where['id']){
                    return ResultWrapper::fail('等级已存在', ErrorCode::$contentNotExists);
                }
            }
        }
        

        isset($update['upgradeCondition']) && $update['upgradeCondition'] = json_encode($update['upgradeCondition']);

        $dbResult = $this->objDCommissionGrade->update($update, $where);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDCommissionGrade->error(), ErrorCode::$dberror);
        }
        //删除缓存
        $this->objCommissionCache->delBusinessmanGrade(true);

        return ResultWrapper::success($dbResult);
    }

    /**
     * 等级列表
     * @param $params
     * @return ResultWrapper
     */
    public function getAllGrade($params = [])
    {
        $params['deleteStatus'] = StatusCode::$standard;
        $params['enterpriseId'] = $this->enterpriseId;

        $dbResult = $this->objDCommissionGrade->select($params,'*','grade ASC');
        if($dbResult === false){
            return ResultWrapper::fail($this->objDCommissionGrade->error(), ErrorCode::$dberror);
        }
        if(empty($dbResult)){
            return ResultWrapper::success($dbResult);
        }

        $dbResult = self::formatUpgradeCondition($dbResult);
        return ResultWrapper::success($dbResult);
    }

    /**
     * 等级详情
     * @param $params
     * @return ResultWrapper
     */
    public function getInfoGrade($params)
    {
        $params['deleteStatus'] = StatusCode::$standard;
        $params['enterpriseId'] = $this->enterpriseId;

        $dbResult = $this->objDCommissionGrade->get($params);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDCommissionGrade->error(), ErrorCode::$dberror);
        }
        if(empty($dbResult)){
            return ResultWrapper::success($dbResult);
        }
        $dbResult = self::formatUpgradeCondition($dbResult);
        return ResultWrapper::success($dbResult);

    }

    /**
     * 格式化升级条件
     * @param $params
     * @return array|mixed
     */
    public function formatUpgradeCondition($params)
    {
        if(empty($params)) return [];
        $modelResult = self::getAllGradeCondition(['type' => StatusCode::$delete]);
        if(!$modelResult->isSuccess()){
            return [];
        }
        $infoData = $modelResult->getData();
        unset($modelResult);
        $info = [];
        foreach($infoData as $value){
            $info[$value['id']]['key'] = $value['key'];
            $info[$value['id']]['title'] = $value['title'];
        }

        $format = $params;
        if(isset($params['id'])){
            $format = [$params];
        }
        foreach($format as &$value){
            if(isset($value['upgradeCondition']) && !empty($value['upgradeCondition'])){
                $value['upgradeCondition'] = json_decode($value['upgradeCondition'], true);
                if(!empty($value['upgradeCondition'])){
                    foreach($value['upgradeCondition'] as $key => $v){
                        if(isset($info[$key])){
                            $value['upgradeConditionInfo'][] = [
                                'id' => $key,
                                'key' => $info[$key]['key'],
                                'name' => $info[$key]['title'],
                                'value' => $v,
                            ];
                        }
                    }
                }
            }
        }

        if(isset($params['id'])){
            $format = array_shift($format);
        }
        return $format;
    }

    /**
     * 升级条件
     * @param array $where
     * @return ResultWrapper
     */
    public function getAllGradeCondition($where = [])
    {
        $dbResult = $this->objDCommissionGradeCondition->select($where);
        if($dbResult === false){
            return ResultWrapper::fail($this->objDCommissionGradeCondition->error(), ErrorCode::$dberror);
        }
        return ResultWrapper::success($dbResult);
    }




}