<?php
/**
 * 职工管理Controller
 * Created by PhpStorm.
 * User: 小威
 * Date: 2019/10/31
 * Time: 18:00
 */

namespace JinDouYun\Controller\Department;

use JinDouYun\Dao\Department\DStaffReflect;
use JinDouYun\Model\Department\MDepartment;
use JinDouYun\Model\System\MBasicSetup;
use Mall\Framework\Core\ErrorCode;
use Mall\Framework\Core\StatusCode;

use JinDouYun\Cache\EnterpriseCache;
use JinDouYun\Cache\RoleAclCache;

use JinDouYun\Controller\BaseController;

use JinDouYun\Model\Department\MStaff;

class Staff extends BaseController
{
    private $objMStaff;
    private $objRoleAclCache;
    private $objEnterpriseCache;
    private $objMDepartment;
    private $basic;

    public function __construct($isCheckAcl = true, $isMustLogin = true)
    {
        parent::__construct($isCheckAcl, $isMustLogin);
        $this->objMStaff = new MStaff($this->onlineEnterpriseId, $this->onlineUserId);
        $this->objRoleAclCache = new RoleAclCache();
        $this->objEnterpriseCache = new EnterpriseCache();
        $this->objMDepartment = new MDepartment($this->onlineEnterpriseId);
        $this->basic = new MBasicSetup($this->onlineEnterpriseId);
    }

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

        $returnData = [
            "departmentId" => isset($params['departmentId']) ? $params['departmentId'] : 0, //int(10) DEFAULT NULL COMMENT '部门id',
            "staffName" => isset($params['staffName']) ? $params['staffName'] : '', //varchar(30) DEFAULT NULL COMMENT '员工姓名',
            "roleId" => isset($params['roleId']) ? $params['roleId'] : 0, //varchar(255) DEFAULT NULL COMMENT '角色id',
            "mobile" => isset($params['mobile']) ? $params['mobile'] : '', //varchar(11) DEFAULT NULL COMMENT '手机号',
            "dataField" => isset($params['dataField']) ? json_encode($params['dataField']) : '',
        ];

        //必填项
        foreach ($returnData as $key => $value) {
            if (empty($value) && $value !== 0) {
                $this->sendOutput($key . '参数错误', ErrorCode::$paramError);
            }
        }
        //选填项
        $returnData['extend'] = [];
        isset($params['departmentPidPath']) && $returnData['extend']['departmentPidPath'] = $params['departmentPidPath'];
        isset($params['rolePidPath']) && $returnData['extend']['rolePidPath'] = $params['rolePidPath'];
        $returnData['email'] = isset($params['email']) ? $params['email'] : '';
        $returnData['sex'] = isset($params['sex']) ? $params['sex'] : '';
        $returnData['age'] = isset($params['age']) ? $params['age'] : '';
        $returnData['education'] = isset($params['education']) ? $params['education'] : '';
        $returnData['info'] = isset($params['info']) ? $params['info'] : '';
        $returnData['stock_right'] = isset($params['stock_right']) ? $params['stock_right'] : '';
        $returnData['evaluate'] = isset($params['evaluate']) ? $params['evaluate'] : '';
        $returnData['avatar'] = isset($params['avatar']) ? $params['avatar'] : '';
        $returnData['spread_uid'] = isset($params['spread_uid']) ? $params['spread_uid'] : '';
        $returnData['is_clock'] = isset($params['is_clock']) ? $params['is_clock'] : 0;
        $returnData['is_technician'] = isset($params['is_technician']) ? $params['is_technician'] : 0;


