<?php
/**
 * 用户中心企业管理Controller
 * Created by PhpStorm.
 * User: 小威
 * Date: 2019/11/04
 * Time: 16:50
 */

namespace JinDouYun\Controller\Enterprise;

use JinDouYun\Model\GoodsManage\MUnits;
use Mall\Framework\Core\ErrorCode;
use Mall\Framework\Core\ResultWrapper;
use Mall\Framework\Core\StatusCode;

use JinDouYun\Cache\EnterpriseCache;

use JinDouYun\Controller\BaseController;

use JinDouYun\Model\Enterprise\MEnterprise;
use JinDouYun\Model\Department\MStaff;
use JinDouYun\Model\Department\MRoleAcl;
use JinDouYun\Model\UserCenter\MUserCenterRegister;

class UserEnterprise extends BaseController
{
    private $objMEnterprise;
    private $objEnterpriseCache;
    private $objMUserCenterRegister;


    public function __construct($isCheckAcl = false, $isMustLogin = true, $checkToken = false)
    {
        parent::__construct($isCheckAcl, $isMustLogin, $checkToken);
        $this->objMEnterprise = new MEnterprise();
        $this->objEnterpriseCache = new EnterpriseCache();

    }

    /**
     * 获取参数
     *
     * @return array
     */
    public function commonFieldFilter()
    {
        $params = $this->request->getRawJson();
        if (empty($params)) {
            $this->sendOutput('参数为空', ErrorCode::$paramError);
        }

        $EnterpriseData = [
            "userCenterId" => $this->onlineUserId, //客户id
            "enterpriseName" => isset($params['enterpriseName']) ? $params['enterpriseName'] : '', //企业名称
            "contact" => isset($params['contact']) ? $params['contact'] : '', //联系人
            "mobile" => isset($params['mobile']) ? $params['mobile'] : '', //联系电话
            "provinceCode" => isset($params['provinceCode']) ? $params['provinceCode'] : '', //省份编码
            "cityCode" => isset($params['cityCode']) ? $params['cityCode'] : '', //城市编码
            "districtCode" => isset($params['districtCode']) ? $params['districtCode'] : '', //区县编码
            "address" => isset($params['address']) ? $params['address'] : '', //详细地址
            //"categoryId" => isset($params['categoryId']) ? $params['categoryId'] : '', //企业类别
            //"startTime" => isset($params['startTime']) ? $params['startTime'] : '', //营业时间
            //"endTime" => isset($params['endTime']) ? $params['endTime'] : '', //停业时间
            "logo" => isset($params['logo']) ? $params['logo'] : '', //企业logo
            "scope" => isset($params['scope']) ? $params['scope'] : '', //企业经营类型4单店铺 5多店铺
        ];

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

        //选填项
        $EnterpriseData['brandName'] = isset($params['brandName']) ? $params['brandName'] : '';
        $EnterpriseData['updateTime'] = time();

        return $EnterpriseData;
    }

    /**
     * 企业添加
     * @throws \Exception
     */
    public function addEnterprise()
    {
        $EnterpriseData = $this->commonFieldFilter();
        $result = $this->objMEnterprise->addEnterprise($EnterpriseData, $this->authorization);
        $content=$result->getData();

        if ($result->isSuccess()) {
            $returnData = $result->getData();
            //存储企业token和企业id
            $this->objEnterpriseCache->enterpriseIdAndTokenCache($returnData['enterpriseId'], $returnData['token']);
            //关联userId和企业id,权限校验需要
            $this->objEnterpriseCache->cacheUserCenterIdAndEnterpriseId($this->onlineUserId, StatusCode::$roleType['admin'],$returnData['enterpriseId']);
            //创建默认门店
            $res = $this->objMEnterprise->autoCreateData($content["userCenterId"], $returnData['enterpriseId']);
            //自动创建单位
            new MUnits($content["userCenterId"],$returnData['enterpriseId']);
            parent::sendOutput($result->getData());
        } else {
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }
    }

