Review.php 45.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
<?php

namespace app\school\controller\review;

use app\common\controller\DoubleBase;

use app\common\model\Territory;
use app\school\model\Manystore;
use app\school\model\match\Match;
use app\school\model\match\MatchFormSet;
use app\school\model\match\MatchItems;
use app\school\model\match\MatchTags;
use app\school\model\match\MatchType;
use app\school\model\review\ReviewScoringTable;
use app\school\model\review\ReviewTags;
use app\school\model\review\ReviewTagsItems;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use app\school\model\match\MatchReviewResult;
use app\school\model\review\ReviewScore;
use function fast\e;

/**
 * 竞赛管理
 *
 * @icon fa fa-circle-o
 */
class Review extends DoubleBase
{
    protected $noNeedRight = ['*'];
    /**
     * Match模型对象
     * @var \app\school\model\match\Match
     */
    protected $model = null;
    protected $matchGroup = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\school\model\review\Review(); //实例化 网络评审模型

        $this->scoringTableModle = new ReviewScoringTable(); //评分表模型

        $this->matchFormSet = new MatchFormSet(); //比赛 表单设置

        $this->matchModel = new Match();//比赛模型

        $this->matchTypeModel = new MatchType(); //比赛赛道模型

        $this->matchTagsModel = new MatchTags(); //比赛分组模型
        $this->Expertsmodel = new \app\school\model\setting\ProjectExperts;
        //新增要查询评分表 列表(可用评分表)
        $scoring_table_list = $this->scoringTableModle->where('is_perfect',1)->select();

        $this->view->assign('scoring_table_list',$scoring_table_list); //评分表列表
        $this->view->assign("territoryList", Territory::getTerritoryList());
    }

    /**
     * [scoringtable 获取评分表下拉列表]
     * @Author   七
     * @DateTime 2020-12-24-9:39
     */
    public function scoringtable(){
        if ($this->request->isAjax()) {
            $searchValue = $this->request->param('searchValue');
            // 查找可用的评分表
            $where = ['is_perfect' => 1];
            if ($searchValue) {
                $where['id'] = $searchValue;
            }
//            $where["school_id"]= SCHOOL_ID;
            $where['manystore_id'] = $this->auth->id;
            $fields = ['id', 'table_name'];
            $total = $this->scoringTableModle->where($where)->count();
            $list = $this->scoringTableModle->field($fields)->where($where)->select();
            $res = [
                'total' => $total,
                'list' => $list
            ];
            return json($res);
        }
    }

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage,则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams('review_name');
            $map = [];
            if($this->auth->rule_type == 1) {
                $map['manystore_id'] = $this->auth->id;
            }
            $count = $this->model->where($where)->where($map)->count();
            $list = $this->model->where($where)->where($map)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->fetchSql(true)
                ->select();
            $result = array("total" => $count, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

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

                list($review_start_time,$review_end_time) = explode(' - ',$params['datetimerange']);
                $params['review_start_time'] = strtotime($review_start_time);
                $params['review_end_time'] = strtotime($review_end_time);
                unset($params['datetimerange']);
                $params['school_id'] = SCHOOL_ID;
                $params['manystore_id'] = $this->auth->id;

                $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);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    $insert["review_id"] = $this->model->id;
                    $insert["tag_name"] = '未分配分组';
                    $insert["school_id"] = SCHOOL_ID;
                    $insert["default"] = 1;
                    $insert["createtime"] = time();
                    $insert["updatetime"] = time();
                    ReviewTags::create($insert);
                    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 inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->assignconfig('review_id',0);
        $this->view->assign('tab',1); //给定默认选项

        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        if(empty($ids)){
            $ids = $this->request->param('id');
        }
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if(empty($params['match_tags_id'][0])) {
                $this->error(__('请选择标签'));
            }
            if(empty(json_decode($params['field_details'],true))) {
                $this->error(__('请选择展示字段'));
            }
            //已经设置过评审的标签不能再次添加
            foreach ($params['match_tags_id'] as $index => $item) {

                $reviewRes = (new \app\school\model\review\Review())->where('match_type_id',$params['match_type_id'])->where('find_in_set(:id,match_tags_id)',['id'=>$item])->where('id','neq',$ids)->select();

                if($reviewRes) {
                    $mtag = MatchTags::get($item);
                    $this->error('标签:('.$mtag['tag_name'].')已添加过评审不能重复添加');
                }
            }

            $params['match_tags_id'] = implode(',',$params['match_tags_id']);

            if ($params) {
                $params = $this->preExcludeFields($params);
                //报名数据
                $itemInfos =  (new MatchItems())->where('match_tag_id','in',$params['match_tags_id'])->select();
                $reviewTagId = Db::name('review_tags')->where(['review_id' => $params['id']])->where('tag_name','未分配分组')->value('id');
                $save = [];
                if($itemInfos) {
//                    dump($params);die;
                    foreach ($itemInfos as $val) {
                        $old = Db::name('review_tags_items')->where(['review_id' => $ids,'match_items_id' => $val['id']])->find();
                        if($old) {
                            continue;
                        }
                        $tmp['review_id'] = $ids;
                        $tmp['match_items_id'] = $val['id'];
                        $tmp['review_tags_id'] = $reviewTagId;
                        $save[] = $tmp;
                    }
                }
                $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);
                    }
                    if(!empty($save)) {
                        (new ReviewTagsItems)->insertAll($save);
                    }
                    //review——tag_items删除不存在的标签数据
