<?php
/**
 * 代办事项
 */

namespace Apicp\Controller\HomePage;

use Common\Common\Answer;
use Common\Common\Cache;
use Common\Common\Contact;
use Common\Common\Exam;
use Common\Common\Integral;
use Common\Common\Train;
use Common\Common\Workmate;
use Common\Service\CommonAgencyRecordService;
use VcySDK\AdminerRole;
use VcySDK\EnterprisePlugin;
use VcySDK\Member;
use VcySDK\Service;

class AgencyMattersController extends AbstractController
{
    protected $_require_login = false;

    /**
     * @var array 当前管理员有权限的目录
     */
    protected $_cp_menu = [];

    /**
     * @var int 当前管理员类型(1=系统管理员;2=用户自定义)
     */
    protected $_ear_type;

    /**
     * @var array 关闭的代办事项(没有app_data_id的待办事项)
     */
    protected $_close_action = [];

    /**
     * 代办事项:完善企业信息
     */
    const ACTIVE_IS_COMPLETE_EP_INFO = 'completeEpInfo';
    /**
     * 代办事项:获取人员未关注数量
     */
    const ACTIVE_IS_NOT_CONCERNED = 'notConcerned';
    /**
     * 代办事项:问答待审核
     */
    const ACTIVE_IS_APPROVAL_ANSWER = 'approvalAnswer';
    /**
     * 代办事项:邀请待审核
     */
    const ACTIVE_IS_APPROVAL_INVITE = 'approvalInvite';
    /**
     * 代办事项:话题待审核
     */
    const ACTIVE_IS_APPROVAL_WORKMATE = 'approvalWorkmate';
    /**
     * 代办事项:积分待审核
     */
    const ACTIVE_IS_APPROVAL_INTEGRAL_CONVERT = 'approvalIntegralConvert';
    /**
     * 代办事项:企业培训报名待审核
     */
    const ACTIVE_IS_APPROVAL_TRAIN_SIGN_UP = 'approvalTrainSignUp';
    /**
     * 代办事项:考试待批阅
     */
    const ACTIVE_IS_NEED_READING_PAPER = 'needReadingPaper';

    public function index()
    {
        // 关闭的代办事项(没有app_data_id的待办事项)
        $agencyRecordServ = new CommonAgencyRecordService();
        $actionList = $agencyRecordServ->list_by_conds([
            'app_data_id' => 0,
            'ea_id' => $this->_login->user['eaId']]);
        $this->_close_action = empty($actionList) ? [] : array_column($actionList, 'agency_action');

        // 考试待批阅
        $this->needReadingPaper();
        // 企业培训报名审核
        $this->approvalTrainSignUp();
        // 积分兑换待审核
        $this->approvalIntegralConvert();
        // 帖子待审核
        $this->approvalWorkmate();
        // 话题待审核
        $this->approvalTopic();
        // 邀请待审核
        $this->approvalInvite();
        // 问答待审核
        $this->approvalAnswer();
        // 企业信息是否完善
        $this->checkCompleteEpInfo();
        // 未加入人员数量
        $this->notConcerned();

        return true;
    }

    /**
     * 企业信息是否完善
     */
    private function checkCompleteEpInfo()
    {
        // 代办事项是否被关闭
        if (in_array(self::ACTIVE_IS_COMPLETE_EP_INFO, $this->_close_action)) {
            return true;
        }

        // 需要完善企业信息
        $needCompleteEpInfo = false;

        $epDetail = Cache::instance()->get('Common.EnterpriseDetail', '', ['expire' => 300]);
        // 看那个字段没有填写
        foreach (
            array_intersect_key($epDetail, array_fill_keys([
                'corpName',
                'epIndustry',
                'epCompanysize',
                'epContacter',
                'epContactmobile',
                'epContactemail',
                'epPostalCode',
                'epAddress',
            ], '')) as $item
        ) {
            if (empty($item)) {
                $needCompleteEpInfo = true;
            }
        };
        // 另外判断地区
        if (empty($epDetail['epArea']) && empty($epDetail['epCity']) && empty($epDetail['epProvince'])) {
            $needCompleteEpInfo = true;
        }

        if ($needCompleteEpInfo) {
            $this->_result[] = [
                'id' => self::ACTIVE_IS_COMPLETE_EP_INFO,
                'message' => '【企业信息】尚未完善企业账户信息,立即前往设置',
                'url' => admincpUrl('/admincp/#/c/system-settings/account-info'),
            ];
        }

        return true;
    }

