<?php

namespace app\school\controller\project_approval;

use app\common\controller\DoubleBase;
use app\school\controller\project_common\ProjectData;
use app\school\model\project_common\ProjectRegister;
use app\school\model\project_common\ProjectReview;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

class Rate extends DoubleBase
{
    protected $containerId = null;
    protected $model = null;
    // 评审阶段(0:立项评审;1:中期检查;2:项目结题)
    protected $reviewStage = 0;
    protected $shopIdAutoCondition = false;
    // 项目级别列表
    protected $levels = [
        '0' => '未评级',
        '1' => '院级',
        '2' => '校级',
        '3' => '省级',
        '4' => '国家级'
    ];
    // 引入获取项目数据的traits
    use ProjectData;

    public function _initialize()
    {
        parent::_initialize();
        $this->containerId = $_COOKIE['container_id'];
        $this->model = new ProjectRegister();
    }

    public function index()
    {
        if ($this->request->isAjax())
        {
            $map = [];
            $filter = json_decode($this->request->get('filter'), true);
            //自定义搜索条件
            if(isset($filter['project_type'])) {
                $map['a.project_type'] =  $filter['project_type'];
            }
            if(isset($filter['project_level'])) {
                $map['a.project_level'] =  $filter['project_level'];
            }
            if(isset($filter['college_id'])) {
                $map['u.college'] =  $filter['college_id'];
            }
            if(isset($filter['username'])) {
                $map['u.nickname'] = ['like',"%{$filter['username']}%"];
            }
            $map['a.review_stage'] = ['IN', '1,2'];
            if ($this->auth->rule_type == 1){
                //所属学院或部门
                $map['a.project_college'] =  $this->auth->college_id;
            }
            $result = $this->approvalProjectData($map);
            return json($result);
        }

        $stageWhere = [
            'container_id' => $this->containerId,
            'review_stage' => 0
        ];
        $reviewStageIds = (new ProjectReview())->where($stageWhere)->column('id');

        $this->assignconfig('review_stage_ids', $reviewStageIds);
        $this->assignconfig('project_level', $this->levels);
        $this->assign('levels', $this->levels);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->where(array('id'=>$ids,'school_id'=>SCHOOL_ID))->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        $this->assign('project_levels', $this->levels);
        return $this->view->fetch();
    }

    /**
     * 批量评级
     */
    public function rate()
    {
        if ($this->request->isAjax()) {
            $ids = explode(',', $this->request->param('ids'));
            $projectLevel = $this->request->param('project_level');

            $projectLevels = array_map(function ($id) use ($projectLevel) {
                return [
                    'id' => $id,
                    'project_level' => $projectLevel
                ];
            }, $ids);

            Db::startTrans();
            try {
                $this->model->allowField(true)->saveAll($projectLevels);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success();
        }
    }
}