<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\adminapi\logic\notice;

use app\common\enum\notice\NoticeEnum;
use app\common\logic\BaseLogic;
use app\common\model\master_worker_register\MasterWorkerRegister;
use app\common\model\notice\NoticeSetting;
use app\common\model\works\ServiceWork;

/**
 * 通知逻辑层
 * Class NoticeLogic
 * @package app\adminapi\logic\notice
 */
class NoticeLogic extends BaseLogic
{

    /**
     * @notes 查看通知设置详情
     * @param $params
     * @return array
     * @author 段誉
     * @date 2022/3/29 11:34
     */
    public static function detail($params)
    {

        $noticeSetting = NoticeSetting::field('*')->findOrEmpty($params['id'])->toArray();
        if (empty($noticeSetting)) {
            return [];
        }
        if (empty($noticeSetting['system_notice'])) {
            $noticeSetting['system_notice'] = [
                'title' => '',
                'content' => '',
                'status' => 0,
            ];
        }
        $noticeSetting['system_notice']['tips'] = NoticeEnum::getOperationTips(NoticeEnum::SYSTEM, $noticeSetting['scene_id']);
        if (empty($noticeSetting['sms_notice'])) {
            $noticeSetting['sms_notice'] = [
                'template_id' => '',
                'content' => '',
                'status' => 0,
            ];
        }
        $noticeSetting['sms_notice']['tips'] = NoticeEnum::getOperationTips(NoticeEnum::SMS, $noticeSetting['scene_id']);
        if (empty($noticeSetting['oa_notice'])) {
            $noticeSetting['oa_notice'] = [
                'template_id' => '',
                'template_sn' => '',
                'name' => '',
                'first' => '',
                'remark' => '',
                'tpl' => [],
                'status' => 0,
            ];
        }
        $noticeSetting['oa_notice']['tips'] = NoticeEnum::getOperationTips(NoticeEnum::OA, $noticeSetting['scene_id']);
        if (empty($noticeSetting['mnp_notice'])) {
            $noticeSetting['mnp_notice'] = [
                'template_id' => '',
                'template_sn' => '',
                'name' => '',
                'tpl' => [],
                'status' => 0,
            ];
        }
        $noticeSetting['mnp_notice']['tips'] = NoticeEnum::getOperationTips(NoticeEnum::MNP, $noticeSetting['scene_id']);
        $noticeSetting['system_notice']['is_show'] = in_array(NoticeEnum::SYSTEM, explode(',', $noticeSetting['support']));
        $noticeSetting['sms_notice']['is_show'] = in_array(NoticeEnum::SMS, explode(',', $noticeSetting['support']));
        $noticeSetting['oa_notice']['is_show'] = in_array(NoticeEnum::OA, explode(',', $noticeSetting['support']));
        $noticeSetting['mnp_notice']['is_show'] = in_array(NoticeEnum::MNP, explode(',', $noticeSetting['support']));
        $noticeSetting['default'] = '';
        //$noticeSetting['type'] = NoticeEnum::getTypeDesc($noticeSetting['type']);
        $noticeSetting['type'] = $noticeSetting['type'].'';
        $noticeSetting['recipient'] = $noticeSetting['recipient'].'';
        return $noticeSetting;
    }


    /**
     * @notes 通知设置
     * @param $params
     * @return bool
     * @author 段誉
     * @date 2022/3/29 11:34
     */
    public static function set($params)
    {
        try {
            // 校验参数
            //self::checkSet($params);

            // 拼装更新数据
            $updateData = [];
            $updateData['scene_id'] = $params['scene_id'];
            $updateData['scene_name'] = $params['scene_name'];
            $updateData['scene_desc'] = $params['scene_desc'];
            $updateData['recipient'] = $params['recipient'];
            $updateData['designated_user'] = $params['designated_user'];
            $updateData['type'] = $params['type'];
            $updateData['support'] = $params['support']??2;
            foreach ($params['template'] as $item) {
                if($item['type']??0) $updateData[$item['type'] . '_notice'] = json_encode($item, JSON_UNESCAPED_UNICODE);
            }
        
            $noticeSetting = NoticeSetting::findOrEmpty($params['id'] ?? 0);
            if ($noticeSetting->isEmpty()) {
                $noticeSetting->save($updateData);
                return true;
            }
            // 更新通知设置
            NoticeSetting::where('id', $params['id'])->update($updateData);
            return true;
        } catch (\Exception $e) {
            self::setError($e->getMessage());
            return false;
        }
    }