        $returnData['extend'] = json_encode($returnData['extend']);
        $returnData['updateTime'] = time();
        if (isset($params['isSetRule']) && !empty($params['isSetRule'])){
            $returnData['isSetRule'] = $params['isSetRule'];
        }
        if (isset($params['rule']) && !empty($params['rule'])){
            $returnData['rule'] = json_encode($params['rule']);
        }
        return $returnData;
    }

    /**
     * 职工添加
     */
    public function addStaff()
    {
        $addStaffData = $this->commonFieldFilter();
        $addStaffData['shopId'] = $this->shopId;

        // 拉去用户钉钉userID
        $data = $this->basic->getBasicSetup($this->onlineEnterpriseId)->getData();
        if (isset($data['basicData']['appKey']) || isset($data['basicData']['appSecret'])){
            $url = 'https://oapi.dingtalk.com/topapi/v2/user/getbymobile?access_token='.$this->voucher();
            $json = [
                'mobile' => $addStaffData['mobile'],
            ];
            $data = $this->post_json($url, json_encode($json));
            $data  = json_decode($data);
            if ($data->errcode > 0){
                $userid = '';
            }else{
                $userid = $data->result->userid;
            }
            $addStaffData['userId'] = $userid;
        }

        $result = $this->objMStaff->addStaff($addStaffData);
        if ($result->isSuccess()) {
            $resultData = $result->getData();
            $userCenterId = $resultData['userCenterId'];
            //缓存职工的userCenterId和拥有的数据域
            $this->objRoleAclCache->cacheStaffUidAndDataField(
                $this->onlineEnterpriseId,
                $userCenterId,
                json_decode($addStaffData['dataField'], true)
            );

            //缓存职工和角色组id的关系
            $extend = json_decode($addStaffData['extend'], true);
            if(isset($extend['rolePidPath'])) {
                $rolePidPath = explode(',', $extend['rolePidPath']);
                $this->objRoleAclCache->cacheStaffAndRole(
                    $this->onlineEnterpriseId,
                    $userCenterId,
                    $rolePidPath[0]
                );
            }

            //缓存职工的userCenterId和当前企业的关系
            $this->objEnterpriseCache->cacheUserCenterIdAndEnterpriseId(
                $userCenterId,
                StatusCode::$roleType['staff'],
                $this->onlineEnterpriseId
            );
            parent::sendOutput($resultData['title']);
        } else {
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }
    }

    /**
     * 职工删除
     */
    public function deleteStaff()
    {
        $params = $this->request->getRawJson();
        if (empty($params)) {
            $this->sendOutput('参数为空', ErrorCode::$paramError);
        }
        $deleteData = [
            'id' => isset($params['id']) ? $params['id'] : [],
        ];
        foreach($deleteData as $key => $value){
            if(empty($value)){
                parent::sendOutput($key.'参数错误', ErrorCode::$paramError);
            }
        }
        $result = $this->objMStaff->deleteStaff($deleteData);
        if ($result->isSuccess()) {
            $staffResult = $this->objMStaff->getStaffInfo($deleteData);
            $staffInfo = $staffResult->getData();
            //删除职工和角色id的关系
            $this->objRoleAclCache->deleteStaffRelationRole($this->onlineEnterpriseId, $staffInfo['userCenterId']);

            //删除redis里的企业id和员工id的关联
            $this->objEnterpriseCache->deleteEnterprise($staffInfo['userCenterId'], $this->onlineEnterpriseId);
            parent::sendOutput($result->getData());
        } else {
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }
    }

    /**
     * 职工修改
     */
    public function updateStaff()
    {
        $id['id'] = $this->request->param('request_id');
        if (empty($id['id'])) {
            $this->sendOutput('参数为空', ErrorCode::$paramError);
        }
        $params = $this->commonFieldFilter();

        $result = $this->objMStaff->updateStaff($params, $id);
        if ($result->isSuccess()) {
            $staffResult = $this->objMStaff->getStaffInfo($id);
            $staffInfo = $staffResult->getData();

            //缓存职工的userCenterId和拥有的数据域
           $test = $this->objRoleAclCache->cacheStaffUidAndDataField(
                $this->onlineEnterpriseId,
                $staffInfo['userCenterId'],
                $staffInfo['dataField']
            );
            //缓存职工和角色id的关系
            if(isset($staffInfo['extend']) && isset($staffInfo['extend']['rolePidPath'])) {
                $rolePidPath = explode(',',$staffInfo['extend']['rolePidPath']);
                $this->objRoleAclCache->cacheStaffAndRole(
                    $this->onlineEnterpriseId,
                    $staffInfo['userCenterId'],
                    $rolePidPath[0]
                );
            }
            parent::sendOutput($result->getData());
        } else {
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }
    }

    /**
     * 职工列表
     */
    public function getAllStaff()
    {
        $params = $this->request->getRawJson();

        $pageParams = pageToOffset($params['page'] ?: 1, $params['pageSize'] ?: 10);
        $selectParams['limit'] = $pageParams['limit'];
        $selectParams['offset'] = $pageParams['offset'];

        //部门id
        if(isset($params['departmentId']) && !empty($params['departmentId'])){
            $selectParams['departmentId'] = $params['departmentId'];
        }

        //角色id
        if(isset($params['roleId']) && !empty($params['roleId'])){
            $selectParams['roleId'] = $params['roleId'];
        }

        //员工姓名
        if(isset($params['keyword']) && !empty($params['keyword'])){
            $selectParams['staffName'] = $params['keyword'];
        }

        if (isset($params['signId']) && !empty($params['signId'])){
            $selectParams['signId'] = $params['signId'];
        }

        if (isset($params['shopId']) && !empty($params['shopId'])){
            $selectParams['shopId'] = $params['shopId'];
        }else{
            if($this->shopId){
                $selectParams['shopId'] = $this->shopId;
            }
        }

        $result = $this->objMStaff->getAllStaff($selectParams);
        if ($result->isSuccess()) {
            $returnData = $result->getData();
            $pageData = [
                'pageIndex' => $params['page'],
                'pageSize' => $params['pageSize'],
                'pageTotal' => $returnData['total'],
            ];
            parent::sendOutput($returnData['data'], 0, $pageData);
        } else {
            parent::sendOutput($result->getData(), ErrorCode::$dberror);
        }
    }

    /**
     * 职工详情
     */
    public function getStaffInfo()
    {
        $where = [];
        $id = $this->request->param('request_id');
        if(!empty($id)){
            $where['id'] = $id;
        }
        $params = $this->request->getRawJson();
        if(empty($id) && isset($params['userCenterId']) && !empty($params['userCenterId'])){
            $where['userCenterId'] = $params['userCenterId'];
        }

        $result = $this->objMStaff->getStaffInfo($where);
        if ($result->isSuccess()) {
            parent::sendOutput($result->getData());
        } else {
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }
    }

    /**
     * 根据userCenterId 获取职工详情
     * @throws \Exception
     */
    public function getStaffDataByUserCenterId()
    {
        $modelResult = $this->objMStaff->getStaffDataByUserCenterId($this->onlineUserId);
        if($modelResult->isSuccess()){
            parent::sendOutput($modelResult->getData(), $modelResult->getErrorCode());
        }
        parent::sendOutput($modelResult->getData());
    }

    /**
     * 获取商铺下的员工
     */
    public function getStaffByShopId() {
        $params = $this->request->getRawJson();
        if( empty($params) ){
            $this->sendOutput('参数为空', ErrorCode::$paramError );
        }
        $pageParams = pageToOffset($params['page']?:1, $params['pageSize']?:10);
        $selectParams['limit'] = $pageParams['limit'];
        $selectParams['offset'] = $pageParams['offset'];

        if(isset($params['shopId']) && !empty($params['shopId'])){
            $selectParams['shopId'] = $params['shopId'];
        }else{
            parent::sendOutput('shopId参数错误', ErrorCode::$paramError);
        }
        $result = $this->objMStaff->getStaffByShopId($selectParams);
        if(!$result->isSuccess()){
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }
        $returnData = $result->getData();
        $pageData = [
            'pageIndex' => $params['page'],
            'pageSize' => $params['pageSize'],
            'pageTotal' => $returnData['total'],
        ];
        parent::sendOutput($returnData['data'], 0, $pageData);

    }

    /**
     * 提成流水
     */
    public function getAllStaffRewardDesc()
    {
        $params = $this->request->getRawJson();
        if (empty($params)) {
            parent::sendOutput('参数为空', ErrorCode::$paramError);
        }

        $pageParams = pageToOffset($params['page'] ?: 1, $params['pageSize'] ?: 10);
        $selectParams['limit'] = $pageParams['limit'];
        $selectParams['offset'] = $pageParams['offset'];

        if(isset($params['staffId']) && !empty($params['staffId'])){
            $selectParams['staffId'] = $params['staffId'];
        }

        if(isset($params['source']) && !empty($params['source'])){
            $selectParams['source'] = $params['source'];
        }

        if (isset($params['type']) && !empty($params['type'])){
            $selectParams['type'] = $params['type'];
        }

        if(isset($params['star']) && !empty($params['star']) && isset($params['end']) && !empty($params['end'])){
            $selectParams['createTime'] = [
                'star' => $params['star'],
                'end' => $params['end']
            ];
        }

        if(!empty($this->shopId)){
            $selectParams['shopId'] = $this->shopId;
        }

        $result = $this->objMStaff->getAllStaffRewardDesc($selectParams);
        if ($result->isSuccess()) {
            $returnData = $result->getData();
            $pageData = [
                'pageIndex' => $params['page'],
                'pageSize' => $params['pageSize'],
                'pageTotal' => $returnData['total'],
                'zc' => $returnData['zc']['amount'] ?? 0,
                'sr' => $returnData['sr']['amount'] ?? 0,
            ];
            parent::sendOutput($returnData['data'], 0, $pageData);
        } else {
            parent::sendOutput($result->getData(), ErrorCode::$dberror);
        }
    }

    /**
     * 员工业绩提成修改
     */
    public function updateStaffTargetAndReward()
    {
        $id = $this->request->param('request_id');
        if (empty($id)) {
            $this->sendOutput('参数为空', ErrorCode::$paramError);
        }

        $params = $this->request->getRawJson();

        $data = [];
        (isset($params['target']) && !empty($params['target'])) && $data['target'] = $params['target'];
        (isset($params['rewardGo']) && !empty($params['rewardGo'])) && $data['rewardGo'] = $params['rewardGo'];

        $modelResult = $this->objMStaff->updateStaffData($data, ['id' => $id]);
        if($modelResult->isSuccess()){
            parent::sendOutput($modelResult->getData());
        } else {
            parent::sendOutput($modelResult->getData(), $modelResult->getErrorCode());
        }
    }


    /**
     * 员工提现列表
     * @return void
     */
    public function  getWithdrawal()
    {
        $params = $this->request->params();

        $pageParams = pageToOffset($params['page'] ?: 1, $params['pageSize'] ?: 10);
        $limit = $pageParams['limit'];
        $offset = $pageParams['offset'];

        if (isset($params['auditStatus']) and !empty($params['auditStatus'])){
            $selectParams['auditStatus'] = $params['auditStatus'];
        }

        if (isset($params['staffId']) and !empty($params['staffId'])){
            $selectParams['staffId'] = $params['staffId'];
        }

        if (isset($params['reflectStatus']) and !empty($params['reflectStatus'])){
            $selectParams['reflectStatus'] = $params['reflectStatus'];
        }

        if (isset($params['end']) and !empty($params['end']) && isset($params['start']) and !empty($params['start'])){
            $selectParams[] = ['createTime' , '>=', strtotime($params['start'])];
            $selectParams[] = ['createTime' , '<=', strtotime($params['end'])];
        }

        $db = new DStaffReflect('default');
        $list = $db->select($selectParams, '*', 'id DESC', $limit, $offset);
        foreach ($list as &$item)
        {
            $item['reflectInfo'] = json_decode($item['reflectInfo']);
        }

        $count = $db->count($selectParams);
        $pageData = [
            'pageIndex' => $params['page'],
            'pageSize' => $params['pageSize'],
            'pageTotal' => $count,
        ];
        parent::sendOutput($list, 0, $pageData);
    }


    /**
     * 审核打款接口
     * @return void
     */
    public function examineWithdrawal()
    {
        $params = $this->request->params();
        if (empty($params['id'])) $this->sendOutput('id参数为空', ErrorCode::$paramError);
        $db = new DStaffReflect('default');
        $data = $db->get(['id' => $params['id']]);
        if (isset($params['auditStatus']) and !empty($params['auditStatus'])){
            if ($data['auditStatus'] == 2) $this->sendOutput('已审核', ErrorCode::$paramError);
            $res = $db->update(['auditStatus' => $params['auditStatus']]);
        }
        if (isset($params['reflectStatus']) and !empty($params['reflectStatus'])){
            if ($data['reflectStatus'] != 4) $this->sendOutput('当前申请已审核完成', ErrorCode::$paramError);
            $res = $db->update(['reflectStatus' => $params['reflectStatus']]);
        }
        if ($res){
            $this->sendOutput('成功');
        }
        $this->sendOutput('失败', ErrorCode::$paramError);
    }

}
