Scoringtable.php 11.4 KB
<?php

namespace app\school\controller\review;

use app\common\controller\DoubleBase;

use app\school\model\Manystore;
use app\school\model\review\ReviewScoringTable;
use app\school\model\review\ReviewScoringTableFields;

use think\Db;
use think\Exception;

class Scoringtable extends DoubleBase
{
    protected $noNeedRight = ['*'];
    protected $containerId = null;
    protected $model = null;

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

        $this->model = new ReviewScoringTable(); //评分表模型
        $this->reviewScoringTableFields = new ReviewScoringTableFields(); //评分项模型

    }

    /**
     * [index 显示评分列表]
     * @Author   七
     * @DateTime 2020-12-23-10:29
     * @return array|mixed|\think\response\Json
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $map = [];
//            if($this->auth->rule_type != Manystore::IS_COLLEGE) {
//                $map['school_id'] = SCHOOL_ID;
//            }else {
//                $map['manystore_id'] = $this->auth->id;
//            }
            $map['manystore_id'] = $this->auth->id;
            //我们要针对不同的 学校 显示不同的 评分表
            $fields = ['id', 'container_id', 'table_name', 'total_score', 'is_perfect'];
            $total = $this->model
                ->where($where)
                ->where($map)
                ->count();
            $rows = $this->model
                ->field($fields)
                ->where($where)
                ->where($map)
                ->limit($offset, $limit)->select();
            $res = [
                'total' => $total,
                'rows' => $rows
            ];
            return $res;
        }

        return $this->fetch();
    }

    /**
     * [del 删除]
     * @Author   七
     * @DateTime 2020-12-23-10:29
     * @param string $ids
     */
    public function del($ids = "")
    {
        if ($ids) {
            try {
                //评分表
                $usedTable = Db::name('review')->where(['scoring_table_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'));
    }

    /**
     * [add 添加评分表]
     * @Author   七
     * @DateTime 2020-12-23-10:30
     * @return string
     */
    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['manystore_id'] = $this->auth->id;
                $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();
    }


    /**
     * [edit 编辑评分表]
     * @Author   七
     * @DateTime 2020-12-23-10:30
     * @param null $ids
     * @return string
     */
    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('review')->where(['scoring_table_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();
    }

    /**
     * [edit 查看评分内容]
     * @Author   七
     * @DateTime 2020-12-23-10:30
     * @param null $ids
     * @return string
     */
    public function see($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();
        }

        $this->view->assign("row", $row);
        $this->view->assign("tab", 1);
        $this->view->assign("used", 1);
        $this->assignconfig('used', 1);
        $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 {
                $this->reviewScoringTableFields->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 {
                $this->reviewScoringTableFields->update($param);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success();
        }

        $row = $this->reviewScoringTableFields->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 {
                $this->reviewScoringTableFields->get($ids)->delete();
                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 = $this->reviewScoringTableFields->where(['score_set_id' => $ids])->select();
        foreach ($rows as &$val) {
            $val['item_details'] = json_decode($val['item_details'], true);
        }
        return $rows;
    }
}