ActivityService.class.php 37.2 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 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208
<?php
/**
 * ActivityService.class.php
 * 活动信息表
 * @author: houyingcai
 * @email:  594609175@qq.com
 * @date :  2017-05-05 15:25:21
 */

namespace Common\Service;

use Common\Common\Helper;
use Common\Model\ActivityModel;
use Common\Model\CommentModel;
use Common\Model\LikeModel;
use Common\Model\RightModel;
use Com\Validate;
use Common\Model\PacketModel;
use Common\Common\User;
use VcySDK\Member;
use VcySDK\Service;

class ActivityService extends AbstractService
{

    // 发布活动
    const PUBLISH_ACTIVITY = 1;
    // 结束活动
    const STOP_ACTIVITY = 2;

    // 审核中
    const CHECK_ING = 0;
    // 已通过
    const  CHECK_PASS = 1;
    // 已驳回(未通过)
    const CHECK_FAIL = 2;


    // 红包功能开启
    const RED_OPENED = 1;
    // 红包功能未开启
    const RED_NOT_OPEN = 0;

    // 红包发放比例和(100)
    const TOTAL_PRO = 100;

    // 手机号码位数
    const MOBLIE_LENGTH = 11;

    // 红包类型:随机比例红包
    const RAND_PRO_RED = 1;

    // 基数放大比例数
    const BASENUM_PRO = 100;

    // 活动状态:草稿
    const DRAFT_STATUS = 0;

    // 开启审核
    const IS_CHECK_OPEN = 1;
    // 关闭审核
    const IS_CHECK_CLOSE = 0;

    // 自动审核
    const AUTO_CHECK = 2;


    // 开启抢红包图标
    const SHOW_RED_OPEN = 1;
    // 不开启抢红包图标
    const SHOW_RED_CLOSE = 0;

    //活动未隐藏
    const IS_HIDE_NO = 0;


    // 取一条数据用
    const ONE = 1;

    // 扩展字段必填
    const IS_REQUIRE_TRUE = 1;
    // 扩展字段非必填
    const IS_REQUIRE_FALSE = 0;

    /* @var LikeModel 点赞数据model */
    protected $_d_like = null;

    /* @var  CommentModel 回帖数据model */
    protected $_d_comment = null;

    /* @var PacketModel 红包数据model */
    protected $_d_packet = null;

    /* @var RightModel 权限model */
    protected $_d_right = null;


    // 构造方法
    public function __construct()
    {
        $this->_d = new ActivityModel();
        // 实例化点赞
        $this->_d_like = new LikeModel();
        // 实例化评论
        $this->_d_comment = new CommentModel();
        // 实例化红包
        $this->_d_packet = new PacketModel();
        // 实例化权限
        $this->_d_right = new RightModel();

        parent::__construct();
    }

    /**
     * 活动中心编辑任务类型
     *
     * @param array $old_activity 原始数据
     * @param array $activity 最新提交数据
     *
     * @return array
     */
    public function edit_new_type($old_activity = [], $activity = [])
    {
        // 验证数据
        $data = $this->new_validate_for_add($activity);

        // 已发布的不能编辑保存成草稿
        if ($old_activity['activity_status'] == ActivityModel::ACTIVITY_PUBLISH && $activity['activity_status'] == ActivityModel::ACTIVITY_DRAFT) {

            E('_ERR_ACTIVITY_STATUS');
        }

        // 是否是立即发布活动
        if ($activity['activity_status'] == ActivityModel::ACTIVITY_PUBLISH) {

            $data['publish_time'] = MILLI_TIME;
        }

        // 活动数据入库
        $this->_d->update($old_activity['ac_id'], $data);

        $result = ['ac_id' => intval($old_activity['ac_id'])];

        return $result;

    }