    /**
     * 获取人员未关注数量
     * @return bool
     */
    private function notConcerned()
    {
        // 代办事项是否被关闭
        if (in_array(self::ACTIVE_IS_NOT_CONCERNED, $this->_close_action)) {
            return true;
        }

        // 企业应用
        $enterprisePluginSdk = new EnterprisePlugin(Service::instance());
        $pluginList = $enterprisePluginSdk->listAll();
        $pluginList = array_combine_by_key($pluginList, 'plIdentifier');
        // 人员状态
        $memberSdk = new Member(Service::instance());
        $memberDetail = $memberSdk->memberStatusCount([]);

        // 有人没关注
        if ($memberDetail['notConcerned'] > 0 &&
            // 通讯录开启的
            ($pluginList['contact']['available'] == EnterprisePlugin::AVAILABLE_OPEN) &&
            // 有邀请人员权限 或者 超级管理员
            $this->checkRight('member-invite')
        ) {
            $this->_result[] = [
                'id' => self::ACTIVE_IS_NOT_CONCERNED,
                'message' => "【员工管理】有{$memberDetail['notConcerned']}名员工尚未加入,立即前往邀请",
                'url' => admincpUrl('/admincp/#/c/contacts/employee-contract')
            ];
        }

        return true;
    }

    /**
     * 待审核问答
     * @author tangxingguo
     * @return bool
     */
    public function approvalAnswer()
    {
        // 代办事项是否被关闭
        if (in_array(self::ACTIVE_IS_APPROVAL_ANSWER, $this->_close_action)) {
            return true;
        }

        // 管理员是否有权限
        if (!$this->checkRight('answer-list')) {
            return true;
        }

        // 待审核的提问数量
        $answer = &Answer::instance();
        $count = $answer->getAnswerCount(['check_status' => Answer::QUESTION_CHECK_STATUS_WAIT]);

        if ($count > 0) {
            $this->_result[] = [
                'id' => self::ACTIVE_IS_APPROVAL_ANSWER,
                'message' => "【问答审核】有{$count}条问答待审核,点击立即前往",
                'url' => admincpUrl('/admincp/#/c/my-app/answer-center')
            ];
        }

        return true;
    }

    /**
     * 待审核邀请人员
     * @author tangxingguo
     * @return bool
     */
    public function approvalInvite()
    {
        // 代办事项是否被关闭
        if (in_array(self::ACTIVE_IS_APPROVAL_INVITE, $this->_close_action)) {
            return true;
        }

        // 管理员是否有权限
        if (!$this->checkRight('member-invite')) {
            return false;
        }

        // 待审核的邀请数量
        $contact = &Contact::instance();
        $count = $contact->getNeedInviteCount([
            'check_status' => Contact::CHECK_STATUS_WAIT,
            'type' => Contact::INVITE_TYPE_APPROVAL
        ]);

        if ($count > 0) {
            $this->_result[] = [
                'id' => self::ACTIVE_IS_APPROVAL_INVITE,
                'message' => "【用户审核】有{$count}名员工邀请待审核,点击立即前往",
                'url' => admincpUrl('/admincp/#/c/contacts/invite')
            ];
        }

        return true;
    }

