<?php

declare(strict_types=1);

namespace app\control\controller\account;

use app\BaseController;
use app\common\model\Base;
use app\Request;
use app\common\model\account\Department as DepartmentModel;
use app\common\model\core\Excel;
use think\facade\App;
use think\response\Json;

/**
 * Class Department
 * @package app\control\controller\account
 */
class Department extends BaseController
{
    /**
     * @param Request $request
     * @return Json
     *
     * @api {post} /account/department/search 部门列表
     * @apiGroup AccountDepartment
     * @apiName sort1
     * @apiVersion 1.0.0
     *
     * @apiDescription 部门列表
     *
     * @apiParam {number} current  页码
     * @apiParam {number} pageSize  页数
     * @apiParam {string} [title]  部门名称
     * @apiParam {string} [grandpa]  传递多少返回多少（相当于下一级的爷爷）
     * @apiParam {number} [pid]  上级ID
     * @apiParam {number} tree  0 - 普通列表  1 - 树状列表
     *
     * @apiSuccess {Number} code    状态码，0：请求成功
     * @apiSuccess {String} message   提示信息
     * @apiSuccess {Object} dataSet    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {"errCode":0,"errMsg":"","dataSet":[],"total":0}
     *
     * @apiErrorExample {json} Error-Response:
     * {"errCode":5001,"errMsg":"接口异常"}
     */
    public function search(Request $request)
    {
        $input = $request->post();
        $pageIndex = empty($input['current']) ? 0 : intval($input['current']);
        $pageSize = empty($input['pageSize']) ? 10 : intval($input['pageSize']);
        $total = 0;
        $filters = [];
        $grandpa = 0;
        if (!empty($input['title'])) {
            $filters['title'] = $input['title'];
        }
        if (!empty($input['tree'])) {
            $filters['tree'] = $input['tree'];
        } else {
            $filters['pid'] = empty($input['pid']) ? 0 : $input['pid'];
        }
        $dataSet = DepartmentModel::search($filters, $pageIndex, $pageSize, $total);
        if (!empty($filters['pid'])) {
            $departmentInfo = DepartmentModel::fetch(intval($filters['pid']));
            if (!empty($departmentInfo)) {
                $grandpa = $departmentInfo['pid'];
            }
        }
        return payload(['dataSet' => $dataSet, 'total' => $total, 'grandpa' => $grandpa]);
    }

    /**
     * @param Request $request
     * @return Json
     *
     * @api {post} /account/department/modify 修改职务
     * @apiGroup AccountDepartment
     * @apiName sort2
     * @apiVersion 1.0.0
     *
     * @apiDescription 修改职务
     *
     * @apiParam {number} id  id
     * @apiParam {string} title  部门名称
     *
     * @apiSuccess {Number} code    状态码，0：请求成功
     * @apiSuccess {String} message   提示信息
     * @apiSuccess {Object} dataSet    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {"errCode":0,"errMsg":"","dataSet":[],"total":0}
     *
     * @apiErrorExample {json} Error-Response:
     * {"errCode":5001,"errMsg":"接口异常"}
     */
    public function modify(Request $request)
    {
        $input = $request->post();
        if (empty($input['id']) || empty($input['title'])) {
            return payload(error(-10, '缺少参数'));
        }
        DepartmentModel::update(intval($input['id']), ['title' => $input['title']]);
        return payload();
    }