    /**
     * 验证新增活动数据
     *
     * @param array $activity 活动数据
     *
     * @return bool
     */
    public function validate_for_add(&$activity)
    {

        // 验证规则
        $rules = [
            'subject' => 'require|max:30',
            'source' => 'max:20',
            'begin_time' => 'require',
            'end_time' => 'require',
            'cover_id' => 'require',
            'content' => 'require',
            'is_all' => 'require|in:0,1',
            'is_notice' => 'require|in:0,1',
            'activity_status' => 'require|in:0,1,2',
            'is_red_open' => 'require|in:0,1',
        ];

        // 错误提示
        $msgs = [
            'subject.require' => L('_ERR_SUBJECT_EMPTY'),
            'subject.max' => L('_ERR_SUBJECT_LENGTH_ERROR'),
            'source.max' => L('_ERR_SOURCE_LENGTH_ERROR'),
            'begin_time' => L('_ERR_BEGINTIME_EMPTY'),
            'end_time' => L('_ERR_ENDTIME_EMPTY'),
            'cover_id' => L('_ERR_COVER_EMPTY'),
            'content' => L('_ERR_CONTENT_EMPTY'),
            'is_all' => L('_ERR_ISALL_INVALID'),
            'is_notice' => L('_ERR_ISNOTICE_INVALID'),
            'activity_status' => L('_ERR_ACTIVITY_STATUS_INVALID'),
            'is_red_open' => L('_ERR_IS_RED_OPEN_INVALID'),
        ];

        // 开始验证
        $validate = new Validate($rules, $msgs);
        if (!$validate->check($activity)) {

            E($validate->getError());
        }

        // 开始时间不能大于结束时间
        if ($activity['begin_time'] > $activity['end_time'] && $activity['end_time'] > 0) {

            E('_ERR_BEGINTIME_GT_ENDTIME');
        }

        // 如果不是全公司并且参与权限是空
        if ($activity['is_all'] != self::IS_ALL && empty($activity['right'])) {

            E('_ERR_RIGHT_EMPTY');
        }

        // 处理全公司时,传递是否可围观
        if ($activity['is_all'] == self::IS_ALL) {

            $activity['is_all_look'] = Helper::SALE_NOT_ALL_LOOK;
        }

        // 判断红包是否开启,红包设置为空,抛错
        if ($activity['is_red_open'] == self::RED_OPENED && empty($activity['red_content'])) {

            E('_EMPTY_REDSET');
        }

        // 开启随机比例红包,校验红包参数
        if ($activity['red_content']['red_type'] == 1 && !empty($activity['red_content'])) {

            // 验证红包配置信息
            $rules = [
                'red_type' => 'require|in:1,2,3',
                'red_base_num' => 'require',
                'is_show_red' => 'require|in:0,1',
                'warn_mobile' => 'require',
            ];

            // 错误提示
            $msgs = [
                'red_type' => L('_ERR_REDTYPE_INVALID'),
                'red_base_num' => L('_EMPTY_RED_BASENUM'),
                'is_show_red' => L('_ERR_ISSHOWRED_INVALID'),
                'warn_mobile' => L('_EMPTY_MOBILE'),
            ];

            //正整数正则
            $is_int = '/^[0-9]*[1-9][0-9]*$/';

            // 判断基数是否为正整数
            if (!preg_match($is_int, $activity['red_content']['red_base_num'])) {

                E('_ERR_RED_BASENUM_NOT_NUMBER');
            }

            // 基数格式化
            $activity['red_content']['red_base_num'] = $activity['red_content']['red_base_num'] * self::BASENUM_PRO;

            // 判断手机号码格式正确性
            if (!preg_match($is_int, $activity['red_content']['warn_mobile'])
                || strlen($activity['red_content']['warn_mobile']) != self::MOBLIE_LENGTH) {

                E('_ERR_MOBILE');
            }


            // 开始验证
            $validate = new Validate($rules, $msgs);
            if (!$validate->check($activity['red_content'])) {

                E($validate->getError());
            }

            // 每人领取次数验证
            if (!empty($activity['red_content']['red_get_num'])) {

                if (!preg_match($is_int, $activity['red_content']['red_get_num'])) {

                    E('_ERR_RED_GET_NUM_NOT_NUMBER');
                }
            } else {

                $activity['red_content']['red_get_num'] = 0;
            }

            // 空祝福语格式化
            if (empty($activity['packet_bless'])) {

                $activity['packet_bless'] = '';
            }

            // 红包规则验证
            if (empty($activity['red_content']['rule_list'])) {

                E('_EMPTY_RED_RULE');
            }

            $rule_list = $activity['red_content']['rule_list'];

            // 用于储存比例和
            $total_proportion = 0;

            // 金钱验证正则
            $money_rule = '/^[0-9]+(.[0-9]{1,2})?$/';

            // 判断红包规则内是否有误
            foreach ($rule_list as $key => $value) {

                if (!is_numeric($rule_list[$key]['red_proportion']) ||
                    $rule_list[$key]['red_proportion'] > 100 ||
                    $rule_list[$key]['red_proportion'] <= 0) {

                    E('_ERR_RED_PROPORTION');
                }

                // 新增逻辑:判断基数*百分比是否为整数
                $percentage_each_num = $value['red_proportion'] * $activity['red_content']['red_base_num'] / 100;
                if (floor($percentage_each_num) != $percentage_each_num) {
                    // 红包基数与百分比之积必须是整数
                    E('_ERR_RED_PROPORTION_TOTAL_NOT_NUMERIC');
                }

                $total_proportion += $rule_list[$key]['red_proportion'];

                if (empty($rule_list[$key]['red_proportion_money']) ||
                    !preg_match($money_rule, $rule_list[$key]['red_proportion_money'])) {

                    // 判断金额格式
                    E('_ERR_RED_PRO_MONEY');
                }
            }

            // 验证比例和是否错误
            if ($total_proportion != self::TOTAL_PRO) {

                E('_ERR_TOTAL_PRO');
            }

            // 如果开启审核,审核人员为空
            if (self::IS_CHECK_OPEN == $activity['is_check_open'] && empty($activity['check_user_list'])) {

                E('_EMPTY_CHECK_UID');
            }
        }
        // 扩展字段中名称存在重复值
        if (!empty($activity['ext_fields'])) {
            if (count(unserialize($activity['ext_fields'])) != count(array_combine_by_key(unserialize($activity['ext_fields']), 'name'))) {
                E('_ERR_EXT_FIELDS_NAME');
            }

        }
        return true;
    }

