<?php

namespace app\admin\service\sys_manage;

use app\model\SysDept;
use support\Db;
use support\Request;

class DeptService
{
    /**
     * @Desc 部门列表
     * @Author Gorden
     * @Date 2024/2/21 10:28
     *
     * @param $page
     * @param $limit
     * @param $keywords
     * @return \support\Response
     */
    public static function deptList($page, $limit, $keywords)
    {
        $list = SysDept::select('*')
            ->when($keywords != '', function ($query) use ($keywords) {
                $query->where('dept_name', 'like', '%' . $keywords . '%');
            })
            ->orderBy('dept_addtimes', 'DESC')
            ->forPage($page, $limit)
            ->get()
            ->toArray();
        $count = SysDept::when($keywords != '', function ($query) use ($keywords) {
            $query->where('dept_name', 'like', '%' . $keywords . '%');
        })->count();

        return json_success('', compact('list', 'page', 'limit', 'count'));
    }

    public static function selectList(Request $request)
    {

        $category = $request->get('dept_category', '医护科室');

        $depts = SysDept::where('dept_category', $category)
            ->select('dept_id', 'dept_name')
            ->get()
            ->toArray();

        return json_success('', $depts);
    }

    /**
     * @Desc 部门详情
     * @Author Gorden
     * @Date 2024/2/21 10:35
     *
     * @param $id
     * @return \support\Response
     */
    public static function deptInfo($id)
    {
        $dept = SysDept::find($id);
        if (!$dept) {
            return json_fail('部门不存在');
        }

        $dept = $dept->toArray();
        return json_success('', $dept);
    }

    /**
     * @Desc 创建部门
     * @Author Gorden
     * @Date 2024/2/21 9:22
     *
     * @param $params
     * @return \support\Response
     */
    public static function insertDept($params)
    {
        Db::beginTransaction();
        try {
            $data = [
                'dept_super_id' => $params['dept_super_id'],
                'dept_status' => $params['dept_status'],
                'dept_category' => $params['dept_category'],
                'dept_code' => $params['dept_code'],
                'dept_city' => $params['dept_city'],
                'dept_name' => $params['dept_name'],
                'dept_telephone' => $params['dept_telephone'],
                'dept_position' => $params['dept_position'] ?? '',
                'dept_address' => $params['dept_address'] ?? '',
                'dept_remark' => $params['dept_remark'] ?? '',
                'dept_extend_json' => !empty($params['dept_extend_json']) ? $params['dept_extend_json'] : '{}',
                'dept_addtimes' => time()
            ];

            $deptId = SysDept::insertGetId($data);
            if (!$deptId) {
                throw new \Exception('创建部门失败');
            }
            // 获取上级部门path
            $deptSuperPath = '/0/';
            if ($params['dept_super_id'] != 0) {
                $deptSuperPath = SysDept::where('dept_id', $params['dept_super_id'])->value('dept_super_path');
            }
            // 更新部门path
            $path = $deptSuperPath . $deptId . '/';
            if (!SysDept::where('dept_id', $deptId)->update(['dept_super_path' => $path])) {
                throw new \Exception('创建部门失败');
            }
            // 事务提交
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return json_fail('创建部门失败');
        }

        return json_success('部门创建成功');
    }

    /**
     * @Desc 修改部门
     * @Author Gorden
     * @Date 2024/2/21 10:15
     *
     * @param $id
     * @param $params
     * @return \support\Response
     */
    public static function updateDept($id, $params)
    {
        $dept = SysDept::where('dept_id', $id)->first();
        if (!$dept) {
            return json_fail('部门不存在');
        }
        // 上级部门是否变动
        if ($dept->dept_super_id != $params['dept_super_id']) {
            $deptSuperPath = SysDept::where('dept_id', $params['dept_super_id'])->value('dept_super_path');
        }
        Db::beginTransaction();
        try {
            $data = [
                'dept_status' => $params['dept_status'],
                'dept_category' => $params['dept_category'],
                'dept_code' => $params['dept_code'],
                'dept_city' => $params['dept_city'],
                'dept_name' => $params['dept_name'],
                'dept_telephone' => $params['dept_telephone'],
                'dept_position' => $params['dept_position'] ?? '',
                'dept_address' => $params['dept_address'] ?? '',
                'dept_remark' => $params['dept_remark'] ?? '',
                'dept_extend_json' => !empty($params['dept_extend_json']) ? $params['dept_extend_json'] : '{}',
            ];
            // 上级变动，更新
            if (isset($deptSuperPath)) {
                $data['dept_super_id'] = $params['dept_super_id'];
                $data['dept_super_path'] = $deptSuperPath . $id . '/';
            }
            // 修改失败，异常
            if (!SysDept::where('dept_id', $id)->update($data)) {
                throw new \Exception('修改部门失败');
            }

            if ($dept->dept_super_id != $params['dept_super_id']) {
                $subs = SysDept::getAllSubDept($dept->dept_super_path);
                if ($subs) {
                    foreach ($subs as $sub) {
                        SysDept::where('dept_id', $sub['dept_id'])->update(['dept_super_path' => str_replace($dept->dept_super_path, $data['dept_super_path'], $sub['dept_super_path'])]);
                    }
                }
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollBack();
            return json_fail('修改部门失败');
        }

        return json_success('修改部门成功');
    }

    /**
     * @Desc 修改部门状态
     * @Author Gorden
     * @Date 2024/2/21 10:41
     *
     * @param $id
     * @param $status
     * @return \support\Response
     */
    public static function updateStatus($id, $status)
    {
        try {
            if (!SysDept::where('dept_id', $id)->update(['dept_status' => $status])) {
                throw new \Exception('部门状态修改失败');
            }
        } catch (\Exception $e) {
            return json_fail('部门状态修改失败');
        }

        return json_success('部门状态修改成功');
    }

    /**
     * @Desc 删除部门
     * @Author Gorden
     * @Date 2024/2/21 10:48
     *
     * @param $id
     * @return \support\Response
     */
    public static function delDept($id)
    {
        try {
            if (!SysDept::where('dept_id', $id)->delete()) {
                throw new \Exception('删除部门失败');
            }
        } catch (\Exception $e) {
            return json_fail('删除部门失败');
        }

        return json_success('删除部门成功');
    }

    /**
     * @Desc 检查部门是否存在
     * @Author Gorden
     * @Date 2024/2/21 13:37
     *
     * @param $deptId
     * @return bool
     */
    public static function checkDeptExist($deptId)
    {
        return SysDept::where('dept_id', $deptId)->exists();
    }

    public static function getPremisesList()
    {
        $premises = SysDept::where('dept_category','营业场所')->pluck('dept_name','dept_id')->toArray();
        $arr = [];

        foreach($premises as $key => $value){
            $arr[] = [
                'key'=>$key,
                'label' =>$value
            ];
        }

        return $arr;
    }
}