    /**
     * @param Request $request
     * @return Json
     *
     * @api {post} /account/department/add 添加部门
     * @apiGroup AccountDepartment
     * @apiName sort3
     * @apiVersion 1.0.0
     *
     * @apiDescription 添加部门
     *
     * @apiParam {number} pid  父级Id  没有填写0
     * @apiParam {string} title  部门名称
     *
     * @apiSuccess {Number} code    状态码，0：请求成功
     * @apiSuccess {String} message   提示信息
     * @apiSuccess {Object} dataSet    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {"errCode":0,"errMsg":"","dataSet":[],"total":0}
     *
     * @apiErrorExample {json} Error-Response:
     * {"errCode":5001,"errMsg":"接口异常"}
     */
    public function add(Request $request)
    {
        $input = $request->post();
        $input['pid'] = empty($input['pid']) ? 0 : $input['pid'];
        if (empty($input['title'])) {
            return payload(error(-10, '缺少参数'));
        }
        if ($input['pid'] != 0) {
            $existsParent = DepartmentModel::fetch(intval($input['pid']));
            if (empty($existsParent)) {
                return payload(error(-20, '父级部门不存在'));
            }
        }
        $newRow = [
            'pid' => $input['pid'],
            'title' => $input['title']
        ];
        $existsDepartment = DepartmentModel::fetch($newRow);
        if (!empty($existsDepartment) && ($existsDepartment['title'] === $newRow['title'])) {
            return payload(error(-21, '部门已存在'));
        }
        if ($newRow['pid'] == 0) {
            $newRow['first'] = 0;
        } else {
            $newRow['first'] = ($existsParent['first'] == 0) ? $existsParent['id'] : $existsParent['first'];
        }
        $result = DepartmentModel::add($newRow);
        if (is_error($result)) {
            return payload($result);
        }
        return payload();
    }

    /**
     * @param Request $request
     * @return Json
     *
     * @api {post} /account/department/batchAdd 批量添加部门
     * @apiGroup AccountDepartment
     * @apiName sort4
     * @apiVersion 1.0.0
     *
     * @apiDescription 批量添加部门
     *
     * @apiParam {number} pid  父级Id  没有填写0
     * @apiParam {object} title  部门名称
     *
     * @apiSuccess {Number} code    状态码，0：请求成功
     * @apiSuccess {String} message   提示信息
     * @apiSuccess {Object} dataSet    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {"errCode":0,"errMsg":"","dataSet":[],"total":0}
     *
     * @apiErrorExample {json} Error-Response:
     * {"errCode":5001,"errMsg":"接口异常"}
     */
    public function batchAdd(Request $request)
    {
        $input = $request->post();
        $input['pid'] = empty($input['pid']) ? 0 : $input['pid'];
        if (empty($input['title'])) {
            return payload(error(-10, '缺少参数'));
        }
        if ($input['pid'] > 0) {
            $existsParent = DepartmentModel::fetch(intval($input['pid']));
            if (empty($existsParent)) {
                return payload(error(-20, '父级部门不存在'));
            }
        }
        foreach ($input['title'] as $v) {
            if (!empty($v)) {
                $newRow = [
                    'pid' => $input['pid'],
                    'title' => $v
                ];
                DepartmentModel::add($newRow);
            }
        }
        return payload();
    }

    /**
     * @param Request $request
     * @return Json
     *
     * @api {post} /account/department/import 导入部门
     * @apiGroup AccountDepartment
     * @apiName sort5
     * @apiVersion 1.0.0
     *
     * @apiDescription 导入部门 <br/>
     * excel导入文件示例： <a href="http://172.16.1.11:888/docs/departmentImport.xls">http://localhost:888/docs/departmentImport.xls</a>
     * @link http://172.16.1.11:888/docs/departmentImport.xls
     *
     * @apiParam {file} department  excel文件
     *
     * @apiSuccess {Number} code    状态码，0：请求成功
     * @apiSuccess {String} message   提示信息
     * @apiSuccess {Object} dataSet    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {"errCode":0,"errMsg":"","dataSet":[],"total":0}
     *
     * @apiErrorExample {json} Error-Response:
     * {"errCode":5001,"errMsg":"接口异常"}
     */
    public function import(Request $request)
    {
        $input = $request->post();
        if (empty($input['src'])) {
            return payload(error(-10, '缺少参数src'));
        }
        $departments = Excel::read(
            App::getRootPath() . 'public/' . $input['src'],
            [['field' => 'title', 'column' => 'A'], ['field' => 'pidTitle', 'column' => 'B']]
        );
        if (is_error($departments) || is_error($departments)) {
            return payload(error(-11, '导入文件错误'));
        }
        $line = 1;
        $error = [];
        foreach ($departments as $department) {
            $line++;
            if (empty($department['title'])) {
                $error[] = ['line' => $line, 'msg' => '部门名称为空'];
                continue;
            }
            $info = DepartmentModel::fetch(['title' => (string)$department['title']]);
            if (!empty($info)) {
                $error[] = ['line' => $line, 'msg' => '部门已存在'];
            }
            $newRow = [
                'title' => (string)$department['title'],
                'pid' => 0
            ];
            if (!empty($department['pidTitle'])) {
                $info = DepartmentModel::fetch(['title' => (string)$department['pidTitle']]);
                if (empty($info)) {
                    $error[] = ['line' => $line, 'msg' => '上级部门不存在'];
                    continue;
                }
                $newRow['pid'] = $info['id'];
            }
            $result = DepartmentModel::add($newRow);
            if (!$result) {
                $error[] = ['line' => $line, 'msg' => '添加部门失败'];
            }
        }
        if (!empty($error)) {
            return payload(['dataSet' => ['error' => $error]]);
        }
        return payload();
    }