    /**
     * 对象数组转换为数组
     *
     * @param $array
     *
     * @return array
     */
    public function object_array($array)
    {
        if (is_object($array)) {

            $array = (array)$array;
        }
        if (is_array($array)) {

            foreach ($array as $key => $value) {
                $array[$key] = $this->object_array($value);

            }
        }

        return $array;
    }

    /**
     * 验证新增活动数据
     *
     * @param array $activity 活动数据
     *
     * @return array|bool
     */
    protected function new_validate_for_add($activity)
    {
        // 验证规则
        $rules = [
            'subject' => 'require|max:30',
            'source' => 'max:10',
            'cover_id' => 'require',
            'content' => 'require',
            'activity_status' => 'require|in:0,1',
        ];

        // 错误提示
        $msgs = [
            'subject.require' => L('_ERR_SUBJECT_EMPTY'),
            'subject.max' => L('_ERR_SUBJECT_LENGTH_ERROR'),
            'source.max' => L('_ERR_SOURCE_LENGTH_ERROR'),
            'cover_id' => L('_ERR_COVER_EMPTY'),
            'content' => L('_ERR_CONTENT_EMPTY'),
            'is_recomend' => L('_ERR_ISRECOMMEND_INVALID'),
            'activity_status' => L('_ERR_ACTIVITY_STATUS_INVALID'),
        ];

        // 开始验证
        $validate = new Validate($rules, $msgs);
        if (!$validate->check($activity)) {

            E($validate->getError());

            return false;
        }

        // 组装数据
        $data = [
            'ac_id' => $activity['ac_id'],
            'activity_type' => $activity['activity_type'],
            'subject' => $activity['subject'],
            'source' => $activity['source'],
            'content' => $activity['content'],
            'cover_id' => $activity['cover_id'],
            'activity_status' => $activity['activity_status'],
            'integral_action_type' => self::INTEGRAL_ACTION_TYPE_NO,
            'is_all' => self::IS_ALL,
            'last_time' => MILLI_TIME,
            'begin_time' => 0,
            'end_time' => 0
        ];

        return $data;
    }

