<?php

namespace app\common\service;

use app\common\model\Project;
use app\common\service\Service;
use app\common\util\WhereBuilder;
use Carbon\Carbon;

class ProjectService extends Service
{
    public function page($param = [])
    {
        $this->autoParams($param);

        $status = $this->array('status');
        $keyword = $this->pg('keyword');
        $responsibility_person_id = $this->pg('responsibility_person_id');
        
        $create_time_begin_time = $this->pg('create_time_begin_time');
        $create_time_end_time = $this->pg('create_time_end_time');

        $update_time_begin_time = $this->pg('update_time_begin_time');
        $update_time_end_time = $this->pg('update_time_end_time');

        $min_amount = $this->pg('min_amount');
        $max_amount = $this->pg('max_amount');
        
        $min_dev_time_days = $this->pg('min_dev_time_days');
        $max_dev_time_days = $this->pg('max_dev_time_days');

        $min_maintain_time_days = $this->pg('min_maintain_time_days');
        $max_maintain_time_days = $this->pg('max_maintain_time_days');
        
        $where = WhereBuilder::builder()
            ->like('p.name|p.source', $keyword)
            ->in('p.status', $status)
            ->eq('p.responsibility_person_id', $responsibility_person_id)
            ->between('p.create_time', $create_time_begin_time, $create_time_end_time)
            ->between('p.update_time', $update_time_begin_time, $update_time_end_time)
            ->between('p.pre_dev_time', $min_dev_time_days, $max_dev_time_days)
            ->between('p.pre_maintain_time', $min_maintain_time_days, $max_maintain_time_days)
            ->between('p.estimated_amount', $min_amount, $max_amount)
            ->build();

        return (new Project)->alias('p')
            ->with(['schedules'])
            ->append(['participants'])
            ->field('p.*')
            ->field('a.real_name as responsibility_person')
            ->join('admin a', 'a.id = p.responsibility_person_id', 'LEFT')
            ->where($where)
            ->paginate($this->tp6Page());
    }

    public function create($param = []) 
    {
        $param = $this->autoParams($param);

        return Project::create($param);
    }

    public function info($param = [])
    {
        $this->autoParams($param);
        $project = $this->one(Project::class);
        $project->append(['contracts', 'schedules']);

        return $project;
    }

    public function update($param = [])
    {
        $param = $this->autoParams($param);
        return Project::update($param);
    }

    public function delete($param = [])
    {
        $this->autoParams($param);
        $project = $this->one(Project::class);
        return $project->delete();
    }
}