    /**
     * @param Request $request
     * @return Json
     *
     * @api {post} /account/department/delete 删除部门
     * @apiGroup AccountDepartment
     * @apiName sort6
     * @apiVersion 1.0.0
     *
     * @apiDescription 删除部门
     *
     * @apiParam {number} [id]  id
     * @apiParam {number} [ids]  id集合
     *
     * @apiSuccess {Number} code    状态码，0：请求成功
     * @apiSuccess {String} message   提示信息
     * @apiSuccess {Object} dataSet    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {"errCode":0,"errMsg":"","dataSet":[],"total":0}
     *
     * @apiErrorExample {json} Error-Response:
     * {"errCode":5001,"errMsg":"接口异常"}
     */
    public function delete(Request $request)
    {
        $input = $request->post();
        if (empty($input['id']) && empty($input['ids'])) {
            return payload(error(-10, '缺少参数'));
        }
        if (!empty($input['id'])) {
            $departments = DepartmentModel::search(['pid' => $input['id']]);
            if (!empty($departments)) {
                return payload(error(-20, '请先删除下级部门'));
            }
        } else {
            foreach ($input['ids'] as $v) {
                $departments = DepartmentModel::search(['pid' => $v]);
                if (!empty($departments)) {
                    $department = DepartmentModel::fetch(intval($v));
                    return payload(error(-20, "请先删除（{$department['title']}）下级部门"));
                }
            }
        }
        DepartmentModel::remove($input);
        return payload();
    }

    /**
     * @api {get} /account/department/export 导出部门列表
     * @apiGroup AccountDepartment
     * @apiName sort7
     * @apiVersion 1.0.0
     *
     * @apiDescription 导出部门列表 导出为EXCEL文件
     *
     * @apiSuccess {Number} code    状态码，0：请求成功
     * @apiSuccess {String} message   提示信息
     * @apiSuccess {Object} dataSet    返回数据
     *
     * @apiSuccessExample {json} Success-Response:
     * {"errCode":0,"errMsg":"","dataSet":[],"total":0}
     *
     * @apiErrorExample {json} Error-Response:
     * {"errCode":5001,"errMsg":"接口异常"}
     *
     */
    public function export()
    {
        $dataSet = DepartmentModel::search([], 0);
        $newSet = Base::headelId('id', $dataSet);
        $headers = ['', '序号', '部门名称', '上级部门'];
        $excelSet = [];
        foreach ($newSet as $v) {
            $excelSet[] = [
                '' => '',
                'id' => $v['id'],
                'title' => $v['title'],
                'pTitle' => empty($newSet[$v['pid']]['title']) ? '' : $newSet[$v['pid']]['title'],
            ];
        }
        Excel::write('部门列表', $headers, $excelSet);
        exit;
    }
}