//                    if(!empty($chaMatchTagsId)) {
//                        $matchItemIds = (new MatchItems())->whereIn('match_tag_id',$chaMatchTagsId)->column('id');
//                        if(!empty($matchItemIds)) {
//                            Db::name('review_tags_items')->whereIn('match_items_id',$matchItemIds)->delete();
//                        }
//                    }
//                    if(!empty($itemIds)) {
//                        $cha = array_diff($itemIds,$itemTags);
//                        if($cha) {
//                            $reviewTagId = Db::name('review_tags')->where(['review_id' => $params['id']])->where('tag_name','未分配分组')->value('id');
//                            $s = [];
//                            foreach ($cha as $k => $v) {
//                                $s[$k]['review_tags_id'] = $reviewTagId;
//                                $s[$k]['match_items_id'] =  $v;
//                            }
//                            (new ReviewTagsItems)->insertAll($s);
//                        }
//                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } 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', ''));
        }
        $fieldDetails = $this->getFieldDetails($ids);
        $this->view->assign("row", $fieldDetails['row']); //选中的数据

        $this->view->assign('tab',$this->request->param('tab')); //显示切换的tab
        $matchList = $this->getMatchList(); //获取比赛列表
        $match_id = empty($fieldDetails['row']['match_id']) ? key($matchList) : $fieldDetails['row']['match_id'];
        $matchTypeList = $this->getMatchTypeList($match_id);
        $matchType_id = empty($fieldDetails['row']['match_type_id']) ? key($matchTypeList) : $fieldDetails['row']['match_type_id'];
        $mtchTagList = $this->getMatchTagList($matchType_id);
        // 默认表单内容
        $fieldDetails = empty($fieldDetails['row']['match_type_id']) ? $this->getFieldDetails($ids,key($matchTypeList)) : $fieldDetails;
        $this->view->assign("fieldLang", $fieldDetails['fieldLang']); //表单列表
        $this->view->assign('formFieldsMap', $fieldDetails['formFieldsMap']); //表单类型及内容
        $this->view->assign('matchList',$matchList);
        $this->view->assign('matchTypeList',$matchTypeList);
        $this->view->assign('mtchTagList',$mtchTagList);  //标签
        $this->assignconfig('review_id',$ids);
        return $this->view->fetch();
    }


    public function editReview()
    {
        $params = $this->request->param('row/a');
        $review = new \app\school\model\review\Review();
        $info = $review->where(['id' => $params['id']])->find();
        if(!$info) {
            $this->error('评审不存在或已删除');
        }
        if(empty($params['review_name'])) {
            $this->error('请填写评审名称');
        }
        if(empty($params['scoring_table_id'])) {
            $this->error('请选择评分表');
        }

       list($startTime,$endTime) = explode(' - ',$params['datetimerange']);
        $params['review_start_time'] = strtotime($startTime);
        $params['review_end_time'] = strtotime($endTime);
        unset($params['datetimerange']);
        Db::startTrans();
        try {
            $result = $info->isUpdate(true)->save($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error('修改失败,稍后请重试');
        }
        $this->success('修改成功');
    }

    /**
     * 删除项目(软删除)
     */
    public function del($ids = "")
    {
        $info = Db::name('match_review_score')->where(['review_id' => $ids])->find();
        if($info) {
            $this->error("评审表已经被使用,不能删除");
        }
        if ($ids) {
            Db::startTrans();
            try {
                $this->model->get($ids)->delete();
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success('删除成功');
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }


    /**
     * [getFieldDetail 获取表单字段]
     * @Author   七
     * @DateTime 2020-12-25-9:09
     * @param $review_id      网络评审表id
     * @param $match_type_id  比赛赛道id(当没有的时候传递默认的赛道id数据,或不传递)
     */
    public function getFieldDetails($review_id=NULL,$match_type_id=NULL){
       //如果为ajax 请求则2使用请求数据查询
        if($this->request->isAjax()){
            $review_id = $this->request->param('review_id');
            $match_type_id = $this->request->param('match_type_id');
        }
        $row = []; //组装 已有值
        if(!empty($review_id)){
            $row = $this->model->get($review_id); //根据评审比赛id 查询评审数据
            $row['datetimerange'] = date("Y-m-d H:i:s",$row['review_start_time']).' - '.date("Y-m-d H:i:s",$row['review_end_time']);
            //格式化 评审表设置的 评审可见字段
            $row['field_details'] = empty(json_decode($row['field_details'], true)) ? [] : json_decode($row['field_details'], true);
            if(empty($match_type_id)){ //如果传入的赛道id为空的话,则查询自身存在的赛道id,自身也不存在的话 则为新增或初始,则不传
                $match_type_id = !empty($row['match_type_id']) ? $row['match_type_id'] : [];
            }
            $row['match_tags_id'] = empty($row['match_tags_id']) ? [] : explode(',',$row['match_tags_id']);
        }
        $formFieldsMap = []; //存储 实际的表单内容
        $fieldLang = [];
        //二次不为空的时候执行
        if(!empty($match_type_id)){
            //我们要根据赛道id 来查询 赛道下设置的所有表单数据
            $formFieldsMap = $this->matchFormSet->comment('查询所有表单数据,表单类型:表单字段')
                ->field('id,stage_title,stage_type,form_data')
                ->where(['match_type_id' => $match_type_id])
                ->select();

            $field_ids = array_column($formFieldsMap,'id');  //键值
            $formFieldsMap = array_combine($field_ids,$formFieldsMap) ;

            //循环转化表单数据
            foreach ($formFieldsMap as $k => $v){
                $form_data = json_decode($v['form_data'],true);
                $res = [];
                if(is_array($form_data)){
                    foreach ($form_data as $kk => $vv){
                        $res[$vv['name']] = $vv['title'];
                    }
                }
                $formFieldsMap[$k]['form_data'] = $res;
            }
            //获取表单的名称
            $fieldLang = $this->matchFormSet->where(['match_type_id' => $match_type_id])->column( 'stage_title', 'id');
        }
        return ['row'=>$row,'formFieldsMap'=>$formFieldsMap,'fieldLang'=>$fieldLang];
    }

    /**
     * [getMatchList 获取学校 比赛列表]
     * @Author   七
     * @DateTime 2020-12-25-10:19
     */
    public function getMatchList(){
        $map = [];
        if($this->auth->rule_type == Manystore::IS_COLLEGE) {
            $map['college_id'] = $this->auth->college_id;
        }
        return $this->matchModel->where($map)->where('school_id',SCHOOL_ID)->column('match_title','id');
    }

    /**
     * [getMatchTypeList 获取比赛赛道]
     * @Author   七
     * @DateTime 2020-12-25-9:59
     * @param $match_id 比赛id
     */
    public function getMatchTypeList($match_id){
        return $this->matchTypeModel->where(['match_id'=>$match_id])->column('name','id');
    }

    /**
     * [getMatchTagList 获取赛道分组]
     * @Author   七
     * @DateTime 2020-12-25-10:15
     * @param $match_type_id
     */
    public function getMatchTagList($match_type_id){
        return $this->matchTagsModel->where(['match_type_id'=>$match_type_id])->where('tag_name','neq','淘汰')->column('tag_name','id');
    }


    /**
     * [reviewData 评审数据]
     * @Author   七
     * @DateTime 2021-01-05-10:40
     * @return array|mixed
     */
    public function reviewData()
    {
	    //dump($this->request->param());die;
        //项目评审id
        $params = $this->request->param();
        $reviewId = $this->request->param('ids');
        $this->matchItemsModel = new MatchItems(); //竞赛报名表
        $this->reviewModle = new \app\school\model\review\Review();  //评审模型
        $this->reviewTagsModel = new ReviewTags(); //评审标签模型
        $this->reviewTagsItemsModel = new ReviewTagsItems(); //标签关联报名详情
        //首先需要 筛选有哪些可以显示的数据 根据评审表的范围 来查
        $review_data = $this->reviewModle->get($reviewId);
        if ($this->request->isAjax()) {

            //搜索报名数据的基本条件
            $where_jc = [
                'a.school_id' => SCHOOL_ID
            ];

//            'match_id' => $review_data['match_id'],
//            'match_type' => $review_data['match_type_id'],
//            'match_tag_id' => ['in',$review_data['match_tags_id']],

            $match_tags_ids = [];
            if(!empty($review_data['match_tags_id'])){
//                $where_jc['a.match_tag_id'] =  explode(',',$review_data['match_tags_id']);
                $match_tags_ids =  explode(',',$review_data['match_tags_id']);
            }

            if(!empty($review_data['match_type_id'])){
                $where_jc['a.match_type'] = $review_data['match_type_id'];
            }

            //获取选中标签 然后筛选显示哪些数据 为空则表示为 显示全部数据
            $count = 0;
//            dump($where_jc);die;
            $review_tags_id = $this->request->param('review_tags_id');
            if(isset($review_tags_id)){
//                if($review_tags_id=='all'){
//                    $query = $this->matchItemsModel
//                        ->alias('a')
//                        ->field('a.*,b.match_details,i.id as tags_items_id,i.review_tags_id,res.result')
//                        ->join('fa_match_items_details b','a.id=b.match_items_id','left')
//                        ->join('fa_review_tags_items i','a.id=i.match_items_id','left')
//                        ->join('fa_match_review_result res','a.id = res.match_item_id','left')
//                        ->where('res.deletetime',null)
//                        ->order('res.result desc')
//                        ->where($where_jc);
//                }elseif ($review_tags_id==0){
//                    $this->reviewTagsModel = new ReviewTags(); //评审标签模型
//                    //查询标签数据
//                    $where = ['review_id' => $reviewId,'school_id' => SCHOOL_ID];
//                    $review_tags_id_ = $this->reviewTagsModel->where($where)->column('id');
//                    $match_items_ids = Db::name("review_tags_items")->whereIn('review_tags_id',$review_tags_id_)->column("match_items_id");
//                    $query = $this->matchItemsModel
//                        ->alias('a')
//                        ->field('a.*,b.match_details,res.result')
//                        ->join('fa_match_items_details b','a.id=b.match_items_id','left')
//                        ->join('fa_match_review_result res','a.id = res.match_item_id','left')
//                        ->where('res.deletetime',null)
//                        ->order('res.result desc')
//                        ->where($where_jc)->whereNotIn('a.id',$match_items_ids);
//
//                }else{
////                    $query = $this->matchItemsModel
////                        ->alias('a')
////                        ->field('a.*,b.match_details,i.id as tags_items_id,i.review_tags_id,res.result')
////                        ->join('fa_review_tags_items i','a.id=i.match_items_id','inner')
////                        ->join('fa_match_items_details b','a.id=b.match_items_id','left')
////                        ->join('fa_match_review_result res','a.id = res.match_item_id','left')
////                        ->where('res.deletetime',null)
////                        ->order('res.result desc')
////                        ->where($where_jc)->where('i.review_tags_id',$review_tags_id);
//                    $query = $this->matchItemsModel
//                        ->alias('a')
//                        ->field('a.*,b.match_details,i.id as tags_items_id,i.review_tags_id')
//                        ->join('fa_review_tags_items i','a.id=i.match_items_id','inner')
//                        ->join('fa_match_items_details b','a.id=b.match_items_id','left')
////                        ->join('fa_match_review_result res','a.id = res.match_item_id','left')
////                        ->where('res.deletetime',null)
////                        ->order('res.result desc')
//                        ->where($where_jc)->where('i.review_tags_id',$review_tags_id);
//                }
                $query = $this->matchItemsModel
                        ->alias('a')
                        ->field('a.*,b.match_details,i.id as tags_items_id,i.review_tags_id,res.result')
                        ->join('fa_review_tags_items i','a.id=i.match_items_id','inner')
                        ->join('fa_match_items_details b','a.id=b.match_items_id','left')
                        ->join('fa_match_review_result res','res.match_item_id = a.id and res.tag_id = a.match_tag_id','left')
                        ->where('res.deletetime',null)
                        ->order('res.result desc')
                        ->where($where_jc)->where('i.review_tags_id',$review_tags_id);
            }else{
                $this->reviewTagsModel = new ReviewTags(); //评审标签模型
                $where = ['review_id' => $reviewId,'school_id' => SCHOOL_ID,'tag_name' => '未分配分组'];
                $reviewTagId = $this->reviewTagsModel->where($where)->column('id');
                //查询标签数据
//                $where = ['review_id' => $reviewId,'school_id' => SCHOOL_ID];
//                $review_tags_id_ = $this->reviewTagsModel->where($where)->column('id');
                $match_items_ids = Db::name("review_tags_items")->whereIn('review_tags_id',$reviewTagId)->column("match_items_id");
//                $query = $this->matchItemsModel
//                    ->alias('a')
//                    ->field('a.*,b.match_details,i.id as tags_items_id,i.review_tags_id,res.result')
//                    ->join('fa_match_items_details b','a.id=b.match_items_id','left')
//                    ->join('fa_match_review_result res','a.id = res.match_item_id','left')
//                    ->join('fa_review_tags_items i','a.id=i.match_items_id','inner')
//                    ->whereIn('i.review_tags_id',$reviewTagId)
//                    ->where('res.deletetime',null)
//                    ->order('res.result desc')
//                    ->where($where_jc)->whereIn('a.id',$match_items_ids);
                $query = $this->matchItemsModel
                    ->alias('a')
                    ->field('a.*,b.match_details,i.id as tags_items_id,i.review_tags_id,res.result')
                    ->join('fa_match_items_details b','a.id=b.match_items_id','left')
                    ->join('fa_match_review_result res','res.match_item_id = a.id and res.tag_id = a.match_tag_id','left')
                    ->join('fa_review_tags_items i','a.id=i.match_items_id','inner')
                    ->whereIn('i.review_tags_id',$reviewTagId)
                    ->where('res.deletetime',null)
                    ->order('res.result desc')
                    ->where($where_jc)->whereIn('a.id',$match_items_ids);
            }
            if(!empty($match_tags_ids)) {
                $query->where('a.match_tag_id','in',$match_tags_ids);
            }
            $query1 = clone $query;
            $count = $query1->count();
            $rows = $query->limit($params['offset'],$params['limit'])->select();
            //评审信息
            if(!empty($rows)){
                foreach ($rows as $k=>$val){
//                    $val['result'] = Db::name('match_review_result')->where('deletetime',null)->where(['match_item_id' => $val['id'],'tag_id' => $val['match_tag_id']])->value('result');
                    $score_total = 0;
                    $expert = [];
                    $detail = json_decode($val['match_details'],true);

                    if(is_object($val)){
                        $val = json_decode(json_encode($val),TRUE);
                    }
                    if(!empty($detail)){
                        $val = array_merge($detail,$val);
                    }
                    if(isset($val['tags_items_id'])){
                        $score = Db::name("match_review_score")->where(['tag_items_id'=>$val['tags_items_id']])->select();
                        
                        if(!empty($score)){
                            foreach ($score as $key=>$value){
                                if(empty($value['score_total'])){
                                    $value['score_total'] = 0;
                                }
                                $expert[$key]['expert_name'] =  Db::name('project_experts')->where(['id'=>$value['judge_id']])->value('nickname');
                                $expert[$key]['score_total'] = $value['score_total'];
                                $score_total +=$value['score_total'];
                            }
                        }
                    }

                    if(isset($val['review_tags_id'])){
                        $val['tag_name'] =Db::name("review_tags")->where('id',$val['review_tags_id'])->value('tag_name');
                    }else{
                        $val['tag_name'] = '未分配分组';
                    }

                    $val['expert'] = $expert;
                    $val['score_total']  = $score_total;
                    $val['mobile']  = Db::name('user')->where('id',$val['user_id'])->value("mobile");
                    $rows[$k] = $val;
                }
            }
            return ['total' =>$count,'rows'  => $rows];
        }
        $data = [];
        $field_details = json_decode($review_data['field_details'],true); //显示字段
        if(!empty($field_details)){
            foreach ($field_details as $v ){
                $data[]=['checkbox'=>true];
                foreach ($v as $value){
                    $data[] = [
                        'field' => $value,
                        'title' => __($value)
                    ];
                }
            }
            $data[] = [
                'field' => 'expert',
                'title' => '评委',
            ];
        }
        //$this->assignconfig('data', $data);  //显示字段(默认显示字段 从报名中取前四个)

        $reviewStage = $this->getTagsList($reviewId);
        $this->assignconfig('reviewStage',$reviewStage); //评审标签
        $this->assignconfig('review_id', $reviewId); //评审id
        return $this->fetch();
    }

    public function getTagsList($reviewId){
        $this->reviewTagsModel = new ReviewTags(); //评审标签模型

        //查询标签数据
        $where = ['review_id' => $reviewId,'school_id' => SCHOOL_ID];
        $reviewStage = $this->reviewTagsModel->where($where)->select();
//        array_push($reviewStage,['id' => 'all','tag_name' => '全部数据']);
        foreach ($reviewStage as $k => $v){
            //查询标签下的 报名数据 (筛选分配过来的数据)
            $reviewStage[$k]['count'] = 0;
        }
        return $reviewStage;
    }

    /**
     * [addReviewTags 新增/修改标签]
     * @Author   七
     * @DateTime 2021-01-07-14:24
     */
    public function addReviewTags(){
        if($this->request->isAjax()){
            $params = $this->request->param();
            $this->reviewTagsModel = new ReviewTags(); //评审标签模型
            $result = false;
            Db::startTrans();
            try {
                $params['school_id'] = SCHOOL_ID;
                $result = $this->reviewTagsModel->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) {
                $reviewStage = $this->getTagsList($params['review_id']);
                $this->assignconfig('reviewStage',$reviewStage); //评审标签
                $this->success('新增标签成功!');
            } else {
                $this->error(__('No rows were inserted'));
            }
        }
        $this->error('请求失败!');
    }

//    /**
//     * 根据传入的评审主题表id,生成该表对应的数据(基本设置、显示字段设置)
//     * 因为是比赛下的 赛道,所以 会存在 比赛id 和赛道id 赛道有自己独立的表单
//     * @param int $review_id 评审主题表id
//     * @return array
//     */
//    private function buildReviewSet($review_id,$match_type_id)
//    {
//        //根据传入的 比赛id 查询比赛信息
//        $row = $this->model->find($review_id); //评审信息
//        $row['field_details'] = empty(json_decode($row['field_details'], true)) ? [] : json_decode($row['field_details'], true);
//        if(empty($match_type_id)){
//            //赛道id
//            $match_type_id = !empty($row['match_type_id']) ? $row['match_type_id'] : $this->match_type_id();
//        }
//        $formFieldsMap = $this->matchFormSet->where(['project_type_id' => $row['project_type_id']])->column( 'form_data', 'stage_type');
//        $formFieldsMap = array_map(function ($fields) {
//            $res = [];
//            $fields = json_decode($fields, true);
//            foreach ($fields as $v) {
//                $res[$v['name']] = $v['title'];
//            }
//            return $res;
//        }, $formFieldsMap);
//        $fieldLang = $this->matchFormSet->where(['project_type_id' => $row['project_type_id']])->column( 'stage_title', 'stage_type');
////        // 不需要default类型的表单数据
////        unset($formFieldsMap['default']);
////        unset($fieldLang['default']);
//        return [$row, $formFieldsMap, $fieldLang];
//    }
    /**
     * @return string|\think\response\Json
     * @throws Exception
     * 评委页面
     */
    public function project_experts(){
        $param = $this->request->param();
        $tags_items_ids = $param['tags_items_id'];
        $review_tag_id = $param['review_tag_id'];

        $match_items_ids = Db::name("review_tags_items")->where('id','in',$tags_items_ids)->column('match_items_id');

        $judge_ids = Db::name('match_review_score')->where(["tag_items_id"=>['in',$tags_items_ids]])->column('judge_id');


        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage,则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams('nickname');
            $params = [];
            if($this->shopIdAutoCondition && SCHOOL_ID){
                $params['school_id'] = SCHOOL_ID;
            }
            $total = $this->Expertsmodel
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->Expertsmodel
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $list = collection($list)->toArray();

            $territoryModel = new Territory();
            foreach ($list as &$value) {
                $territoryIds = explode(',',$value['territory_id']);
                $territoryInfo = $territoryModel->whereIn('id',$value['territory_id'])->column('territory_name');
                $value['territory_name'] = $territoryInfo ? implode(',',$territoryInfo) : '--';
            }


            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        $this->assignconfig("old_judge",implode(",",$judge_ids));
        $this->assignconfig("match_items_id",implode(',',$match_items_ids));
        $this->assignconfig("review_id",$param['review_id']);
        $this->assign("review_tag_id",$param['review_tag_id']);
        $this->assignconfig("tags_items_id",$param['tags_items_id']);
        return $this->view->fetch();
    }

    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 添加评委
     */
    public function addJudge(){
        $param = $this->request->param();
        $match_items_ids = $param['match_items_id']; //作品
        $match_items = Db::name('match_items')->where('id','in',$match_items_ids)->select();
        if(empty($match_items)){
            $this->error('项目不存在');
        }
        if(empty($param['check_array'])){
            $this->error('请选择评委');
        }
        $setError = null;
        if(!empty($param['check_array']) && !empty($match_items)){
            $teachers = explode(',',$param['check_array']);
            $old_judge = explode(",",$param['old_judge']);
            $status = Db::transaction(function () use ($param,$teachers,$old_judge,$match_items,$match_items_ids){

                //获取选中的作品 + 标签 对应的 id
                $tagsItemsIds = ReviewTagsItems::where('review_tags_id',$param['review_tag_id'])
                    ->where('match_items_id','in',$match_items_ids)->select();
                $deleteItemIds = [];
                foreach ($tagsItemsIds as $k=>$v){
                    $deleteItemIds[] = $v['id'];
                }
                // 是否已取消之前选择的专家
                foreach ($old_judge as $delete_teacher){
                    if (!in_array($delete_teacher , $teachers)){
                        $delete_teachers = ReviewScore::all(
                            [
                                'tag_items_id'=>['in',$deleteItemIds],
                                'judge_id'=>$delete_teacher
                            ]
                        );
                        foreach ($delete_teachers as $k=>$v){
                            $v->delete(true);
                        }
                    }
                }


                $saveAll = [];
                $i = 0;
                $matchItems = new MatchItems();
                foreach ($teachers as $key=>$teacher){
                    foreach ($tagsItemsIds as $k=>$tagsItems){ //作品唯一ID
                        $count = ReviewScore::where('judge_id',$teacher)
                            ->where('tag_items_id',$tagsItems['id'])->count();
                        if (!$count){
                            $match_tag_id = $matchItems->where('id',$tagsItems['match_items_id'])->value('match_tag_id');
                            $saveAll[$i]['match_items_id']    = $tagsItems['match_items_id'];
                            $saveAll[$i]['tag_items_id']      = $tagsItems['id'];
                            $saveAll[$i]['tag_id']            = $match_tag_id;
                            $saveAll[$i]['review_id']         = $tagsItems['review_id'];
                            $saveAll[$i]['judge_id']          = $teacher;
                            $saveAll[$i]['createtime']        = time();
                            $i++;
                        }
                    }
                }
                if(count($saveAll) < 1){
                    $setError = "无可分配的数据";
                    return true;
                }
                return (new ReviewScore())->saveAll($saveAll);
            });
            if (!$status){
                $this->error($setError);
            }
            $this->success('分配成功');
            /*foreach ($teachers as $key=>$teacher){
                foreach ($match_items as $k=>$match_item){

                }
            }*/


            /* foreach ($teacher as $k=>$v){

                 if(in_array($v,$old_judge)){

                     $info = Db::name('match_review_score')->where(["tag_items_id"=>$param['tags_items_id'],"judge_id"=>$v])->find();

                     if(!empty($info)){
                         continue;
                     }

                 }
                 $insert[$k]['match_items_id']    = $match_items['id'];
                 $insert[$k]['tag_items_id']      = $param['tags_items_id'];
                 $insert[$k]['tag_id']            = $match_items['match_tag_id'];
                 $insert[$k]['review_id']         = $param['review_id'];
                 $insert[$k]['judge_id']          = $v;
                 $insert[$k]['createtime']        = time();
             }

             $data = Db::name('match_review_score')->insertAll($insert);

             if($data){
                 $this->success("添加成功");
             }else{
                 $this->error('添加失败');
             }*/
        }
    }

    /**
     * @throws Exception
     * @throws PDOException
     * 移动项目到某个标签
     */
    public function changeMatchTag(){
        $param = $this->request->param();

        if(empty($param['new_tags_id'])){
            $this->error('请选择移动到的标签');
        }

        if(empty($param['match_items_ids'])){
            $this->error('请选择报名数据');
        }
        foreach ($param['match_items_ids'] as $v){
            $itemInfo = MatchItems::get($v);
            $review = Db::name('review')->where('find_in_set(:id,match_tags_id)',['id'=>$itemInfo['match_tag_id']])->find();


            $id = Db::name('review_tags_items')->where(['review_tags_id'=>$param['new_tags_id'],'match_items_id'=>$v,'review_id'=>$review['id']])->value('id');
            if($id){
                continue;
            }else {
                $scoreResModel = new MatchReviewResult();
//                $oldData = Db::name('review_tags_items')->alias('r')
//                    ->field('r.id,w.id as review_id')
//                    ->join('review_tags t','r.review_tags_id = t.id','left')
//                    ->join('review w','w.id = t.review_id','left')
//                    ->where('r.match_items_id',$v)
//                    ->find();
                $old =  Db::name('review_tags_items')->where(['review_id' => $review['id'],'match_items_id' => $v])->select();
                //删除该数据之前分组信息 及分数信息
                Db::startTrans();
                try {
                    //删除其他分组下该记录信息
                    Db::name('review_tags_items')->where(['review_id' => $review['id'],'match_items_id' => $v])->delete();
                    Db::name('match_review_score')->where(['match_items_id' => $v,'tag_id' => $itemInfo['match_tag_id'],'review_id' => $review['id']])->delete();
                    //删除统计结果
                    Db::name('match_review_result')->where(['match_item_id' => $v,'review_id' => $review['id'],'tag_id' => $itemInfo['match_tag_id']])->delete();
                    //删除该阶段评分
//                    if($oldData) {
//                        Db::name('review_tags_items')->where('id',$oldData['id'])->delete();
//                        Db::name('match_review_score')->where(['match_items_id' => $v,'tag_items_id' => $oldData['id'],'review_id' => $oldData['review_id']])->delete();
//                    }
//                    $scoreResModel->where(['match_item_id' => $v,'review_id' => $oldData['review_id']])->delete();
                    $newReviewId = Db::name('review_tags')->where(['id' => $param['new_tags_id']])->value('review_id');
                    Db::name('review_tags_items')->insertGetId(['review_tags_id' => $param['new_tags_id'], 'match_items_id' => $v,'review_id' => $newReviewId]);
                    Db::commit();
                }  catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
            }
        }

        $this->success('移动成功');
    }

    /**
     * @throws Exception
     * @throws PDOException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 删除评委
     */
    public function delExperts(){
        $param = $this->request->param();

        if(empty($param['match_items_id']) ){
            $this->error("参数错误-2001");
        }

        if(empty($param['old_judge'])){
            $this->error("参数错误-2002");
        }

        $info = Db::name('match_review_score')->where(["match_items_id"=>$param['match_items_id'],"judge_id"=>$param['old_judge']])->find();
        if(empty($info)){
            $this->error('此评委已被删除');
        }else{
           $status = Db::name('match_review_score')->where(["match_items_id"=>$param['match_items_id'],"judge_id"=>$param['old_judge']])->delete();
           if($status){
                $this->success('删除成功');
           }else{
               $this->error('删除失败');
           }
        }
    }

    /**
     * 竞赛分数统计
     */
    public function item_statistic()
    {
        $ids = request()->param('ids');
        $score_type = request()->param('score_type');
        $review_id = request()->param('review_id');

        if(empty($ids) || !in_array($score_type,[1,2,3]) || empty($review_id)) {
            $this->error('参数错误-请选择数据');
        }
        $scoreModel = new ReviewScore();
        $scoreResModel = new MatchReviewResult();
        $save = [];
        $del = [];
        foreach (explode(',',$ids) as $key => $value) {
            $itemInfo = Db::name('match_items')->where('id',$value)->find();
            //是否已经打分
//            $scoreRes = $scoreModel->field('id,score_detail,score_total')->where('match_items_id',$value)->select();
            $scoreRes = $scoreModel->where('score_total','not null')->where('review_id',$review_id)->where(['match_items_id' => $value,'tag_id' => $itemInfo['match_tag_id']])->select();

            if(!$scoreRes) {
                continue;
            }
            $scoreRes = collection($scoreRes)->toArray();
            $statisticalRes = $scoreResModel->where(['match_item_id' => $value,'tag_id' => $itemInfo['match_tag_id']])->find();

            if($statisticalRes) {
                array_push($del,$statisticalRes['id']);
//                $statisticalRes->delete();
            }

            $save[$key]['match_item_id']    = $value;
            $save[$key]['review_id']        = $review_id;
            $save[$key]['score_type']       = $score_type;
            $save[$key]['score_type']       = $score_type;
            $save[$key]['tag_id']           = $itemInfo['match_tag_id'];
            $save[$key]['result']           = 0;
            //dump(collection($scoreRes)->toArray());die;

            $sumNumber = array_sum(array_column($scoreRes,'score_total'));
            $count = 0;
            foreach($scoreRes as $kk=>$vv){
               if($vv['score_total'] == null){
                   continue;
               }  
               $count++;
            }
            
            if($score_type == ReviewScore::STATISTICAL_ONE) {
                $resultScore = number_format($sumNumber / $count,2);
                $save[$key]['result'] = $resultScore;
            }else if($score_type == ReviewScore::STATISTICAL_TWO) {
                $save[$key]['result'] = $sumNumber;
            }else{
                if(count($scoreRes) < 4) {
                    $this->error('数据不足4个专家评分,不能使用该统计方式');
                }
                $scoreList = array_column($scoreRes,'score_total');
                sort($scoreList);             //排序
                array_pop($scoreList);        //去掉最大值
                array_shift($scoreList);       //去掉最小值
                $sum = array_sum($scoreList);  //求和
                $save[$key]['result'] = $sum;
            }

        }
        if(empty($save)) {
            $this->error('没有满足统计条件的数据');
        }
        Db::startTrans();
        try {
            if(!empty($del)) {
                $scoreResModel->whereIn('id',$del)->delete();
            }
            $scoreResModel->insertAll($save);
            Db::commit();
        }  catch (Exception $e) {
            Db::rollback();
            $this->error('统计失败,稍后请重试');
        }
        $this->success('成功');
    }
}