<?php

declare (strict_types=1);

namespace app\controller\manager;

use app\model\Account;
use app\model\Account as AccountModel;
use app\model\AccountWorksite;
use Exception;
use app\model\Log;
use think\Collection;
use think\response\View;
use think\response\Json;
use think\db\exception\DbException;
use think\exception\ValidateException;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;

class Worksite extends Base
{
    protected $noNeedLogin = ['getAccountList', 'outlay'];

    /**
     * 列表
     *
     * @throws Exception
     */
    public function index()
    {
        if ($this->request->isPost()) {
            $params = input('searchParams/a');
            $page   = input('page/d', 1);
            $size   = input('size/d', 20);

            $where = [];
            if (!empty($params)) {
                foreach ($params as $key => $param) {
                    $param = trim($param);
                    if ($key == 'keyword') {
                        $where[] = ['w.name', 'like', '%'.$param.'%'];
                        continue;
                    }
                    if ($param == '0' || !empty($param)) {
                        $where[] = ['w.'.$key, 'like', '%'.$param.'%'];
                    }
                }
            }

            $query = \app\model\Worksite::alias('w')->leftJoin('account a', 'a.id = w.manager_id')->where($where);
            $total = $query->count();

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

            if ($total > 0) {
                $res['list'] = $query->fieldRaw('w.*,a.nickname,a.real_name,a.mobile')->page($page, $size)->order('w.sort', 'desc')->order('w.id', 'desc')->select();
                $statusText  = \app\model\Worksite::statusText();
                $res['list']->each(function ($item) use ($statusText) {
                    $item->status_text = $statusText[$item->status] ?? '';
                    $item->manager     = ($item->nickname ? '昵称:'.$item->nickname : '').($item->real_name ? '  姓名:'.$item->real_name : '').($item->mobile ? '  手机:'.$item->mobile : '');
                });
            }

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

        return $this->view();
    }

    /**
     * 添加
     *
     * @return Json|View
     */
    public function add()
    {
        if ($this->request->isPost()) {
            try {
                $input = input('post.');
                if (!isset($input['name'])) {
                    return $this->json(4000, '参数错误');
                }

                $insert = [
                    'name'       => $input['name'] ?? '',
                    'lng'        => $input['lng'] ?? '',
                    'lat'        => $input['lat'] ?? '',
                    'address'    => $input['address'] ?? '',
                    'manager_id' => $input['manager_id'] ?? 0,
                ];

                if (!isset($input['am']) || !isset($input['pm'])) {
                    return $this->json(4000, '工作时间必填');
                }

                $amArr = explode('-', $input['am']);
                $pmArr = explode('-', $input['pm']);

                $morningOn    = trim($amArr[0]);
                $morningOff   = trim($amArr[1]);
                $afternoonOn  = trim($pmArr[0]);
                $afternoonOff = trim($pmArr[1]);

                if ($morningOn >= $morningOff || $afternoonOn >= $afternoonOff || $morningOff > $afternoonOn) {
                    return $this->json(4000, '工作时间设置错误');
                }

                $insert['morning_on']        = $morningOn;
                $insert['morning_off']       = $morningOff;
                $insert['afternoon_on']      = $afternoonOn;
                $insert['afternoon_off']     = $afternoonOff;
                $insert['start_at']          = time();//明天生效
                $insert['old_morning_on']    = $morningOn;
                $insert['old_morning_off']   = $morningOff;
                $insert['old_afternoon_on']  = $afternoonOn;
                $insert['old_afternoon_off'] = $afternoonOff;

                if ($input['manager_id'] > 0) {
                    if (AccountWorksite::where('account_id', $input['manager_id'])->count() > 0) {
                        return $this->json(4003, '该负责人已绑定其他工地');
                    }
                }

                $item = \app\model\Worksite::create($insert);

                if ($input['manager_id'] > 0) {
                    AccountWorksite::where('worksite_id', $item->id)->delete();
                    AccountWorksite::create([
                        'worksite_id' => $item->id,
                        'account_id'  => $input['manager_id'],
                    ]);
                    Account::where('id', $input['manager_id'])->save(['role' => Account::ROLE_MANAGER, 'worksite_id' => $item->id]);
                }

                return $this->json();
            } catch (Exception $e) {
                return $this->json(4001, '添加失败'.$e->getMessage());
            }
        }

        return $this->view();
    }

    /**
     * 编辑
     *
     * @return \think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit()
    {
        $id = input('id');

        //通过ID查询
        $item = \app\model\Worksite::where('id', (int) $id)->find();

        if (empty($item)) {
            return $this->json(4000, '没有相关记录!');
        }

        if ($this->request->isPost()) {
            try {
                $input = input('post.');
                // 需要更新的字段
                $update = [
                    'name'       => $input['name'] ?? '',
                    'lng'        => $input['lng'] ?? '',
                    'lat'        => $input['lat'] ?? '',
                    'address'    => $input['address'] ?? '',
                    'manager_id' => $input['manager_id'] ?? 0,
                ];

                if (!isset($input['name']) || !isset($input['lng']) || !isset($input['lat'])) {
                    return $this->json(4000, '参数错误');
                }

                if (!isset($input['am']) || !isset($input['pm'])) {
                    return $this->json(4000, '工作时间必填');
                }

                $amArr = explode('-', $input['am']);
                $pmArr = explode('-', $input['pm']);

                $morningOn    = trim($amArr[0]);
                $morningOff   = trim($amArr[1]);
                $afternoonOn  = trim($pmArr[0]);
                $afternoonOff = trim($pmArr[1]);

                if ($morningOn >= $morningOff || $afternoonOn >= $afternoonOff || $morningOff > $afternoonOn) {
                    return $this->json(4000, '工作时间设置错误');
                }

                // 工作时间是否有变更
                // 若工作时间有变更 第二天生效,时间在start_at前时使用old_系列时间
                if ($item['morning_on'] != $morningOn || $item['morning_off'] != $morningOff
                    || $item['afternoon_on'] != $afternoonOn || $item['afternoon_off'] != $afternoonOff) {
                    $update['morning_on']        = $morningOn;
                    $update['morning_off']       = $morningOff;
                    $update['afternoon_on']      = $afternoonOn;
                    $update['afternoon_off']     = $afternoonOff;
                    $update['start_at']          = strtotime('23:59:59') + 1;//明天生效
                    $update['old_morning_on']    = $item['morning_on'] ?: $morningOn;
                    $update['old_morning_off']   = $item['morning_off'] ?: $morningOff;
                    $update['old_afternoon_on']  = $item['afternoon_on'] ?: $afternoonOn;
                    $update['old_afternoon_off'] = $item['afternoon_off'] ?: $afternoonOff;
                }

                Account::where('id', $item['manager_id'])->save(['role' => Account::ROLE_NORMAL]);
                AccountWorksite::where('worksite_id', $id)->delete();
                if ($input['manager_id'] > 0) {
                    if (AccountWorksite::where('account_id', $input['manager_id'])->where('worksite_id', '<>', $id)->count() > 0) {
                        return $this->json(4003, '该负责人已绑定其他工地');
                    }
                    AccountWorksite::create([
                        'worksite_id' => $id,
                        'account_id'  => $input['manager_id'],
                    ]);

                    Account::where('id', $input['manager_id'])->save(['role' => Account::ROLE_MANAGER, 'worksite_id' => $id]);
                }

                $item->save($update);
                return $this->json();
            } catch (Exception $e) {
                return $this->json(5000, $e->getMessage());
            }
        }

        $bindAccount = Account::where('id', $item['manager_id'])->column('id,nickname,real_name,mobile');

        $accountList = [];
        foreach ($bindAccount as $ac) {
            $accountList[] = [
                'name_text' => $ac['nickname'].'【姓名:'.$ac['real_name'].'】【手机:'.$ac['mobile'].'】',
                'id'        => $ac['id'], 'selected' => true
            ];
        }
        $item['am']            = $item['morning_on'].' - '.$item['morning_off'];
        $item['pm']            = $item['afternoon_on'].' - '.$item['afternoon_off'];
        $this->data['jsonStr'] = $bindAccount ? json_encode($accountList, JSON_UNESCAPED_UNICODE) : json_encode([]);
        $this->data['item']    = $item;
        $this->data['id']      = $id;
        return $this->view();
    }

    /**
     * 更新属性
     *
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws DataNotFoundException
     * @throws Exception
     */
    public function modify()
    {
        if (!$this->request->isPost()) {
            return $this->json(4000, '非法请求');
        }

        $item     = input('post.');
        $validate = $this->validateByApi($item, [
            'field' => 'require',
            'value' => 'require',
        ]);

        if ($validate !== true) {
            return $validate;
        }

        // 通过ID查询
        if (!$info = \app\model\Worksite::where('id', (int) $item['id'])->find()) {
            return $this->json(4001, '记录不存在');
        }

        $update = [$item['field'] => $item['value']];

        try {
            $info->save($update);
            return $this->json();
        } catch (ValidateException $e) {
            return $this->json(4001, $e->getError());
        } catch (Exception $e) {
            return $this->json(5000, '修改失败');
        }
    }

    /**
     * 删除
     *
     * @return \think\response\Json
     */
    public function del(): Json
    {
        if (!$this->request->isPost()) {
            return $this->json(4000, '非法请求');
        }

        $ids = $this->request->param('ids/a', []);
        if (empty($ids)) {
            $ids[] = $this->request->param('id/d', 0);
            $ids   = array_filter($ids);
        }

        try {
            if (count($ids)) {
                //删除逻辑
                if (\app\model\Account::whereIn('Worksite', $ids)->count() > 0) {
                    return $this->json(4000, '所选岗位已分配给用户,请先移除后再删除');
                }
                \app\model\Worksite::whereIn('id', $ids)->delete();

                Log::write(get_class(), 'del', '删除操作,涉及到的ID为:'.implode(',', $ids));
            }
        } catch (Exception $e) {
            return $this->json(5000, $e->getMessage());
        }

        return $this->json();
    }

    /**
     * 获取客户列表
     *
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException|Exception
     */
    public function getAccountList(): Json
    {
        if ($this->request->isPost()) {
            $keyword = input('keyword/s', '');
            $page    = input('page/d', 1);
            $size    = input('size/d', 10);
            $id      = input('id', '');

            $relationIds = explode(',', $id);//已选记录

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

            $res = AccountModel::findList($where, ['id', 'nickname', 'real_name', 'mobile'], $page, $size);

            if ($res['total'] > 0 && $relationIds) {
                $res['list'] = $res['list']->toArray();
                foreach ($res['list'] as &$item) {
                    $item['name_text'] = sprintf("昵称:%s;真实姓名:%s,手机号:%s", $item['nickname'], $item['real_name'], $item['mobile']);
                    if (count($relationIds) > 0 && in_array($item['id'], $relationIds)) {
                        $item['selected'] = true;
                    }
                }
            }

            return $this->json(0, '操作成功', $res);
        }
        return $this->json(4001, '非法请求');
    }

    /**
     * 项目支出汇总
     *
     */
    public function outlay(): View
    {
        $id = input('id');


        return $this->view();
    }
}