<?php

namespace app\controller\api\v1;

use app\controller\api\Base;
use app\model\Account;
use app\model\CheckLog;
use app\model\OvertimeLog;
use app\model\Position;
use app\model\Worksite;
use app\repository\CommonRepository;
use app\repository\OperationRepository;
use app\validate\CommonValidate;
use think\Collection;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Config;
use think\response\Json;

class Common extends Base
{
    protected $noNeedLogin = [
        'slidePositions',
        'slides',
        'getCurrentWorksite',
        'worksiteList',
        'positionList',
        'notice',
    ];

    /**
     * 发送短信验证码
     *
     * @OA\Post(
     *     path="/common/send-code",
     *     tags={"common"},
     *     operationId="sendCode",
     * )
     */
    public function sendCode(): Json
    {
        $input    = input('post.');
        $validate = new CommonValidate();
        if (!$validate->scene('send_sms')->check($input)) {
            return $this->json(4001, '参数错误');
        }
        if (!in_array($input['type'], ['register', 'login', 'binding'])) {
            return $this->json(4002, '参数错误');
        }

//        CommonRepository::getInstance()->sendSms($input['phone'], $input['type']);
        return $this->json();
    }

    /**
     * 查看轮播图可视位置配置信息
     */
    public function slidePositions(): Json
    {
        $repo = OperationRepository::getInstance();
        $list = $repo->slidePositions();
        return $this->json(0, 'success', $list);
    }


    /**
     * 轮播图
     */
    public function slides(): Json
    {
        $size     = $this->request->param('size/d', 0);
        $position = trim($this->request->param('position/s', ''));
        if (empty($position)) {
            return $this->json();
        }

        try {
            $repo = OperationRepository::getInstance();
            $list = $repo->slideListByPosition($position, $size);
            $domain = $this->request->domain();
            $list->each(function ($item) use ($domain) {
                $item->src = resourceJoin($item->src, $domain);
                unset($item->created_at);
                unset($item->sort);
            });
        } catch (\Exception $e) {
            $list = new Collection();
        }

        return $this->json(0, 'success', $list);
    }

    // 根据经纬度获取所在工地 500米
    public function getCurrentWorksite(): Json
    {
        $lng = input('lng/s');
        $lat = input('lat/s');

        if (empty($lng) || empty($lat)) {
            return $this->json(4002, "参数错误");
        }

        Config::load('extra/base', 'base');
        $baseConfig = config('base');
        $signArea   = $baseConfig['sign_area'] ?? 200;

        return $this->json(0, 'success', Worksite::getNearest($lng, $lat, $signArea));
    }

    // 工地列表 todo 如果有相关用户 则获取该用户相关的工地列表 如工人 则只获取其参与过的工地列表 需要添加一个字段来确认是否根据用户过滤
    public function worksiteList(): Json
    {
        $page       = input('page/d', 1);
        $size       = input('size/d', 500);
        $keyword    = input('keyword/s');

//        $accountId = $this->request->user['user_id'] ?? 0;

        $where = [];

        if (!empty($keyword)) {
            $where[] = ['name|address', 'like', '%'.$keyword.'%'];
        }

        $where[] = ['status', '=', Worksite::COMMON_ON];
        $query   = Worksite::where($where);

        $total = $query->count();

        $res = [
            'total'   => $total,
            'current' => $page ?: 1,
            'size'    => $size ?: 500,
            'list'    => new Collection(),
        ];

        if ($total > 0) {
            $res['list'] = $query->page($page, $size)
                ->field('id,name')
                ->order('sort', 'desc')
                ->order('id', 'desc')
                ->select();
        }

        return $this->json(0, 'success', $res);
    }

    // 技术岗位列表
    public function positionList(): Json
    {
        $page       = input('page/d', 1);
        $size       = input('size/d', 500);
        $keyword    = input('keyword/s');

        $where = [];

        if (!empty($keyword)) {
            $where[] = ['name', 'like', '%'.$keyword.'%'];
        }

        $query   = Position::where($where);

        $total = $query->count();

        $res = [
            'total'   => $total,
            'current' => $page ?: 1,
            'size'    => $size ?: 500,
            'list'    => new Collection(),
        ];

        if ($total > 0) {
            $res['list'] = $query->page($page, $size)
                ->field('id,name')
                ->order('sort', 'desc')
                ->order('id', 'desc')
                ->select();
        }

        return $this->json(0, 'success', $res);
    }

    /**
     * 加班申请详情
     *
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function overtimeInfo(): Json
    {
        $accountId = $this->request->user['user_id'] ?? 0;
        $id = input('id/d');

        if (!$account = Account::where('id', $accountId)->field('id,role')->find()) {
            return $this->json(6001, '请先登录'.$accountId, $account);
        }

        if (!$item = OvertimeLog::find($id)) {
            return $this->json(4004, '加班记录不存在');
        }

        if ($item['account_id'] != $accountId && $account['role'] != Account::ROLE_MANAGER) {
            return $this->json(4003, '无权查看');
        }

        return $this->json(0,'success', $item);
    }

    /**
     * 获取通知消息 在打卡页面每次加载都需要请求此接口,查看是否需要展示信息
     * 如果有登录token就查询用户相关小题
     * 如果没有登录token则返回空
     *
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function notice(): Json
    {
        $accountId = $this->request->user['user_id'] ?? 0;

        if ($accountId == 0) {
            return $this->json(0, 'success', ['notice' => 0, 'msg' => '', 'id' => 0]);
        }

        if (!$account = Account::find($accountId)) {
            return $this->json(0, 'success', ['notice' => 0, 'msg' => '', 'id' => 0]);
        }

        if ($account['role'] != Account::ROLE_NORMAL) {
            return $this->json(0, 'success', ['notice' => 0, 'msg' => '', 'id' => 0]);
        }

        $checkLog = CheckLog::where('account_id', $accountId)->where('is_register', Account::COMMON_ON)->order('id', 'desc')->find();
        if (empty($checkLog)) {
            return $this->json(0, 'success', ['notice' => 0, 'msg' => '', 'id' => 0]);
        }

        if ($checkLog['status'] != -1) {
            return $this->json(0, 'success', ['notice' => 0, 'msg' => '', 'id' => 0]);
        }

        return $this->json(0, 'success', ['notice' => 1, 'msg' => $checkLog['refund_reason'], 'id' => $checkLog['id']]);
    }
}