    /**
     * @notes 校验参数
     * @param $params
     * @throws \Exception
     * @author 段誉
     * @date 2022/3/29 11:35
     */
    public static function checkSet($params)
    {
        $noticeSetting = NoticeSetting::findOrEmpty($params['id'] ?? 0);

        if ($noticeSetting->isEmpty()) {
            throw new \Exception('通知配置不存在');
        }

        if (!isset($params['template']) || !is_array($params['template']) || count($params['template']) == 0) {
            throw new \Exception('模板配置不存在或格式错误');
        }

        // 通知类型
        $noticeType = ['system', 'sms', 'oa', 'mnp'];

        foreach ($params['template'] as $item) {
            if (!is_array($item)) {
                throw new \Exception('模板项格式错误');
            }

            if (!isset($item['type']) || !in_array($item['type'], $noticeType)) {
                throw new \Exception('模板项缺少模板类型或模板类型有误');
            }

            switch ($item['type']) {
                case "system";
                    self::checkSystem($item);
                    break;
                case "sms";
                    self::checkSms($item);
                    break;
                case "oa";
                    self::checkOa($item);
                    break;
                case "mnp";
                    self::checkMnp($item);
                    break;
            }
        }
    }


    /**
     * @notes 校验系统通知参数
     * @param $item
     * @throws \Exception
     * @author 段誉
     * @date 2022/3/29 11:35
     */
    public static function checkSystem($item)
    {
        if (!isset($item['title']) || !isset($item['content']) || !isset($item['status'])) {
            throw new \Exception('系统通知必填参数：title、content、status');
        }
    }


    /**
     * @notes 校验短信通知必填参数
     * @param $item
     * @throws \Exception
     * @author 段誉
     * @date 2022/3/29 11:35
     */
    public static function checkSms($item)
    {
        if (!isset($item['template_id']) || !isset($item['content']) || !isset($item['status'])) {
            throw new \Exception('短信通知必填参数：template_id、content、status');
        }
    }


    /**
     * @notes 校验微信模板消息参数
     * @param $item
     * @throws \Exception
     * @author 段誉
     * @date 2022/3/29 11:35
     */
    public static function checkOa($item)
    {
        if (!isset($item['template_id']) || !isset($item['template_sn']) || !isset($item['name']) || !isset($item['first']) || !isset($item['remark']) || !isset($item['tpl']) || !isset($item['status'])) {
            throw new \Exception('微信模板消息必填参数：template_id、template_sn、name、first、remark、tpl、status');
        }
    }


    /**
     * @notes 校验微信小程序提醒必填参数
     * @param $item
     * @throws \Exception
     * @author 段誉
     * @date 2022/3/29 11:35
     */
    public static function checkMnp($item)
    {
        if (!isset($item['template_id']) || !isset($item['template_sn']) || !isset($item['name']) || !isset($item['tpl']) || !isset($item['status'])) {
            throw new \Exception('微信模板消息必填参数：template_id、template_sn、name、tpl、status');
        }
    }

