<?php

declare (strict_types=1);

namespace app\controller\manager;

use app\model\WorksiteOutsource as Mwo;
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 WorksiteOutsource extends Base
{
    protected $noNeedLogin = ['index', 'add', 'edit', 'del', 'modify'];

    /**
     * 列表
     *
     * @throws Exception
     */
    public function index()
    {
        $worksiteId = input('worksite_id/d', 0);
        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|cl.name|o.name', 'like', '%'.$param.'%'];
                        continue;
                    }
                    if ($param == '0' || !empty($param)) {
                        $where[] = ['cl.'.$key, '=', $param];
                    }
                }
            }

            if ($worksiteId > 0) {
                $where[] = ['cl.worksite_id', '=', $worksiteId];
            }

            $query = Mwo::alias('cl')
                ->leftJoin('worksite w', 'w.id = cl.worksite_id')
                ->leftJoin('outsource o', 'o.id = cl.outsource_id')
                ->where($where);
            $total = $query->count();

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

            if ($total > 0) {
                $res['list'] = $query->fieldRaw('cl.*,w.name as worksite_name,o.name as outsource_name')->page($page, $size)->order('cl.id', 'desc')->select();
            }

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

        $this->data['worksiteId']    = $worksiteId;
        $this->data['outsourceList'] = \app\model\Outsource::list();
        return $this->view();
    }

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

                Mwo::create([
                    'name'         => $input['name'] ?? '',
                    'outsource_id' => $input['outsource_id'] ?? 0,
                    'amount'       => $input['amount'] ?? 0,
                    'log_time'     => $input['log_time'] ?? '',
                    'year'         => date('Y', strtotime($input['log_time'])),
                    'month'        => date('m', strtotime($input['log_time'])),
                    'day'          => date('d', strtotime($input['log_time'])),
                    'ym'           => date('Ym', strtotime($input['log_time'])),
                    'remarks'      => $input['remarks'] ?? '',
                    'worksite_id'  => $input['worksite_id'] ?? 0,
                    'created_at'   => date('Y-m-d H:i:s'),
                ]);

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

        $this->data['outsourceList'] = \app\model\Outsource::list();
        $this->data['worksiteId']    = $worksiteId;
        return $this->view();
    }

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

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

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

        if ($this->request->isPost()) {
            try {
                $input = input('post.');
                if (empty($input['name']) || empty($input['log_time']) || empty($input['amount']) || empty($input['outsource_id'])) {
                    return $this->json(4000, '参数错误');
                }

                $item->save([
                    'name'         => $input['name'] ?? '',
                    'outsource_id' => $input['outsource_id'] ?? 0,
                    'amount'       => $input['amount'] ?? 0,
                    'log_time'     => $input['log_time'] ?? '',
                    'year'         => date('Y', strtotime($input['log_time'])),
                    'month'        => date('m', strtotime($input['log_time'])),
                    'day'          => date('d', strtotime($input['log_time'])),
                    'ym'           => date('Ym', strtotime($input['log_time'])),
                    'remarks'      => $input['remarks'] ?? '',
                ]);
                return $this->json();
            } catch (Exception $e) {
                return $this->json(5000, $e->getMessage());
            }
        }

        $this->data['outsourceList'] = \app\model\Outsource::list();
        $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 = Mwo::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)) {
                Mwo::whereIn('id', $ids)->delete();

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

        return $this->json();
    }
}