ScoreSet.php 9.0 KB
<?php

namespace app\school\controller\setting;

use app\common\controller\DoubleBase;
use app\school\model\setting\ProjectScoreSet;
use think\Db;
use think\Exception;

class ScoreSet extends DoubleBase
{
    protected $containerId = null;
    protected $model = null;

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

    public function index()
    {
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $fields = ['id', 'container_id', 'table_name', 'total_score', 'is_perfect'];
            $total = $this->model->where($where)->where(['container_id' => $this->containerId])->count();
            $rows = $this->model->field($fields)->where($where)->where(['container_id' => $this->containerId])->limit($offset, $limit)->select();
            $res = [
                'total' => $total,
                'rows' => $rows
            ];
            return $res;
        }

        return $this->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            try {
                $usedTable = Db::name('project_review_set')->where(['score_set_id' => $ids])->find();
                // 评分表已经被使用,不可删除和修改
                if (!empty($usedTable)) {
                    $this->error('该评分表已经被使用,不可删除和修改');
                }
                $this->model->get($ids)->delete();
            } catch (Exception $e) {
                $this->error($e->getMessage());
            }
            $this->success();
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 添加评分表
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->shopIdAutoCondition && SCHOOL_ID) {
                    $params['school_id'] = SCHOOL_ID;
                }

                $params['container_id'] = $this->containerId;
                $params['total_score'] = (int)$params['total_score'];

                $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 . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    if (empty($params['id'])) {
                        $result = $this->model->allowField(true)->save($params);
                    } else {
                        $result = $this->model->allowField(true)->save($params, ['id' => $params['id']]);
                    }
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success('', '', $this->model->id);
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }


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

        if ($this->request->isAjax()) {
            $param = $this->request->param('row/a');
            Db::startTrans();
            try {
                $param['total_score'] = (int)$param['total_score'];
                // 评分表总分和已设置的评分项分数是否一致
                $setScore = $this->setScore($this->scoreSetItems($ids));
                $isPerfect = $setScore === $param['total_score'] ? 1 : 0;
                $param['is_perfect'] = $isPerfect;

                $this->model->allowField(true)->save($param,['id' => $param['id']]);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success();
        }

        $tab = $this->request->param('tab');
        $usedTable = Db::name('project_review_set')->where(['score_set_id' => $ids])->find();

        $this->view->assign("row", $row);
        $this->view->assign("tab", $tab);
        $this->view->assign("used", !empty($usedTable));
        $this->assignconfig('used', !empty($usedTable));
        $this->assignconfig('score_set_id', $row['id']);
        return $this->view->fetch();
    }


    /**
     * 添加评分表项-评分项列表
     * @param int $ids 评分表id
     */
    public function addItemsIndex($ids = null)
    {
        if ($this->request->isAjax()) {
            $rows = $this->scoreSetItems($ids);
            $total = count($rows);
            $totalScore = $this->model->where(['id' => $ids])->value('total_score');
            $setScore = $this->setScore($rows);

            // 评分表总分和已设置的评分项分数是否一致
            $isPerfect = $setScore == $totalScore ? 1 : 0;
            $this->model->save(['is_perfect' => $isPerfect], ['id' => $ids]);
            $res = [
                'total' => $total,
                'rows' => $rows,
                'extend' => [
                    'total_score' => $totalScore,
                    'set_score' => $setScore
                ]
            ];
            return $res;
        }

        return $this->fetch();
    }

    /**
     * 添加评分表项-添加打分点
     */
    public function addItemsAdd($ids = null)
    {
        if ($this->request->isAjax()) {
            $params = $this->request->param('row/a');

            Db::startTrans();
            try {
                Db::name('project_score_set_fields')->insert($params);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success();
        }
        $this->assign('score_set_id', $ids);
        return $this->fetch();
    }

    /**
     * 添加评分表项-编辑打分项
     * @param int $ids 打分项id
     */
    public function addItemsEdit($ids = null)
    {

        if ($this->request->isAjax()) {
            $param = $this->request->param('row/a');

            Db::startTrans();
            try {
                Db::name('project_score_set_fields')->update($param);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success();
        }

        $row = Db::name('project_score_set_fields')->where(['id' => $ids])->find();
        if (!$row) {
            $this->error('没有找到数据');
        }
        if (empty(json_decode($row['item_details'], true))) {
            $row['item_details'] = null;
        }
        $this->assign('row', $row);
        return $this->fetch();
    }

    /**
     * 添加评分表项-删除打分项
     * @param int $ids 打分项id
     */
    public function addItemsDel($ids = null)
    {
        if ($ids) {
            Db::startTrans();
            try {
                Db::name('project_score_set_fields')->delete($ids);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success();
        }
        $this->error('表单项数据错误,请联系管理员');
    }


    /**
     * 计算已经设置的评分项分数
     * @param array $rows 评分的评分项数组
     * @return int $setScore
     */
    private function setScore($rows = [])
    {
        $setScore = 0;
        foreach ($rows as $v) {
            $setScore += empty($v['item_details'])
                ? 0
                : array_sum(array_map(function ($item) {
                    return $item['score'];
                }, $v['item_details']));
        }
        return $setScore;
    }

    /**
     * 根据id获取评分表评分项数组(评分要点为数组格式)
     * @param int $ids 评分表id
     * @return array
    */
    private function scoreSetItems($ids = null)
    {
        if (!$ids) {
            $this->error('评分表id为空');
        }
        $rows = Db::name('project_score_set_fields')->where(['score_set_id' => $ids])->select();
        foreach ($rows as &$val) {
            $val['item_details'] = json_decode($val['item_details'], true);
        }
        return $rows;
    }
}