<?php
/**
 * @copyright Copyright (c) 2021 勾股工作室
 * @license https://opensource.org/licenses/GPL-3.0
 * @link https://www.gougucms.com
 */

declare (strict_types = 1);

namespace app\api\controller;

use app\api\ApiController;
use app\api\middleware\Auth;
use app\user\model\DepartmentChange as DepartmentChange;
use app\user\model\PersonalQuit as PersonalQuit;
use think\exception\ValidateException;
use think\facade\Db;

class UserPersonal extends ApiController
{

    protected $middleware = [
    	Auth::class => ['except' => []]
    ];

    //调部门列表
    public function change()
    {
        $this->checkAuth();
        $param = get_params();
        $where = [];
        if (!empty($param['keyword'])) {
            $where[] = ['u.name|p.remark|a.title|b.title','like', '%' . $param['keyword'] . '%'];
        }
        $where[] = ['p.status','=', 1];
        $rows = empty($param['limit']) ? get_config('app.page_size') : $param['limit'];
        $list = DepartmentChange::where($where)
            ->field('p.*,u.name as name,ad.name as admin,a.title as adepartment,b.title as bdepartment')
            ->alias('p')
            ->join('admin u', 'p.uid = u.id', 'LEFT')
            ->join('admin ad', 'p.admin_id = ad.id', 'LEFT')
            ->join('department a', 'p.from_did = a.id', 'LEFT')
            ->join('department b', 'p.to_did = b.id', 'LEFT')                
            ->order('p.id desc')
            ->paginate($rows, false, ['query' => $param])
            ->each(function ($item, $key) {
                $item->move_time = date('Y-m-d', $item->move_time);
            });
        $this->apiSuccess('获取成功', $list);
    }

    //新增&编辑调部门
    public function change_add()
    {
        $this->checkAuth();
        $param = get_params();
        if (!empty($param['id']) && $param['id'] > 0) {
            $param['update_time'] = time();
            $param['move_time'] = isset($param['move_time']) ? strtotime($param['move_time']) : 0;
            $res = Db::name('DepartmentChange')->strict(false)->field(true)->update($param);
            add_log('edit', $param['id'], $param);
        } else {
            if (empty($param['uid'])) {
                $this->apiError("请选择调出人员");
            }
            if (empty($param['from_did'])) {
                $this->apiError("请选择调出部门");
            }
            if (empty($param['to_did'])) {
                $this->apiError("请选择调入部门");
            }
            if (empty($param['move_time'])) {
                $this->apiError("请选择调动时间");
            }
            $param['move_time'] = isset($param['move_time']) ? strtotime($param['move_time']) : 0;
            $count = Db::name('Department')->where(['leader_id' => $param['uid']])->count();
            if($count>0){
                $this->apiError("请先撤销该员工的部门负责人头衔再调部门");
            }
            $param['create_time'] = time();
            $param['admin_id'] = JWT_UID;
            $res = Db::name('DepartmentChange')->strict(false)->field(true)->insertGetId($param);
            if ($res!==false) {
                Db::name('Admin')->where('id', $param['uid'])->update(['did' => $param['to_did']]);
            }
            add_log('add', $res, $param);
        }
        $this->apiSuccess('操作成功');
    }

    //离职
    public function leave()
    {
        $param = get_params();
        $where = array();
        if (!empty($param['keyword'])) {
            $where['u.name|p.remark'] = ['like', '%' . $param['keyword'] . '%'];
        }
        $where['p.status'] = array('eq', 1);
        $rows = empty($param['limit']) ? get_config('app.page_size') : $param['limit'];
        $list = PersonalQuit::where($where)
            ->field('p.*,u.name as name,u.did,u.position_id,d.title as department,ps.title as position')
            ->alias('p')
            ->join('admin u', 'p.uid = u.id', 'LEFT')
            ->join('department d', 'u.did = d.id', 'LEFT')
            ->join('position ps', 'u.position_id = ps.id', 'LEFT')
            ->order('p.id desc')
            ->paginate($rows, false, ['query' => $param])
            ->each(function ($item, $key) {
                $item->quit_time = date('Y-m-d', $item->quit_time);
                $item->lead_admin = Db::name('admin')->where(['id' => $item->lead_admin_id])->value('name');
                $this_uids_name = Db::name('admin')->where([['id','in', $item->connect_uids]])->column('name');
                $item->connect_names = implode(',', $this_uids_name);
            });
        $this->apiSuccess('操作成功', $list);
    }

    //添加离职档案
    public function leave_add()
    {
        $this->checkAuth();
        $param = get_params();
        if (empty($param['uid'])) {
            $this->apiError("请选择离职人员");
        }
        if (empty($param['lead_admin_id'])) {
            $this->apiError("请选择部门负责人");
        }
        if (empty($param['connect_uids'])) {
            $this->apiError("请选择交接人员");
        }
        if (empty($param['quit_time'])) {
            $this->apiError("请选择离职时间");
        }
        $count = Db::name('Department')->where(['leader_id' => $param['uid']])->count();
        if($count>0){
            $this->apiError("请先撤销该员工的部门负责人头衔再添加离职档案");
        }
        $param['quit_time'] = isset($param['quit_time']) ? strtotime($param['quit_time']) : 0;
        if (!empty($param['id']) && $param['id'] > 0) {
            $param['update_time'] = time();
            $res = Db::name('PersonalQuit')->strict(false)->field(true)->update($param);
            add_log('edit', $param['id'], $param);
        } else {
            $param['create_time'] = time();
            $param['admin_id'] = JWT_UID;
            $res = Db::name('PersonalQuit')->strict(false)->field(true)->insertGetId($param);
            add_log('add', $res, $param);
        }
        if ($res!==false) {
            Db::name('Admin')->where('id', $param['uid'])->update(['status' => 2]);
        }
        $this->apiSuccess("操作成功");
    }

    //删除离职档案
    public function leave_delete()
    {
        $this->checkAuth();
        $id = get_params("id");
        if (empty($id)) {
            $this->apiError("请选择离职人员");
        }
        $data['status'] = '-1';
        $data['id'] = $id;
        $data['update_time'] = time();
        if (Db::name('PersonalQuit')->update($data) !== false) {
            $uid = Db::name('PersonalQuit')->where('id', $id)->value('uid');
            Db::name('Admin')->where('id', $uid)->update(['status' => 1]);
            add_log('delete', $id);
            $this->apiSuccess("删除成功");
        } else {
            $this->apiError("删除失败");
        }
    }
}