    public static function getInformation($params)
    {
        try {
            $noticeInfo = [
                'confirm_code' => 0,
                'massage' => '',
                'to_router' => '',
            ];
            /*if(!in_array($adminId,[1,2])){
                return $noticeInfo;
            }*/
            //$params['business_code']
            switch ($params['business_code']){
                case 'service_work':
                    // 用户下单待派单 service_status
                    $serviceWorkCount = ServiceWork::where('work_status', 0)->where('service_status','<', 3)->where('work_pay_status','>', 0)->count('id');
                    if($serviceWorkCount){
                        $noticeInfo['confirm_code'] = 101;
                        $noticeInfo['count'] = $serviceWorkCount;
                        $noticeInfo['massage'] .= '您有'.$serviceWorkCount.'个工单待派单';
                        $noticeInfo['to_router'] = '/works/service_work';
                    }
                    break;
                case 'work_status_receive':
                    // 用户下单待派单 service_status
                    $serviceWorkCount = ServiceWork::where('work_status', 1)->where('work_pay_status','>', 0)->count('id');
                    if($serviceWorkCount){
                        $noticeInfo['confirm_code'] = 101;
                        $noticeInfo['count'] = $serviceWorkCount;
                        $noticeInfo['massage'] .= '您有'.$serviceWorkCount.'个工单待领单';
                        $noticeInfo['to_router'] = '/works/service_work';
                    }
                    break;
                case 'work_status_contact':
                    // 用户下单待派单 service_status
                    $serviceWorkCount = ServiceWork::where('work_status', 2)->where('work_pay_status','>', 0)->count('id');
                    if($serviceWorkCount){
                        $noticeInfo['confirm_code'] = 101;
                        $noticeInfo['count'] = $serviceWorkCount;
                        $noticeInfo['massage'] .= '您有'.$serviceWorkCount.'个工单待联系';
                        $noticeInfo['to_router'] = '/works/service_work';
                    }
                    break;
                case 'worker_register':
                    // 工程师入驻待审核
                    $workerRegisterCount = MasterWorkerRegister::where('status', 0)->count('id');
                    if($workerRegisterCount){
                        $noticeInfo['confirm_code'] = 101;
                        $noticeInfo['count'] = $workerRegisterCount;
                        $noticeInfo['massage'] .= '您有'.$workerRegisterCount.'个工程师入驻待审核';
                        $noticeInfo['to_router'] = '/worker/master_worker_register?master_worker_register.master_worker_register/lists';
                    }
                    break;
                case 'appoint_approval':
                    // 用户更新工单上门时间超过15分钟工程师未确认
                    $serviceWorkCount = ServiceWork::where('appoint_approval', 1)->where('refund_approval','=',0)->where('work_pay_status','>',0)->where('update_time','<', time()-15*60)->count('id');
                    if($serviceWorkCount){
                        $noticeInfo['confirm_code'] = 101;
                        $noticeInfo['count'] = $serviceWorkCount;
                        $noticeInfo['massage'] .= '您有'.$serviceWorkCount.'个工单超过15分钟工程师未确认新上门时间';
                        $noticeInfo['to_router'] = '/works/service_work';
                    }
                    break;
                case 'refund_approval':
                    // 用户退款状态审核中
                    $serviceWorkCount = ServiceWork::where('refund_approval', 1)->where('work_pay_status','>',0)->count('id');
                    if($serviceWorkCount){
                        $noticeInfo['confirm_code'] = 101;
                        $noticeInfo['count'] = $serviceWorkCount;
                        $noticeInfo['massage'] .= '您有'.$serviceWorkCount.'个工单退款审核中';
                        $noticeInfo['to_router'] = '/works/service_work';
                    }
                    break;
            }
            return $noticeInfo;
        } catch (\Exception $e) {
            self::setError($e->getMessage());
            return false;
        }
    }
    public static function getInformationBatch($params)
    {
        try {
            $res = [];
            $params['business_codes'] = explode(',',$params['business_codes']);
            foreach ($params['business_codes'] as $business_code) {
                $noticeInfo = self::getInformation(['business_code'=>$business_code]);
                if($noticeInfo['confirm_code'] == 101){
                    $res[$business_code] = $noticeInfo['count'];
                }else{
                    $res[$business_code] = 0;
                }
            }
            return $res;
        } catch (\Exception $e) {
            self::setError($e->getMessage());
            return false;
        }
    }

}