    /**
     * 待审核帖子
     * @author tangxingguo
     * @return bool
     */
    public function approvalWorkmate()
    {
        // 代办事项是否被关闭
        if (in_array(self::ACTIVE_IS_APPROVAL_WORKMATE, $this->_close_action)) {
            return true;
        }

        // 管理员是否有权限
        if (!$this->checkRight('workmate-list')) {
            return false;
        }

        $workmateServ = &Workmate::instance();
        $count = $workmateServ->getWorkmateCount(['audit_state' => Workmate::CHECK_STATUS_WAIT, 'type' =>Workmate::CIRCLE_NOTE_TYPE, 'pid' => Workmate::CIRCLE_PID_TYPE]);

        if ($count > 0) {
            $this->_result[] = [
                'id' => self::ACTIVE_IS_APPROVAL_WORKMATE,
                'message' => "【同事圈帖子审核】有{$count}条同事圈帖子待审核,点击立即前往",
                'url' => admincpUrl('/admincp/#/c/my-app/workmate')
            ];
        }

        return true;
    }

    /**
     * 待审核话题
     * @author tangxingguo
     * @return bool
     */
    public function approvalTopic()
    {
        // 代办事项是否被关闭
        if (in_array(self::ACTIVE_IS_APPROVAL_WORKMATE, $this->_close_action)) {
            return true;
        }

        // 管理员是否有权限
        if (!$this->checkRight('workmate-list')) {
            return false;
        }

        $workmateServ = &Workmate::instance();
        $count = $workmateServ->getWorkmateCount(['audit_state' => Workmate::CHECK_STATUS_WAIT, 'type' =>Workmate::CIRCLE_TOPIC_TYPE, 'pid' => Workmate::CIRCLE_PID_TYPE]);

        if ($count > 0) {
            $this->_result[] = [
                'id' => self::ACTIVE_IS_APPROVAL_WORKMATE,
                'message' => "【同事圈话题审核】有{$count}条同事圈话题待审核,点击立即前往",
                'url' => admincpUrl('/admincp/#/c/my-app/workmate/workmate-topic')
            ];
        }

        return true;
    }

    /**
     * 待审核积分兑换
     * @author tangxingguo
     * @return bool
     */
    public function approvalIntegralConvert()
    {
        // 代办事项是否被关闭
        if (in_array(self::ACTIVE_IS_APPROVAL_INTEGRAL_CONVERT, $this->_close_action)) {
            return true;
        }

        // 管理员是否有权限
        if (!$this->checkRight('integral')) {
            return false;
        }

        $integral = &Integral::instance();
        $count = $integral->getIntegralConvertCount(['convert_status' => Integral::CONVERT_STATUS_IS_WAIT]);

        if ($count > 0) {
            $this->_result[] = [
                'id' => self::ACTIVE_IS_APPROVAL_INTEGRAL_CONVERT,
                'message' => "【积分商城审核】有{$count}个兑换商品待审核,点击立即前往",
                'url' => admincpUrl('/admincp/#/c/my-app/integral/integral-mall/exchange-manage')
            ];
        }
        return true;
    }


    /**
     * 待审核企业培训报名
     * @author tangxingguo
     */
    public function approvalTrainSignUp()
    {
        // 管理员是否有权限
        if (!$this->checkRight('train')) {
            return false;
        }

        // 需要审核的未过期的企业培训
        $train = &Train::instance();
        $trainList = $train->getEducationList([
            // 培训截止时间
            'ed_end_time > ?' => MILLI_TIME,
            // 开启了报名
            'ed_is_sign_up' => Train::SIGN_OPEN,
            // 开启了审核
            'ed_is_check' => Train::CHECK
        ]);
        if (empty($trainList)) {
            return false;
        }
        $trainIds = array_column($trainList, 'ed_id');

        // 已经关闭的待办事项
        $agencyRecordServ = new CommonAgencyRecordService();
        $closeList = $agencyRecordServ->list_by_conds([
            'agency_action' => self::ACTIVE_IS_APPROVAL_TRAIN_SIGN_UP,
            'ea_id' => $this->_login->user['eaId'],
            'app_data_id' => $trainIds
        ]);
        $closeIds = empty($closeList) ? [] : array_column($closeList, 'app_data_id');

        // 需要待办的事项(需要审核 与 关闭 差集)
        $ids = array_diff($trainIds, $closeIds);

        // 待审核的报名
        $countUids = $train->countRightUserList($ids);
        if (!empty($countUids)) {
            foreach ($countUids as $v) {
                $params = [
                    'ed_id' => $v['ed_id'],
                ];
                $this->_result[] = [
                    'id' => self::ACTIVE_IS_APPROVAL_TRAIN_SIGN_UP,
                    'app_data_id' => $v['ed_id'],
                    'message' => "【企业培训审核】有{$v['count']}个报名待审核,点击立即前往",
                    'url' => admincpUrl("/admincp/#/c/my-app/train/train-detail", $params)
                ];
            }
        }

        return true;
    }