    /**
     * 修改密码
     */
    public function updateUserCenterData()
    {
        $params = $this->request->getRawJson();
        if(empty($params)){
            parent::sendOutput('参数为空', ErrorCode::$paramError);
        }
        $updateData = [
            'oldPassword' => isset($params['oldPassword']) ? $params['oldPassword'] : '',
            'newPassword' => isset($params['newPassword']) ? $params['newPassword'] : '',
            'rePassword' => isset($params['rePassword']) ? $params['rePassword'] : ''
        ];
        foreach($updateData as $key => $value){
            if(empty($value)){
                parent::sendOutput($key.'参数错误', ErrorCode::$paramError);
            }
        }
        if($updateData['newPassword'] !== $updateData['rePassword']){
            parent::sendOutput('两次输入密码不一致', ErrorCode::$paramError);
        }
        $where = ['id' => $this->onlineUserId];
        $modelResult = $this->objMEnterprise->updateUserCenterData($updateData, $where);
        if(!$modelResult->isSuccess()){
            parent::sendOutput($modelResult->getData(), $modelResult->getErrorCode());
        }
        parent::sendOutput($modelResult->getData());
    }


    /**
     * 企业列表
     * @throws \Exception
     */
    public function getAllEnterprise()
    {
        $result = $this->objMEnterprise->getAllEnterprise($this->onlineUserId);
        if ($result->isSuccess()) {
            parent::sendOutput($result->getData());
        } else {
            parent::sendOutput($result->getData(), ErrorCode::$dberror);
        }
    }

    /**
     * 获取当前登录用户的角色对应的操作权限
     */
    public function getAclList() {

        parent::__construct(false, true, true);

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

        $aclData = ['isAdministrator'=>false, 'custom'=>[], 'dataField'=>[] ];

        //判断是否可以进入企业
//        switch ($roleType){
//            case StatusCode::$roleType['admin']:
//                //企业创建者进入
//                $aclData['isAdministrator'] = true;
//                break;
//            case StatusCode::$roleType['staff']:
//                //员工进入
//                $objMStaff = new MStaff($this->onlineEnterpriseId,$this->onlineUserId);
//                $modelResult = $objMStaff->getStaffData(['userCenterId' => $this->onlineUserId]);
//                if(!$modelResult->isSuccess()){
//                    return ResultWrapper::fail($modelResult->getData(), $modelResult->getErrorCode());
//                }
//                $staff = $modelResult->getData();
//                if($staff['shopId'] == 0){
//                    $aclData['isAdministrator'] = true;
//                }
//                break;
//            case StatusCode::$roleType['merchant']:
//                //商户进入
//                $aclData['isAdministrator'] = true;
//                break;
//            default:
//                $this->sendOutput('参数错误', ErrorCode::$paramError);
//                break;
//        }
        if($roleType == StatusCode::$roleType['admin']) {
            $aclData = [
                'isAdministrator' => true,
                'custom' => [],
                'dataField'=>[],
            ];
        }

        if($roleType == StatusCode::$roleType['staff']) {
            //获取当前用户对应的角色的权限
            $objMRoleAcl = new MRoleAcl($this->onlineEnterpriseId);
            $aclResult = $objMRoleAcl->getRoleAclByUserCenterId($this->onlineUserId);
            parent::sendOutput($aclResult->getData());
        }
        parent::sendOutput($aclData);
    }


    /**
     * 自动创建
     * @throws \Exception
     */
    public function autoCreateData()
    {
        $data = $this->request->getRawJson();
        if(empty($data) || !isset($data['enterpriseId']) || !isset($data['userCenterId'])){
            echo '参数错误';
            return;
        }
        $result = $this->objMEnterprise->autoCreateData($data['userCenterId'], $data['enterpriseId']);
        if(!$result->isSuccess()){
            echo $result->getData();
            return;
        }

        //自动创建单位
        new MUnits($data['userCenterId'],$data['enterpriseId']);
        echo '执行成功^^';
    }

}