    /**
     * 获取活动数据
     *
     * @param array $activity 活动数据
     *
     * @return array|bool
     */
    public function fetch_activity($activity)
    {
        $right_view = [];
        $right = $activity['right'];
        unset($activity['right']);

        // 活动状态是否存在
        if (!isset($activity['activity_status'])) {

            E('_EMPTY_ACTIVITY_STATUS');
        }

        // 格式化参与权限字段
        if (!empty($right)) {

            $right_view['r_type'] = !empty($right_view['r_type']) ? $right_view['r_type'] : 0;
            $right_view['uids'] = !empty($right['user_arr']) ? $right['user_arr'] : '';
            $right_view['dp_ids'] = !empty($right['dp_arr']) ? $right['dp_arr'] : '';
            $right_view['job_ids'] = !empty($right['job_arr']) ? $right['job_arr'] : '';
            $right_view['role_ids'] = !empty($right['role_arr']) ? $right['role_arr'] : '';
            $right_view['tag_ids'] = !empty($right['tag_arr']) ? $right['tag_arr'] : '';
        }


        $list = [
            'subject' => raddslashes($activity['subject']),
            // 活动标题
            'source' => raddslashes($activity['source']),
            // 作者
            'begin_time' => $activity['begin_time'],
            // 活动开始时间
            'end_time' => $activity['end_time'] ? $activity['end_time'] : 0,
            // 活动结束时间
            'cover_id' => raddslashes($activity['cover_id']),
            // 活动封面图片ID
            'content' => !empty($activity['content']) ? serialize($activity['content']) : $activity['content'],
            // content
            'is_all' => $activity['is_all'],
            // 	是否全公司可参与(0:否 ,1:是)is_all为0时right不能都为空
            'is_notice' => $activity['is_notice'],
            // 是否发送消息通知(0:否 ,1:是(默认开启))
            'activity_status' => $activity['activity_status'],
            // 动提交状态(0:草稿,1:发布)
            'is_red_open' => intval($activity['is_red_open']),
            // 是否开启红包(0(默认):否,1:是)
            'is_check_open' => intval($activity['is_check_open']),
            // 审核人员权限数据
            'check_user_list' => empty($activity['check_user_list']) ? "" : serialize($activity['check_user_list']),
            'right' => $right_view,
            // 参与权限数组
            'red_content' => $activity['red_content'],
            // 红包数据(仅在is_red_open为1,即开启红包时有值)
            'packet_bless' => raddslashes($activity['red_content']['packet_bless']),
            // 红包祝福语
            'is_show_red' => intval($activity['is_show_red']),
            // 是否显示抢红包(0(默认):否,1:是)
            'ext_fields' => !empty($activity['ext_fields']) ? serialize($activity['ext_fields']) : "",
            // 自定义扩展字段
            'is_all_look' => intval($activity['is_all_look']),
            // 是否可围观
            'is_post_remind' => intval($activity['is_post_remind']),
            // 发帖是否推送消息
            'is_recommend' => intval($activity['is_recomend'])
            // 是否推荐到首页
        ];

        return $list;
    }

    /**
     * 格式化feed流权限数据
     *
     * @param  array $right 权限数组
     *
     * @return array
     */
    protected function format_feed_data($right)
    {
        $feed_right = [];

        // 格式化权限字段
        if (!empty($right)) {

            $feed_right['users'] = !empty($right['uids']) ? array_column($right['uids'], 'memID') : '';
            $feed_right['departments'] = !empty($right['dp_ids']) ? array_column($right['dp_ids'], 'dpID') : '';
            $feed_right['jobs'] = !empty($right['job_ids']) ? array_column($right['job_ids'], 'jobID') : '';
            $feed_right['roles'] = !empty($right['role_ids']) ? array_column($right['role_ids'], 'roleID') : '';
        }

        return $feed_right;
    }


    /**
     * 组装发送消息的数据
     *
     * @param  int $ac_id 活动ID
     * @param  array $activity 活动信息数组
     * @param string $type 发送消息的类型
     *
     * @return array
     */
    public function assemble_msg_params($ac_id, $activity, $type = 'add')
    {

        $right_params = [];
        $params = [
            'ac_id' => $ac_id,
            'subject' => $activity['subject'],
            'begin_time' => $activity['begin_time'],
            'end_time' => $activity['end_time'],
            'content' => unserialize($activity['content'])
        ];

        // 发布、立即发布活动
        if ($type == 'add') {

            // 全公司
            if (self::IS_ALL == $activity['is_all']) {

                $params['is_all'] = $activity['is_all'];
            } else {

                $right = $activity['right'];

                $rightServ = new RightService();

                // 获取参与活动权限范围
                $right_params = $rightServ->list_by_right($right);
            }
        }

        // 编辑活动
        if ($type == 'edit') {

            $right_params = $activity['right'];
        }

        return $params = array_merge($params, $right_params);

    }

    /**
     * 组装给审核人发送消息的数据
     *
     * @param  int $ac_id 活动ID
     * @param  array $new_activity 新活动信息数组
     * @param  array $old_activity 原始活动信息数组
     *
     * @return array
     */
    public function send_check_msg_params($ac_id, $new_activity = [], $old_activity = [])
    {

        $params = [
            'ac_id' => $ac_id,
            'subject' => $new_activity['subject'],
            'begin_time' => $new_activity['begin_time'],
            'end_time' => $new_activity['end_time'],
            'content' => unserialize($new_activity['content'])
        ];

        $new_uids = array_column(unserialize($new_activity['check_user_list']), 'memID');

        // 如果是添加则没有原始审核人
        if (empty($old_activity)) {
            $params['uids'] = $new_uids;

            return $params;
        }
        // 原始审核用户UIDS
        $old_uids = array_column(unserialize($old_activity['check_user_list']), 'memID');

        // 获取差集
        $params['uids'] = array_diff($new_uids, $old_uids);

        return $params;
    }