    /**
     * 考试待批阅
     * @author tangxingguo
     * @return bool
     */
    public function needReadingPaper()
    {
        // 管理员是否有权限
        if (!$this->checkRight('exam')) {
            return false;
        }

        // 需要阅卷的考试
        $exam = &Exam::instance();
        $readingList = $exam->getNeedReadingList();
        if (empty($readingList)) {
            return false;
        }

        // 试卷ID
        $epIds = array_column($readingList, 'ep_id');

        // 已关闭的待办
        $agencyRecordServ = new CommonAgencyRecordService();
        $closeList = $agencyRecordServ->list_by_conds([
            'agency_action' => self::ACTIVE_IS_NEED_READING_PAPER,
            'ea_id' => $this->_login->user['eaId'],
            'app_data_id' => $epIds
        ]);
        $closeIds = empty($closeList) ? [] : array_column($closeList, 'app_data_id');

        // 需要待办的事项(需要审核 与 关闭 差集)
        $ids = array_diff($epIds, $closeIds);

        // 考试信息
        $paperList = $exam->getPaperList(['ep_id' => $ids]);
        if (!empty($paperList)) {
            $paperList = array_combine_by_key($paperList, 'ep_id');
        }

        if (!empty($ids)) {
            foreach ($readingList as $v) {
                // 事项没有被关闭 & 考试没有被删除
                if (in_array($v['ep_id'], $ids) && isset($paperList[$v['ep_id']])) {
                    $params = [
                        'ep_id' => $v['ep_id']
                    ];
                    $this->_result[] = [
                        'id' => self::ACTIVE_IS_NEED_READING_PAPER,
                        'app_data_id' => $v['ep_id'],
                        'message' => "【{$paperList[$v['ep_id']]['ep_name']}】有{$v['count']}名员工试卷待批阅,点击立即前往",
                        'url' => admincpUrl("/admincp/#/c/my-app/exam/exam-paper-detail", $params)
                    ];
                }
            }
        }
        return true;
    }

    /**
     * 检查权限
     * @author tangxingguo
     * @param string $appItem 应用目录
     * @return bool
     */
    public function checkRight($appItem)
    {
        // 当前管理员有权限的目录以及管理员类型
        $this->getCpMenu();

        // 有权限 或者 超级管理员
        if (array_key_exists($appItem, $this->_cp_menu) || $this->_ear_type == AdminerRole::ROLE_TYPE_SYS) {
            return true;
        }
        return false;
    }

    /**
     * 获取当前管理员有权限的目录以及管理员类型
     * @author tangxingguo
     */
    protected function getCpMenu()
    {
        if (empty($this->_cp_menu) || empty($this->_ear_type)) {
            $sdkRole = new AdminerRole(Service::instance());
            $role = $sdkRole->detail([
                'earId' => $this->_login->user['earId'],
                'eaId' => $this->_login->user['eaId']
            ]);
            $this->_cp_menu = !is_null($role['earCpmenu']) ? json_decode($role['earCpmenu'], true) : [];
            $this->_ear_type = $role['earType'];
        }
    }
}