<?php
/**
 * @Copyright (c) 2019  XIGU Inc. All rights reserved.
 * @Link https://www.vlcms.com
 * @License江苏溪谷网络科技有限公司版权所有
 */

namespace app\common\logic;

use app\common\validate\Department as vDepartment;
use app\common\model\Department as mDepartment;
use app\common\model\Manager as mManager;

class Department extends Base
{


    /**
     * @部门列表
     *
     * @author: zsl
     * @since: 2019/5/15 10:28
     */
    public function lists($param)
    {
        $result = ['code' => 200, 'msg' => '请求成功', 'data' => []];
        $where = [];
        if (!empty($param['id'])) {
            $where[] = ['id', '=', $param['id']];
        }
        $where[] = ['status', 'in', '0,1'];
        $field = "id,pid,name,status,create_time";
        $mDepartment = new mDepartment();
        $departmentList = $mDepartment -> field($field) -> where($where) -> select();
        if (!empty($departmentList)) {
            $result['data'] = $departmentList;
        }
        return $result;
    }

    public function treeSelect($param)
    {
        $result = ['code' => 200, 'msg' => '', 'data' => []];
        $return = empty($param['return']) ? 'tree' : $param['return'];
        $where = [];
        $where [] = ['status', '=', '1'];
        $mDepartment = new mDepartment();
        $departmentList = $mDepartment -> field('id,pid,name') -> where($where) -> select();
        if (!empty($departmentList)) {
            $result['data'] = $return == 'tree' ? array_to_tree($departmentList -> toArray()) : $departmentList -> toArray();
        }
        return $result;
    }

    public function create($param)
    {
        $result = ['code' => 200, 'msg' => '添加成功', 'data' => []];
        $vDepartment = new vDepartment();
        if (!$vDepartment -> scene('create') -> check($param)) {
            $result['code'] = 8001;
            $result['msg'] = $vDepartment -> getError();
            return $result;
        }
        try {
            //添加部门
            $mDepartment = new mDepartment();
            $mDepartment -> pid = empty($param['pid']) ? 0 : $param['pid'];
            $mDepartment -> name = $param['name'];
            $mDepartment -> status = $param['status'];
            $mDepartment -> save();
        } catch (\Exception $e) {
            $result['code'] = 8002;
            $result['msg'] = $this -> errorCode(8002);
        }
        return $result;
    }

    public function detail($param)
    {
        $detail = [];
        if (!empty($param['id'])) {
            $mDepartment = new mDepartment();
            $where = [];
            $where[] = ['status', 'in', '0,1'];
            $where[] = ['id', '=', $param['id']];
            $detail = $mDepartment -> where($where) -> find();
            if (!empty($detail)) {
                $detail['pname'] = $mDepartment -> where('id', '=', $detail['pid']) -> value('name');
            }
        }
        return $detail;
    }

    public function update($param)
    {
        $result = ['code' => 200, 'msg' => '保存成功', 'data' => []];
        $mDepartment = $this -> detail(['id' => $param['id']]);
        if (empty($mDepartment)) {
            $result['code'] = 8004;
            $result['msg'] = $this -> errorCode(8004);
            return $result;
        }
        $vDepartment = new vDepartment();
        if (!$vDepartment -> scene('update') -> check($param)) {
            $result['code'] = 8001;
            $result['msg'] = $vDepartment -> getError();
            return $result;
        }
        $subDepartmentIds = $this -> getSubDepartmentIds($mDepartment -> id);
        if (in_array($param['pid'], $subDepartmentIds)) {
            $result['code'] = 8005;
            $result['msg'] = $this -> errorCode(8005);
            return $result;
        }
        try {
            $mDepartment -> pid = empty($param['pid']) ? 0 : $param['pid'];
            $mDepartment -> name = $param['name'];
            $mDepartment -> status = $param['status'];
            $mDepartment -> save();
        } catch (\Exception $e) {
            $result['code'] = 8002;
            $result['msg'] = $this -> errorCode(8002);
        }
        return $result;
    }


    public function enable($param)
    {
        $result = ['code' => 200, 'msg' => '部门启用成功', 'data' => []];
        $where = [];
        if (!empty($param['id'])) {
            $where[] = ['id', '=', $param['id']];
        }
        if (!$this -> reStatus($where, 1)) {
            $result['code'] = 8006;
            $result['msg'] = $this -> errorCode(8006);
        }
        return $result;
    }


    public function disable($param)
    {
        $result = ['code' => 200, 'msg' => '部门禁用成功', 'data' => []];
        $where = [];
        if (!empty($param['id'])) {
            $where[] = ['id', '=', $param['id']];
        }
        if (!$this -> reStatus($where, 0)) {
            $result['code'] = 8007;
            $result['msg'] = $this -> errorCode(8007);
        }
        return $result;
    }

    public function getDepartmentSub($department_id)
    {
        $sub_ids = [];
        $departments = mDepartment :: field('id') -> where('pid', '=', $department_id) -> select();
        if (!$departments -> isEmpty()) {
            $departments = $departments -> toArray();
            $sub_ids = array_column($departments, 'id');
            foreach ($departments as $department) {
                $sub_ids = array_merge($sub_ids, $this -> getDepartmentSub($department['id']));
            }
        }
        return $sub_ids;
    }


    private function reStatus($where, $status)
    {
        try {
            $mManager = new mDepartment();
            $mManager -> where($where) -> update(['status' => $status]);
            return true;
        } catch (\Exception $e) {
            return false;
        }
    }


    /**
     * @获取所有
     *
     * @author: zsl
     * @since: 2021/3/9 16:30
     */
    private function getSubDepartmentIds($department_id)
    {
        //获取所有部门数据
        $mDepartment = new mDepartment();
        $field = "id,pid,name";
        $where = [];
        $where[] = ['status', 'in', [0, 1]];
        $departmentLists = $mDepartment -> field($field) -> where($where) -> select();
        $ids = get_sub_manager_ids($departmentLists, $department_id);
        return array_merge($ids, [$department_id]);
    }


    private function errorCode($code)
    {
        $errorCode = [
                8001 => '',
                8002 => '部门添加失败',
                8003 => '部门修改失败',
                8004 => '部门不存在，或已被删除',
                8005 => '不可选择自身或下级部门为父级部门',
                8006 => '部门启用失败',
                8007 => '部门禁用失败',
                8008 => '部门删除成功',
                8009 => '当前管理员没有公会',
                8010 => '请选择父级部门',
                8011 => '军团昵称修改失败',
                8012 => '超级管理员不可操作',
                8013 => '缺少公会标识',
        ];
        return empty($errorCode[$code]) ? '系统繁忙,请稍候再试' : $errorCode[$code];
    }


}
