<?php

namespace app\admin\service\marketing;

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

class TeamService
{
    const DEPT_CATEGORY = '营销团队';

    /**
     * @Desc 营销团队列表
     * @Author Gorden
     * @Date 2024/2/21 10:28
     *
     * @param $page
     * @param $limit
     * @param $keywords
     * @return \support\Response
     */
    public static function deptList(Request $request)
    {
        $page = $request->get('page', 1);
        $pageSize = $request->get('pageSize', 10);
        $keywords = format_string($request->get('keywords', ''));

        $rows = SysDept::with([
            'premises' => function ($query) {
                $query->select('dept_id', 'dept_name');
            }
        ])->select('dept_id', 'dept_name', 'dept_super_id','dept_addtimes')
            ->where('dept_category', self::DEPT_CATEGORY)
            ->when($keywords != '', function ($query) use ($keywords) {
                $query->where('dept_name', 'like', '%' . $keywords . '%');
            })
            ->orderBy('dept_addtimes', 'DESC')
            ->forPage($page, $pageSize)
            ->get()
            ->toArray();
        $total = SysDept::where('dept_category', self::DEPT_CATEGORY)
            ->when($keywords != '', function ($query) use ($keywords) {
                $query->where('dept_name', 'like', '%' . $keywords . '%');
            })->count();

        return json_success('', compact('rows', 'page', 'pageSize', 'total'));
    }

    /**
     * @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)
    {
        try {
            $data = [
                'dept_category' => self::DEPT_CATEGORY,
                'dept_name' => $params['dept_name'],
                'dept_super_id' => $params['dept_super_id'],    // 这里指营销场所ID
                'dept_status' => $params['dept_status'] ?? 'ACTIVED',
                'dept_addtimes' => time()
            ];

            $deptId = SysDept::insertGetId($data);
            if (!$deptId) {
                throw new BusinessException('创建营销团队失败');
            }
        } catch (BusinessException $e) {
            return json_fail($e->getMessage());
        } catch (\Exception $e) {
            dump($e->getMessage());
            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('营销团队不存在');
        }

        try {
            $data = [
                'dept_name' => $params['dept_name'],
                'dept_super_id' => $params['dept_super_id'],    // 这里指营销场所ID
            ];
            // 修改失败，异常
            SysDept::where('dept_id', $id)->update($data);

        } catch (BusinessException $e) {
            return json_fail($e->getMessage());
        } catch (\Exception $e) {
            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(Request $request)
    {
        $ids = $request->post('dept_id');
        if (!$ids) {
            return json_fail("数据错误");
        }
        try {
            if (is_array($ids)) {
                SysDept::whereIn('dept_id', $ids)->delete();
            } else {
                SysDept::where('dept_id', $ids)->delete();
            }
        } 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();
    }
}