    /**
     * 获取后台活动列表
     *
     * @param array $params 分页及搜索参数
     *
     * @return mixed
     */
    public function get_list_admin($params = [])
    {
        // 默认值
        $page = !empty($params['page']) ? intval($params['page']) : self::DEFAULT_PAGE;
        $limit = !empty($params['limit']) ? intval($params['limit']) : self::DEFAULT_LIMIT;

        // 分页
        list($start, $limit) = page_limit($page, $limit);

        // 获取记录总数
        $total = $this->_d->count_by_where($params);

        // 获取列表数据
        $list = [];
        if ($total > 0) {
            // 排序
            $order_option = ['last_time' => 'DESC'];

            $list = $this->_d->list_by_where($params, [$start, $limit], $order_option);
        }

        // 组装返回数据
        $result['total'] = intval($total);
        $result['limit'] = intval($limit);
        $result['page'] = intval($page);
        $result['list'] = $this->format_list_admin($list);

        return $result;
    }

    /**
     * 格式化后台活动详情数据
     *
     * @param $data array 活动详情数据
     *
     * @return mixed
     */
    public function format_activity_detail($data)
    {
        $data = [
            'subject' => raddslashes($data['subject']),
            'source' => raddslashes($data['source']),
            'ac_id' => intval($data['ac_id']),
            'is_all' => intval($data['is_all']),
            'is_notice' => intval($data['is_notice']),
            'is_recomend' => intval($data['is_recommend']),
            'begin_time' => $data['begin_time'],
            'end_time' => $data['end_time'],
            'activity_status' => $this->activity_status($data['activity_status'], $data['begin_time'],
                $data['end_time']),
            'cover_url' => imgUrlReal($data['cover_id']),
            'cover_id' => $data['cover_id'],
            'likes' => intval($data['likes']),
            'comments' => intval($data['comments']),
            'content' => !empty($data['content']) ? unserialize($data['content']) : $data['content'],
            'is_red_open' => intval($data['is_red_open']),
            'is_check_open' => intval($data['is_check_open']),
            'check_user_list' => !empty($data['check_user_list']) ? unserialize($data['check_user_list']) : [],
            'red_content' => raddslashes($data['red_content']),
            'packet_bless' => raddslashes($data['packet_bless']),
            'is_show_red' => rintval($data['is_show_red']),
            'ext_fields' => !empty($data['ext_fields']) ? unserialize($data['ext_fields']) : [],
            'is_all_look' => intval($data['is_all_look']),
            'is_post_remind' => intval($data['is_post_remind']),
            'stop_pay_time' => $data['stop_pay_time']
        ];

        return $data;
    }

    /**
     * 格式化基本详情数据
     * @param array $data 活动详情
     * @param array $user 用户详情
     * @return array
     * @throws mixed
     */
    public function format_base_detail_data($data = [], $user = [])
    {

        // 获取是否有权限围观,有权限参与,以及活动状态
        list($activity_status, $is_join_right, $is_all_look) = $this->is_join_right($data, $user);

        // 查询当前用户是否点赞
        $mylikecount = $this->_d_like->count_by_conds(
            [
                'uid' => $user['memUid'],
                'obj_id' => $data['ac_id'],
                'type' => self::LIKE_ACTIVITY_TYPE,
            ]
        );

        $result = [
            'ac_id' => intval($data['ac_id']),
            'source' => $data['source'],
            'subject' => $data['subject'],
            'cover_id' => $data['cover_id'],
            'cover_url' => empty($data['cover_id']) ? '' : imgUrlReal($data['cover_id']),
            'begin_time' => $data['begin_time'],
            'end_time' => $data['end_time'],
            'content' => unserialize($data['content']),
            'likes' => intval($data['likes']), // 点赞数
            'comments' => intval($data['comments']),
            'publish_time' => $data['publish_time'], // 发布时间
            'is_join_right' => $is_join_right,
            'activity_status' => $activity_status, // 活动状态
            'is_all_look' => $is_all_look,
            'is_like' => $mylikecount > 0 ? self::IS_LIKE_OK : self::IS_LIKE_NO, // 是否已点赞
        ];

        return $result;
    }

