<?php
/**
 * 部门管理Controller
 * Created by PhpStorm.
 * User: 小威
 * Date: 2019/10/31
 * Time: 17:00
 */

namespace JinDouYun\Controller\Department;

use JinDouYun\Dao\Department\DDepartment;
use Mall\Framework\Core\ErrorCode;
use Mall\Framework\Core\StatusCode;

use JinDouYun\Controller\BaseController;

use JinDouYun\Model\Department\MDepartment;

class Department extends BaseController
{
    private $objMDepartment;

    public function __construct($isCheckAcl = true, $isMustLogin = true)
    {
        parent::__construct($isCheckAcl, $isMustLogin);
        $this->objMDepartment = new MDepartment($this->onlineEnterpriseId);
    }

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

        $returnData = [
            "departmentName" => isset($params['departmentName']) ? $params['departmentName'] : '', //varchar(255) NOT NULL COMMENT '部门名称',
        ];

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

        //选填项
        $returnData['pid'] = isset($params['pid']) ? $params['pid'] : 0;
        $returnData['order'] = isset($params['order']) ? $params['order'] : 0;
        $returnData['desc'] = isset($params['desc']) ? $params['desc'] : '';
        $returnData['extend']['departmentPidPath'] = isset($params['departmentPidPath']) ? $params['departmentPidPath'] : '';
        $returnData['extend'] = json_encode($returnData['extend']);
        $returnData['updateTime'] = time();

        return $returnData;
    }

    /**
     * 部门添加
     */
    public function addDepartment()
    {
        $addDepartmentData = $this->commonFieldFilter();

        $addDepartmentData['shopId'] = $this->shopId;
        $result = $this->objMDepartment->addDepartment($addDepartmentData);
        if ($result->isSuccess()) {
            parent::sendOutput($result->getData());
        } else {
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }
    }

    /**
     * 部门删除
     */
    public function deleteDepartment()
    {
        $id = $this->request->param('request_id');
        if(empty($id)){
            $this->sendOutput('参数为空', ErrorCode::$paramError);
        }
        $params['id'] = $id;
        $result = $this->objMDepartment->deleteDepartment($params);
        if ($result->isSuccess()) {
            parent::sendOutput($result->getData());
        } else {
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }
    }

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

        $result = $this->objMDepartment->updateDepartment($params, $id);
        if ($result->isSuccess()) {
            parent::sendOutput($result->getData());
        } else {
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }
    }

    /**
     * 部门列表
     */
    public function getAllDepartment()
    {
        $params = $this->request->getRawJson();

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

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

        $result = $this->objMDepartment->getAllDepartment($selectParams);

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

    /**
     * 部门详情
     */
    public function getDepartmentInfo()
    {
        $params['id'] = $this->request->param('request_id');
        if (empty($params['id'])) {
            $this->sendOutput('参数为空', ErrorCode::$paramError);
        }
        //自增id

        $result = $this->objMDepartment->getDepartmentInfo($params);
        if ($result->isSuccess()) {
            parent::sendOutput($result->getData());
        } else {
            parent::sendOutput($result->getData(), $result->getErrorCode());
        }
    }


    public function department()
    {
        $data = $this->get_downline();
        foreach ($data as $item)
        {
            if ($item['parent_id'] == 1){
                $department = $this->objMDepartment->getDepartmentInfo(['dept_id' => $item['dept_id']])->getData();
                if ($department){
                    $this->objMDepartment->updateDepartment([
                        'shopId' => $this->shopId,
                        'pid' => 0,
                        'departmentName' => $item['name'],
                        'dept_id' => $item['dept_id'],
                        'updateTime' => time(),
                    ], $department['id']);
                }else{
                    $this->objMDepartment->addDepartment([
                        'shopId' => $this->shopId,
                        'pid' => 0,
                        'departmentName' => $item['name'],
                        'dept_id' => $item['dept_id'],
                        'updateTime' => time(),
                    ]);
                }
            }
        }

        foreach ($data as $item)
        {
            if ($item['parent_id'] > 1){
                $department = $this->objMDepartment->getDepartmentInfo(['dept_id' => $item['dept_id']])->getData();
                $pid = $this->objMDepartment->getDepartmentInfo(['dept_id' => $item['parent_id']])->getData();
                if ($department){
                    $this->objMDepartment->updateDepartment([
                        'shopId' => $this->shopId,
                        'pid' => $pid['id'],
                        'departmentName' => $item['name'],
                        'dept_id' => $item['dept_id'],
                        'updateTime' => time(),
                    ], $department['id']);
                }else{
                    $this->objMDepartment->addDepartment([
                        'shopId' => $this->shopId,
                        'pid' => $pid['id'],
                        'departmentName' => $item['name'],
                        'dept_id' => $item['dept_id'],
                        'updateTime' => time(),
                    ]);
                }
            }
        }

        parent::sendOutput('同步成功');
    }


    public function get_downline($dept_id= 1){

        $url = 'https://oapi.dingtalk.com/topapi/v2/department/listsub';
        $data = $this->curl_get($url.'?access_token='.$this->voucher().'&dept_id='.$dept_id);
        $data = json_decode($data)->result;// 部门

        $arr=array();
        foreach ($data as $key => $v) {
            if($v->parent_id == $dept_id){  //pid为0的是顶级分类
                $arr[]=[
                    'auto_add_user' => $v->auto_add_user,
                    'create_dept_group' => $v->create_dept_group,
                    'dept_id' => $v->dept_id,
                    'name' => $v->name,
                    'parent_id' => $v->parent_id,
                ];

                $arr = array_merge($arr,$this->get_downline($v->dept_id));
            }
        }
        return $arr;

    }

}