AddController.class.php 9.84 KB
<?php
/**
 * 【调研中心-手机端】05_填写调研
 * AddController.class.php
 * CreateBy:daijun
 * Date:2017-03-13
 */

namespace Api\Controller\Record;

use Common\Common\AttachOperation;
use Common\Common\StudyMap;
use Common\Common\Train;
use Common\Common\TaskCenter;
use Common\Common\Integral;
use Common\Service\AnswerService;
use Common\Service\BaseinfoService;
use Common\Service\QuestionService;
use Common\Service\RecordService;

class AddController extends \Api\Controller\AbstractController
{

    // 免登录
    protected $_require_login = false;

    /**
     * @return bool
     * @throws \VcySDK\Exception
     * @throws \Exception
     */
    public function Index()
    {

        // 调研id
        $qu_id = I('post.qu_id', 0, 'intval');
        // 调研id为空:调研ID不能为空
        if (empty($qu_id)) {

            E('_EMPTY_BASEINFO_ID');
        }

        // 调研问题答案列表
        $q_list = I('post.q_list');
        // 答案列表为空:调研问题列表信息不能为空
        if (empty($q_list)) {

            E('_EMPTY_BASEINFO_LIST');
        }

        // 实例化调研基本信息Service
        $base_info_s = new BaseinfoService();
        // 调研基本信息
        $data = $base_info_s->get($qu_id);

        // 查询的调研基本信息为空:调研信息不存在
        if (empty($data)) {

            E('_ERR_BASEINFOID_NO_EXISTENT');
        }

        // 常规类型并且调研已截止:调研已截止
        if (BaseinfoService::ROUTINE_TYPE == $data['qu_type'] && $data['deadline'] <= MILLI_TIME) {

            E('_ERR_BASEINFO_DEADLINE');
        }

        $openid = '';
        $uid = $this->uid;
        if (empty($uid)) {

            $openid = $this->_login->openid;
        }

        // 任务id
        $task_id = I('post.customtask_id', 0, 'intval');
        // 培训计划id
        $plan_id = I('post.plan_id', 0, 'intval');
        // 学习地图
        $map_id = I('post.map_id', 0, 'intval');
        $path_id = I('post.path_id', 0, 'intval');

        $obj_id = 0;
        if (BaseinfoService::TASK_TYPE == $data['qu_type'] && $task_id) {

            $obj_id = $task_id;
        } elseif (BaseinfoService::OFF_LINE_TYPE == $data['qu_type'] && $plan_id) {

            $obj_id = $plan_id;
        }

        if (BaseinfoService::OTHER_TYPE == $data['qu_type'] && $map_id && $path_id) {
            $obj_id = $map_id;
        }

        // 实例化调研回答记录信息Service
        $answer_s = new AnswerService();

        // 组装查询条件
        $condition = [
            'uid' => $uid,
            'openid' => $openid,
            'qu_id' => $qu_id,
            'data_type' => $data['qu_type'],
            'obj_id' => rintval($obj_id)
        ];
        // 查询之前的回答记录
        $answer_list = $answer_s->list_by_conds($condition);

        //  回答记录不为空:你已填写过该调研不可重复填写
        if (!empty($answer_list)) {

            E('_ERR_CANNOT_FILL_IN');
        }

        // 积分策略ID
        $businessid = $qu_id;
        // 积分策略返回值
        $score_list = [];
        // 实例化调研回复详情记录表Service
        $record_s = new RecordService();
        // 实例化调研问题信息表Service
        $question_s = new QuestionService();

        try {
            // 开始事务
            $base_info_s->start_trans();

            // 更新调研主表参与人数
            $involved_num = rintval($data['involved_num']) + 1;
            $base_info_s->update($qu_id, ['involved_num' => $involved_num]);

            // 调研外部用户参与人数
            $outside_num = $answer_s->count_by_conds(['qu_id' => $qu_id, 'uid' => '']);

            // 外部用户微信昵称
            $username = '';

            // 用户uid不为空
            if ($uid) {
                // 调用积分策略
                $score_list = $this->get_score_action($data['integral_action_type'], $uid, $businessid, $data['credit_action_type']);
            } else {

                $username = '外部用户' . ($outside_num + 1);
            }

            // 组装回答表入库数据
            $answer_user = [
                'qu_id' => $qu_id,
                'uid' => $uid,
                'openid' => $openid,
                'username' => $username,
                'businessid' => $businessid,
                'data_type' => intval($data['qu_type']),
                'obj_id' => rintval($obj_id)
            ];

            // 插入用户回答信息表
            $a_id = $answer_s->insert($answer_user);

            list($answer_data, $attach_ids) = $question_s->check_answer($qu_id, $a_id, $q_list);
            // 验证问题及答案信息并组装入库数据
            if (!$answer_data) {

                return false;
            }

            // 插入答题记录表
            $record_s->insert_all($answer_data);

            // 提交事务
            $base_info_s->commit();
        } catch (\Think\Exception $e) {

            \Think\Log::record($e);
            // 事务回滚
            $this->_set_error($e->getMessage(), $e->getCode());
            $base_info_s->rollback();
        } catch (\Exception $e) {

            \Think\Log::record($e);
            $this->_set_error($e->getMessage(), $e->getCode());
            // 事务回滚
            $base_info_s->rollback();
        }

        // 格式化返回的积分策略数据
        $integral = [];
        if (!empty($score_list)) {

            foreach ($score_list as $v) {

                if ('SUCCESS' == $v['result']) {

                    $integral[] = [
                        'content' => '积分',
                        'number' => intval($v['score'])
                    ];
                }
            }
        }

        // 常规任务埋点:参与调研
        if (BaseinfoService::TASK_TYPE == $data['qu_type'] && $task_id) {

            $params = [
                'uid' => $uid,
                'customtask_id' => $task_id,
                'app_data_id' => $qu_id,
                'action_key' => 'questionnaire_join',
                'description' => '参与调研'
            ];

            $taskCenter = &TaskCenter::instance();
            $taskCenter->triggerCustomtask($params);
        }

        // 同步培训完成状态
        if (BaseinfoService::OFF_LINE_TYPE == $data['qu_type'] && $plan_id) {

            $Train = &Train::instance();
            $Train->syncTrainStatus($plan_id, $qu_id);
        }

        // 通知学习地图,应用数据已完成
        if (BaseinfoService::OTHER_TYPE == $data['qu_type'] && $map_id && $path_id) {
            $mapService = new StudyMap($map_id);
            // 验证权限
            $mapService->checkRight($path_id, $qu_id, $this->_login->user);
            // 通知为已完成
            $mapService->studyContent($path_id, $qu_id, $this->_login->user);
        }

        // 附件处理
        if (!empty($attach_ids)) {
            $attach_serv = new AttachOperation();
            $attach_serv->insert_attach(
                APP_DIR,
                'baseinfo',
                $qu_id,
                ['attach_ids' => $attach_ids]
            );
        }

        $this->_result = ['score_list' => $integral];

        return true;
    }