    /**
     * 验证是否具有参与权限
     *
     * @param array $info 活动详情
     * @param array $user
     *
     * @return array
     */
    public function is_join_right($info = [], $user = [])
    {
        // 默认有权发布评论
        $is_join_right = Helper::IS_JOIN_RIGHT;
        // 初始化围观权限(无权限)
        $is_all_look = Helper::SALE_NOT_ALL_LOOK;

        // 获取当前活动状态
        $activity_status = $this->activity_status($info['activity_status'], $info['begin_time'],
            $info['end_time']);

        // 判断参与活动权限
        if ($info['is_all'] != ActivityService::IS_ALL) {
            $right_serv = new RightService();
            $right = $right_serv->list_by_conds(['ac_id' => $info['ac_id']]);

            // 如果没有权限
            if (!$right_serv->check_get_quit($right, $user)) {
                // 如果不能围观且没有权限则抛错
                if (Helper::SALE_NOT_ALL_LOOK == $info['is_all_look']) {
                    E('_ERR_NOT_LOOK_SALE_AUTH');
                }
                // 有查看权限
                $is_all_look = Helper::SALE_ALL_LOOK;
                // 没有参与权限
                $is_join_right = Helper::NOT_IS_JOIN_RIGHT;
            }

        }

        return [$activity_status, $is_join_right, $is_all_look];
    }

    /**
     * 格式化后台活动列表数据
     *
     * @param $list
     *
     * @return mixed;
     */
    public function format_list_admin(&$list)
    {

        foreach ($list as &$v) {

            $v['comment_pass_num'] = $this->_d_comment->count_by_conds(
                [
                    'ac_id' => $v['ac_id'],
                    'check_status' => self::CHECK_PASS
                ]
            );
            $v['comment_checking_num'] = $this->_d_comment->count_by_conds(
                [
                    'ac_id' => $v['ac_id'],
                    'check_status' => self::CHECK_ING
                ]
            );
            $v['ac_id'] = intval($v['ac_id']);
            $v['join_num'] = intval($v['join_num']);
            $v['join_total'] = intval($v['join_total']);
            $v['is_all'] = intval($v['is_all']);
            $v['is_red_open'] = intval($v['is_red_open']);
            $v['is_show_red'] = intval($v['is_show_red']);
            $v['is_hidden'] = intval($v['is_hide']);
            $v['is_check_open'] = intval($v['is_check_open']);
            $v['cover_url'] = imgUrlReal($v['cover_id']);
            $v['is_notice'] = intval($v['is_notice']);
            $v['content'] = empty($v['content']) ? $v['content'] : unserialize($v['content']);
            $v['likes'] = intval($v['likes']);
            $v['comments'] = intval($v['comments']);

            // 转换数据状态
            $v['activity_status'] = $this->activity_status($v['activity_status'], $v['begin_time'], $v['end_time']);
        }

        return $list;
    }

    /**
     * 格式化活动列表返回数据(手机端)
     *
     * @param array $list 活动列表
     * @param int $uid 当前用户uid
     *
     * @return array
     */
    public function format_activity_list($list = [], $uid = 0)
    {
        if (empty($list)) {

            return [];
        }

        $ac_ids = array_column($list, 'ac_id');
        // 获取点赞列表数据
        $like_data = $this->_d_like->list_by_conds([
            'obj_id' => $ac_ids,
            'type' => self::LIKE_ACTIVITY_TYPE,
            'uid' => $uid
        ], null, [], 'like_id,obj_id');

        // 我已经点赞的活动id集合
        $back_cid = array_column($like_data, 'obj_id');
        // 要返回的字段
        $arr = [];
        // 去除中文空格
        $search = [" ", " ", "\n", "\r", "\t"];
        $replace = ["", "", "", "", ""];
        foreach ($list as $key => $val) {

            // 组装封面图
            $val['ac_id'] = intval($val['ac_id']);
            if (empty($val['cover_id'])) {
                $val['cover_url'] = '';
            } else {
                $val['cover_url'] = imgUrlReal($val['cover_id']);
            }
            // 组装状态
            $val['activity_status'] = $this->activity_status($val['activity_status'], $val['begin_time'],
                $val['end_time']);

            $val['is_like'] = in_array($val['ac_id'], $back_cid) ? self::IS_LIKE_OK : self::IS_LIKE_NO;
            $val['content'] = str_replace($search, $replace, strip_tags(unserialize($val['content'])));
            $val['likes'] = intval($val['likes']);
            $val['comments'] = intval($val['comments']);

            $arr[$key] = $val;
        }

        return $arr;
    }

    /**
     * 活动状态转化函数
     *
     * @param string $activity_status 活动状态
     * @param string $begin_time 开始时间
     * @param string $end_time 结束时间
     *
     * @return int 活动状态1:草稿,2:未开始,3:进行中,4:已结束,5:已终止
     */
    public function activity_status($activity_status = '0', $begin_time = '0', $end_time = '0')
    {
        if (ActivityModel::ACTIVITY_DRAFT == $activity_status) {
            // 草稿
            $status = Helper::STATUS_DRAFT;
        } elseif (ActivityModel::ACTIVITY_STOP == $activity_status) {
            // 已终止
            $status = Helper::STATUS_STOP;
        } else {
            // 已发布
            if ($begin_time > MILLI_TIME) {
                // 未开始
                $status = Helper::STATUS_NOT_START;
            } elseif ($begin_time <= MILLI_TIME && $end_time > MILLI_TIME) {
                // 进行中
                $status = Helper::STATUS_ING;
            } else {
                // 已结束
                $status = Helper::STATUS_END;
            }
        }

        return $status;
    }

