<?php
/**
 * @copyright Copyright (c) 2022 勾股工作室
 * @license https://opensource.org/licenses/GPL-3.0
 * @link https://www.gougucms.com
 */

declare (strict_types = 1);

namespace app\api\controller;

use app\api\ApiController;
use app\api\middleware\Auth;
use app\project\model\ProjectTask as TaskList;
use app\oa\model\Schedule as ScheduleList;
use app\project\validate\TaskCheck;
use think\exception\ValidateException;
use think\facade\Db;

class ProjectTask extends ApiController
{

    protected $middleware = [
    	Auth::class => ['except' => []]
    ];

    public function index()
    {
        // $this->checkAuth();
        $param = get_params();
        $param['uid'] = JWT_UID;
        $list = (new TaskList())->list($param);
        $list = $list->toArray();
        foreach($list['data'] as $k=>$v) {
            $list['data'][$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
            $list['data'][$k]['update_time'] = date('Y-m-d H:i:s', $v['update_time']);
        }
        $this->apiSuccess('获取成功', $list);
    }

    //添加
    public function add()
    {
        $this->checkAuth();
        $this->uid = JWT_UID;
        $param = get_params();
        if (isset($param['end_time'])) {
            $param['end_time'] = strtotime(urldecode($param['end_time']));
        }if (isset($param['flow_status'])) {
            if ($param['flow_status'] == 3) {
                $param['over_time'] = time();
            } else {
                $param['over_time'] = 0;
            }
        }
        if (!empty($param['id']) && $param['id'] > 0) {
            $task = (new TaskList())->detail($param['id']);
            try {
                validate(TaskCheck::class)->scene('edit')->check($param);
            } catch (ValidateException $e) {
                $this->apiError($e->getError());
            }
            $param['update_time'] = time();
            $res = TaskList::where('id', $param['id'])->strict(false)->field(true)->update($param);
            if ($res) {
                add_log('edit', $param['id'], $param);
                add_project_log($this->uid,'task',$param, $task);
            }
            $this->apiSuccess('操作成功');
        } else {
            try {
                validate(TaskCheck::class)->scene('add')->check($param);
            } catch (ValidateException $e) {
                $this->apiError($e->getError());
            }
            $param['create_time'] = time();
            $param['admin_id'] = $this->uid;
            $sid = TaskList::strict(false)->field(true)->insertGetId($param);
            if ($sid) {
                add_log('add', $sid, $param);
                $log_data = array(
                    'module' => 'task',
                    'task_id' => $sid,
                    'new_content' => $param['title'],
                    'field' => 'new',
                    'action' => 'add',
                    'admin_id' => $this->uid,
                    'create_time' => time(),
                );
                Db::name('ProjectLog')->strict(false)->field(true)->insert($log_data);
            }
            $this->apiSuccess('操作成功');
        }
        
    }

    //查看
    public function view()
    {
        $this->checkAuth();
        $this->uid = JWT_UID;
        $param = get_params();
        $id = isset($param['id']) ? $param['id'] : 0;
        $detail = (new TaskList())->detail($id);
        if (empty($detail)) {
            $this->apiError('项目任务不存在');
        } else {
            $role_uid = [$detail['admin_id'], $detail['director_uid']];
            $detail['create_time'] = date('Y-m-d H:i:s', $detail['create_time']);
            $detail['update_time'] = date('Y-m-d H:i:s', $detail['update_time']);
            $detail['delete_time'] = date('Y-m-d H:i:s', $detail['delete_time']);
            $project_ids = Db::name('ProjectUser')->where(['uid' => $this->uid, 'delete_time' => 0])->column('project_id');
			$auth = isAuth($this->uid,'project_admin');
            if (in_array($detail['project_id'], $project_ids) || in_array($this->uid, $role_uid) || in_array($this->uid, explode(",",$detail['assist_admin_ids'])) || ($auth==1&&$detail['project_id']>0) || ($this->uid==1)) {
                $file_array = Db::name('ProjectFile')
                ->field('mf.id,mf.topic_id,mf.admin_id,f.name,f.filesize,f.filepath,f.fileext,f.create_time,f.admin_id,a.name as admin_name')
                ->alias('mf')
                ->join('File f', 'mf.file_id = f.id', 'LEFT')
                ->join('Admin a', 'mf.admin_id = a.id', 'LEFT')
                ->order('mf.create_time desc')
                ->where(array('mf.topic_id' => $id, 'mf.module' => 'task'))
                ->select()->toArray();
                $this->apiSuccess('获取成功', compact('detail', 'file_array'));
            }
            else{
                $this->apiError('您没权限查看该任务', [], 2);
            }
        }
    }

    //删除
    public function delete()
    {
        $this->checkAuth();
        $this->uid = JWT_UID;
        $id = get_params("id");
        $detail = Db::name('ProjectTask')->where('id', $id)->find();
        if (empty($detail)) {
            $this->apiError('项目任务不存在');
        }
        if ($detail['admin_id'] != $this->uid) {
            $this->apiError('你不是该任务的创建人，无权限删除', [], 2);
        }
        if (Db::name('ProjectTask')->where('id', $id)->update(['delete_time' => time()]) !== false) {
            $log_data = array(
                'module' => 'task',
                'field' => 'delete',
                'action' => 'delete',
                'task_id' => $detail['id'],
                'admin_id' => $this->uid,
                'old_content' => '',
                'new_content' => $detail['title'],
                'create_time' => time(),
            );
            Db::name('ProjectLog')->strict(false)->field(true)->insert($log_data);
            $this->apiSuccess('删除成功');
        } else {
            $this->apiError('删除失败');
        }
    }
	
	public function task_time() {
        $this->checkAuth();
        $this->uid = JWT_UID;
        $param = get_params();
        $tid = isset($param['tid']) ? $param['tid'] : 0;
        $where = [];
        if ($tid > 0) {
            $task_ids = Db::name('ProjectTask')->where(['delete_time' => 0, 'project_id' => $param['tid']])->column('id');
            $where[] = ['a.tid', 'in', $task_ids];
        }
        else{
            if (!empty($param['uid'])) {
                $where[] = ['a.admin_id', '=', $param['uid']];
            } else {
                $where[] = ['a.admin_id', '=', $this->uid];
            }
            if (!empty($param['keyword'])) {
                $where[] = ['a.title', 'like', '%' . trim($param['keyword']) . '%'];
            }
            //按时间检索
            if (!empty($param['diff_time'])) {
                $diff_time =explode('~', $param['diff_time']);
                $where[] = ['a.start_time', 'between', [strtotime(urldecode($diff_time[0])),strtotime(urldecode($diff_time[1]))]];
            }
        }
        $where[] = ['a.delete_time', '=', 0];
        $rows = empty($param['limit']) ? get_config('app.page_size') : $param['limit'];
        $schedule = ScheduleList::where($where)
            ->field('a.*,u.name,d.title as department,w.title as work_cate')
            ->alias('a')
            ->join('Admin u', 'a.admin_id = u.id', 'LEFT')
            ->join('Department d', 'u.did = d.id', 'LEFT')
            ->join('WorkCate w', 'w.id = a.cid', 'LEFT')
            ->order('a.end_time desc')
            ->paginate($rows, false)
            ->each(function ($item, $key) {
                $item->labor_type_string = '案头工作';
                if($item->labor_type == 2){
                    $item->labor_type_string = '外勤工作';
                }
                if($item->tid > 0){
                    $task = Db::name('ProjectTask')->where(['id' => $item->tid])->find();
                    $item->task = $task['title'] ?? '';
                    $item->project = Db::name('Project')->where(['id' => $task['project_id']])->value('name');
                }
                $item->start_time_a = empty($item->start_time) ? '' : date('Y-m-d', $item->start_time);
                $item->start_time_b = empty($item->start_time) ? '' : date('H:i', $item->start_time);
                $item->end_time_a = empty($item->end_time) ? '' : date('Y-m-d', $item->end_time);
                $item->end_time_b = empty($item->end_time) ? '' : date('H:i', $item->end_time);
                $item->start_time = empty($item->start_time) ? '' : date('Y-m-d H:i', $item->start_time);
                $item->end_time = empty($item->end_time) ? '' : date('H:i', $item->end_time);
            });
        $this->apiSuccess('获取成功', $schedule);
        
    }
}