    /**
     * 调用积分策略
     *
     * @param int $integral_action_type 启用状态 1:启用默认,2:不启用
     * @param string $uid 用户ID
     * @param int $businessid 积分策略ID
     * @param int $credit_action_type 启用状态 1:启用默认,2:不启用
     * @return array|mixed
     */
    private function get_score_action($integral_action_type = 1, $uid = '', $businessid = 0, $credit_action_type = 1)
    {
        // 积分策略返回值
        $score_list = [];

        // 初始化积分策略
        $Integral = new Integral();

        // 用户uid不为空
        if (!empty($uid)) {
            // 组装策略请求参数
            $param = [
                'memUid' => $uid,
                'msgIdentifier' => APP_IDENTIFIER,
                'businessKey' => 'research_center',
                'businessAct' => 'join',
                'businessId' => $businessid,
                'triggers' => [],
            ];

            // 积分策略启用
            if (BaseinfoService::INTEGRAL_ACTION_TYPE_NO != $integral_action_type) {
                // 组装积分策略请求参数
                $param['triggers'][] = [
                    'miType' => 'mi_type0',
                    'businessStrategyId' => '',
                    'triggerTypes' => [
                        [
                            'triggerKey' => 'number',
                            'value' => 1,
                            'remark' => '参加调研'
                        ]
                    ],
                ];
            }

            // 学分策略启用
            if (BaseinfoService::CREDIT_ACTION_TYPE_NO != $credit_action_type) {
                // 组装学分策略请求参数
                $param['triggers'][] = [
                    'miType' => 'mi_type1',
                    'businessStrategyId' => '',
                    'triggerTypes' => [
                        [
                            'triggerKey' => 'number',
                            'value' => 1,
                            'remark' => '参加调研'
                        ]
                    ],
                ];
            }

            // 触发学分策略
            if (!empty($param['triggers'])) {
                $score_list = $Integral->changeScore($param);
            }
        }

        return $score_list;
    }
}