    /**
     *  查询活动信息
     *
     * @param int $ac_id 活动ID
     *
     * @return array|bool 查询结果
     */
    public function activity_info($ac_id = 0)
    {
        //获取活动状态
        $activity = $this->get($ac_id);

        if (empty($activity)) {

            E('_ERR_ARTICLE_NOT_FOUND');
        }
        //转化活动状态
        $activity['activity_status'] = $this->activity_status($activity['activity_status'], $activity['begin_time'],
            $activity['end_time']);

        return $activity;
    }

    /**
     * 前端获取活动列表
     *
     * @param array $params 列表其提交的参数
     * @param array $user 登录用户的信息
     *
     * @return mixed
     */
    public function get_list($params = [], $user = [])
    {
        // 默认值
        $page = !empty($params['page']) ? intval($params['page']) : self::DEFAULT_PAGE;
        $limit = !empty($params['limit']) ? intval($params['limit']) : self::DEFAULT_LIMIT;
        // 分页
        list($start, $limit) = page_limit($page, $limit);

        $right = new RightService();
        // 权限为全公司或者有围观权限的IDS集合
        $ac_ids_all = [];
        // 当前用户有权限的活动参与权限IDS集合(不包含权限为全公司的参与权限IDS)
        $ac_ids_right = [];

        // 1.查询全公司可参与以及全公司可围观的活动id集合
        $is_all_activity_list = $this->get_is_all_look_activity_list();
        if (!empty($is_all_activity_list)) {
            $ac_ids_all = array_column($is_all_activity_list, 'ac_id');
        }

        // 获取当前用户所在部门IDS以及顶级部门IDS集合
        $dp_ids = $right->get_user_dp_list($user);

        // 获取用户标签集合
        $userService = new User();
        $tagsInfo = $userService->getTagsByUserId($user['memUid']);

        $tag_ids = [];
        if (!empty($tagsInfo)) {
            $userTagInfo = isset($tagsInfo['userTagList']) ? array_column($tagsInfo['userTagList'], 'tagId') : [];
            $departTagInfo = isset($tagsInfo['departTagList']) ? array_column($tagsInfo['departTagList'], 'tagId') : [];

            $tag_ids = array_unique(array_merge($userTagInfo, $departTagInfo));
        }

        // 2.查询有权限参与的活动id集合
        $is_right_activity_list = $this->_d_right->get_right_look_activity_list($user['memUid'], $dp_ids,
            $user['job']['jobId'], $user['role']['roleId'], $tag_ids);

        if (!empty($is_right_activity_list)) {
            $ac_ids_right = array_column($is_right_activity_list, 'ac_id');
        }

        // 合并活动id集合
        $ac_ids = array_filter(array_unique(array_merge($ac_ids_all, $ac_ids_right)));

        if (empty($ac_ids)) {

            // 无权限访问任何数据,组装返回数据
            return [
                'total' => 0,
                'limit' => intval($limit),
                'page' => intval($page),
                'list' => []
            ];
        }

        sort($ac_ids);

        // 查询条件:有权限看的活动、不是草稿、并且没有隐藏
        $conds = [
            'ac_id' => $ac_ids,
            'activity_status>?' => self::ACTIVITY_DRAFT,
            'is_hide' => self::CLOSE_ACTIVITY_HIDE
        ];

        // 获取记录总数
        $total = $this->_d->count_by_conds($conds);
        // 获取列表数据
        $list = [];
        if ($total > 0) {
            // 按照发布时间排序
            $order_option = ['publish_time' => 'DESC'];

            $fields = 'ac_id,subject,source,cover_id,begin_time,end_time,content,is_show_red,likes,comments,publish_time,activity_status';

            $list = $this->_d->list_by_conds($conds, [$start, $limit], $order_option, $fields);
        }

        // 组装返回数据
        return [
            'total' => intval($total),
            'limit' => intval($limit),
            'page' => intval($page),
            'list' => $this->format_activity_list($list, $user['memUid']) // 循环格式化返回数据
        ];

    }


    /**
     * 获取全公司可见的活动列表
     * @return array
     */
    public function get_is_all_look_activity_list()
    {
        return $this->_d->get_is_all_look_activity_list();
    }

    /**
     * 更新收藏状态
     *
     * @param string $ids 数据ID,逗号分割的字符串
     *
     */
    public function update_collection($ids)
    {

        $url = rpcUrl('/Public/Rpc/Collection/CollectionUpdate');

        $params = [
            'uid' => '',
            'app' => 'activity',
            'dataId' => $ids
        ];

        $res = \Com\Rpc::phprpc($url)->invoke('Index', $params);

        return $res;
    }

    /**
     * 执行自定义查询SQL语句(安装应用回调时用)
     * @author 侯英才
     *
     * @param string $sql 执行的SQL语句
     *
     * @return mixed
     */
    public function query($sql)
    {
        return $this->_d->query($sql);
    }

    /**
     * 执行自定义非查询SQL语句(安装应用回调时用)
     *
     * @author 侯英才
     *
     * @param string $sql 执行的SQL语句
     *
     * @return mixed
     */
    public function execute($sql)
    {
        return $this->_d->execute($sql);
    }

    /**
     * 处理红包格式intval
     *
     * @param array $array 红包原数组
     *
     * @return array 处理后的数组
     */
    public function red_format($array = [])
    {

        // 格式化红包数据
        $array['id'] = intval($array['id']);
        $array['ac_id'] = intval($array['ac_id']);
        $array['type'] = intval($array['type']);
        $array['red_base_num'] = intval($array['red_base_num']);
        $array['red_get_num'] = intval($array['max_total']);
        unset($array['max_total']);
        $array['status'] = intval($array['status']);
        $array['red_base_num'] = intval($array['red_base_num'] / self::BASENUM_PRO);
        $array['rule_list'] = !empty($array['red_content']) ? unserialize($array['red_content']) : $array['red_content'];

        // 删除无用数据
        unset($array['domain'], $array['status'], $array['updated'], $array['deleted'], $array['red_content'],
            $array['created']);

        return $array;
    }

    /**
     * 管理后台活动已参与列表
     *
     * @param $params
     *
     * @return mixed
     */
    public function list_join($params)
    {

        // 默认值
        $page = !empty($params['page']) ? intval($params['page']) : self::DEFAULT_PAGE;
        $limit = !empty($params['limit']) ? intval($params['limit']) : self::DEFAULT_LIMIT;
        // 分页
        list($start, $limit) = page_limit($page, $limit);

        // 按照发布时间排序
        $order_option = ['created' => 'DESC'];

        // 查询条件:已审核
        $conds = [
            'check_status' => ActivityService::CHECK_PASS,
            'ac_id' => $params['ac_id']
        ];

        $join_list = $this->_d_comment->list_join($conds, [$start, $limit], $order_option);

        foreach ($join_list as $join_k => $join_v) {
            $join_list[$join_k]['memId'] = $join_v['uid'];
        }

        return $join_list;
    }

    /**
     * 通过用户名搜索用户UID
     *
     * @param string $username 用户名称
     *
     * @return array|string
     */
    public function get_username_uid($username = "")
    {
        $uids = [];
        if (!empty($username)) {
            $member = User::instance();
            // 获取用户名对应的用户UID
            $user_list = $member->listAllBasic(['memUsername' => $username]);
            if (!empty($user_list)) {
                $uids = array_column($user_list, 'memUid');
            }
        }

        return !empty($uids) ? $uids : "";
    }

    /**
     * 推荐首页操作
     *
     * @param  int $ac_id 销售活动ID
     * @param  array $activity
     */
    public function send_recommend($ac_id = 0, $activity = [])
    {
        // 暂时不给首页推荐
        return true;
        // 初始化权限
        $send_right = [];
        if (!empty($right)) {
            $send_right = [
                'users' => $right['uids'],
                'departments' => $right['dp_ids'],
                'jobs' => $right['job_ids'],
                'roles' => $right['role_ids'],
                'tags' => $right['tag_ids']
            ];
        }
        $url = rpcUrl('/Public/Rpc/Recommender/ArticleUpdate');
        $data_send = [
            'app' => APP_DIR,
            'dataCategoryId' => '',
            'dataId' => $ac_id,
            'title' => $activity['subject'],
            'summary' => $activity['content'],
            'dataType' => '',
            'endTime' => $activity['end_time'],
            'attachId' => $activity['cover_id'],
            'pic' => imgUrlReal($activity['cover_id']),
            'url' => 'Sale/Frontend/Index/Msg?ac_id=' . $ac_id . '&type=' . self::MSG_TYPE_ACTIVITY,
            'right' => $send_right
        ];

        \Com\Rpc::phprpc($url)->invoke('Index', $data_send);
    }
}