<?php

namespace App\Models;

use Carbon\Carbon;
use Illuminate\Support\Facades\Log;

class Notification extends BaseModel
{
    public static function send($order_id, $overdue = false)
    {
        $order = Order::find($order_id);
        if(!$order) return false;
        if($order['is_draft'] == 1) return false;
        $checked_id = Option::get('orders', 'status', 'checked');
        $reject_id = Option::get('orders', 'status', 'reject');
        $pass_id = Option::get('orders', 'status', 'pass');
        $back_id = Option::get('orders', 'status', 'back');
        $last_role = ProjectRole::find($order['last_project_role_id']);
        $role = ProjectRole::find($order['project_role_id']);
        $status = 1;
        $user_ids = [];
        $project_role_ids = ProjectRole::where('level', $order['level'])->pluck('id');
        if($overdue) {
            // 调用时间到期
            $role = ProjectRole::getFirstRole($order);
            $project_role_ids = [$role['id']];
        } else if($order['status'] == $pass_id) {
            // 租赁完成，调用完成
            if($order['type'] == 1) {
                // 租赁完成
                $project_role_ids = ProjectRole::whereIn('key', ['manager'])->pluck('id');
            } else if($order['is_change' == 2]) {
                // 调用完成且未修改
                $project_role_ids = ProjectRole::whereIn('key', ['admin'])->pluck('id');
            } else {
                // 调用完成且修改
                $project_role_ids = ProjectRole::whereIn('key', ['admin'])->pluck('id');
            }
        } else if($order['status'] == $back_id) {
            $project_role_ids = ProjectRole::whereIn('key', ['admin'])->pluck('id');
        }

        if($overdue) {
            $project_role_ids = ProjectRole::whereIn('key', ['machine', 'admin'])->pluck('id');
        }
        if(count($project_role_ids) > 0) {
            $user_ids = ProjectUser::where([
                ['project_id', $order['project_id']]
            ])->whereIn('project_role_id', $project_role_ids)->pluck('user_id');
        }
        // 外部租赁
        if($order['type'] == 1) {
            // 审批成功
            if($order['status'] == $checked_id && $last_role && $last_role['key'] == 'manager') {
                $status = 1;
            } else if($role && in_array($role['key'], ['machine', 'assist', 'manager'])) {
                // 审批待处理
                $status = 2;
            } else if($order['status'] == $reject_id) {
                // 审批被驳回
                $status = 3;
            } else if($order['status'] == $pass_id) {
                // 租赁已完成
                $status = 5;
            }
        } else {
            // 调用
            // 调用成功
            if($order['status'] == $checked_id && $role && $last_role && in_array($last_role['key'], ['admin', 'sub'])) {
                $status = $order['is_change'] == 1 ? 7 : 1;
            } else if($order['status'] == $reject_id) {
                // 调用被驳回
                $status = 3;
            } else if($order['status'] == $pass_id) {
                // 调用已完成，主动退回
                $status = 6;
            } else if($order['status'] == $back_id) {
                // 调用已归还
                $status = 6;
            } else if($order['is_change'] == 1) {
                // 调用修改通知
                $status = 7;
            } else if($role && in_array($role['key'], ['assist', 'manager', 'sub', 'admin'])) {
                // 调用待处理
                $status = 2;
            }
        }
        // 调用时间到期，发送调用完成通知 status = 5
        if($overdue) {
            $status = 5;
        }
        foreach($user_ids as $user_id) {
            $data = [
                'user_id' => $user_id,
                'order_id' => $order['id'],
                'status' => $status,
                'type' => $order['type'],
                'is_read' => 2
            ];
            self::createAndSend($data);
        }
        return true;
    }

    /**
     * 租赁时间到期 status = 4
     * @param $id
     * @return bool
     */
    public static function sendOverdue($id)
    {
        $order = self::find($id);
        if(!$order) return false;
        $role = $order->type == 1 ? $role = ProjectRole::getByKey('work') : ProjectRole::getByKey('machine');
        $user_ids = ProjectUser::where([
            ['project_id', $order['project_id']],
            ['project_role_id', $role['id']]
        ])->pluck('user_id');
        foreach($user_ids as $user_id) {
            $data = [
                'user_id' => $user_id,
                'order_id' => $order['id'],
                'status' => 4,
                'type' => $order['type'],
                'is_read' => 2
            ];
            self::createAndSend($data);
        }
        return false;
    }

    public static function createAndSend($data)
    {
        $item = Notification::create($data);
        $item->sendOfficialInfo();
    }

    public function sendOfficialInfo()
    {
        $content = $this->getNameContent();
        $user = User::find($this['user_id']);
        $official_app = app('wechat.mini_program.default');
        if($content && isset($content['official']) && $user && $user['open_id']) {
            $info = $content['official'];
            $res = $official_app->uniform_message->send([
                'touser' => $user['open_id'],
                'mp_template_msg' => [
                    'appid'=>env('WECHAT_OFFICIAL_ACCOUNT_APPID'),
                    'template_id' => $info['template_id'],
                    'miniprogram' => [
                        'appid' => env('WECHAT_MINI_PROGRAM_APPID'),
                        'pagepath' => $info['page'],
                    ],
                    'data' => $info['data'],
                ]
            ]);
        }
    }

    /**
     * 申请进度通知
     * @param $project_id
     */
    public static function sendProjectInfo($project_id)
    {
        $project = Project::find($project_id);
        if($project && isset($project['user_id'])) {
            $user = User::find($project['user_id']);
            if($user&&$user['open_id']) {
                $official_app = app('wechat.mini_program.default');
                $title = $project->active == 1 ? '您申请的项目已经通过审批，请及时查看！' : '您申请的项目未通过申请，请重新提交！';
                $official_app->uniform_message->send([
                    'touser' => $user['open_id'],
                    'mp_template_msg' => [
                        'appid'=>env('WECHAT_OFFICIAL_ACCOUNT_APPID'),
                        'template_id' => 'NusdON_pl0l32P6rFeYOlvE-53QYvu_eRnn5LthaVdM',
                        'miniprogram' => [
                            'appid' => env('WECHAT_MINI_PROGRAM_APPID'),
                            'pagepath' => 'pages/index/index',
                        ],
                        'data' => [
                            'first' => $title,
                            'keyword1' => $project->name,
                            'keyword2' => $user->name,
                            'keyword3' => '中铁二局',
                            'keyword4' => '项目经理',
                            'keyword5' => $project->created_at,
                            'remark' => '点击进入小程序查看详情',
                        ],
                    ]
            ]);
            }
        }
    }

    /**
     * @param $project_user
     * @return boolean
     */
    public static function sendAddUserInfo($project_user)
    {
        if(!$project_user) return false;
        $project = Project::find($project_user->project_id);
        if($project && isset($project['user_id'])) {
            $user = User::find($project_user->user_id);
            $role = ProjectRole::find($project_user['project_role_id']);
            $work_point = WorkPoint::find($project['work_point_id']);
            if($user&&$user['open_id']) {
                $official_app = app('wechat.mini_program.default');
                $title = '你的项目授权审批已通过！';
                $remark = '授权角色：' . $project->name . ' - ' . ($work_point ? $work_point->name : '') . ' - ' . ($role ? $role->name : '');
                $official_app->uniform_message->send([
                    'touser' => $user['open_id'],
                    'mp_template_msg' => [
                        'appid'=>env('WECHAT_OFFICIAL_ACCOUNT_APPID'),
                        'template_id' => 'zzNETW2GEZ4_GfVp020yH8n9VL97G9EttONAtcrxG9c',
                        'miniprogram' => [
                            'appid' => env('WECHAT_MINI_PROGRAM_APPID'),
                            'pagepath' => 'pages/index/index',
                        ],
                        'data' => [
                            'first' => $title,
                            'keyword1' => $user->name,
                            'keyword2' => $project_user->created_at,
                            'remark' => $remark,
                        ],
                    ]
                ]);
            }
        }
        return true;
    }

    public function getNameContent()
    {
        $order = Order::find($this['order_id']);

        //如果没有订单就不展示
        if(empty($order)){
            return ['name' => '', 'content' => ''];
        }
        $status_name = isset($order) ? $order->getStatusName() : '';
        $source = ((!empty($order) && !empty($order->project)) ? $order->project->name : '') . '-' . ($order->workPoint ? $order->workPoint->name : '') . '-' . ($order->user ? $order->user->name : '');

        $tomorrow = Carbon::tomorrow();
        $days = OrderDevice::where([
            'order_id' => $order->id,
            'end_date' => $tomorrow
        ])->first() ? 1 : 3;
        if($this['type'] == 1) {
            $detail = OrderDevice::where('order_id', $order->id)->count() . '个设备，￥' . ($order->money / 100);
            $type = '设备租赁订单';
            if($this['status'] == 1) {
                return [
                    'name' => '租赁审批成功通知',
                    'content' => '你的设备租赁申请已通过，请确认相关信息：',
                    'official' => [
                        'template_id' => 'dlRsvUWqeziBvGbdT89b69slvZll6gZVRCotIXCwwjM',
                        'page' => 'pages/order-detail/index?id=' . $this['order_id'],
                        'data' => [
                            'first' => '您有一个订单已通过审核，请注意查看！',
                            'keyword1' => $this['created_at'],
                            'keyword2' => $type,
                            'keyword3' => $status_name,
                            'keyword4' => $source,
                            'keyword5' => $detail,
                            'remark' => '点击进入小程序查看详情。',
                        ]
                    ]
                ];
            } else if($this['status'] == 2) {
                return [
                    'name' => '租赁审批待处理通知',
                    'content' => '你有一条设备租赁申请待审批，请确认相关信息：',
                    'official' => [
                        'template_id' => 'dlRsvUWqeziBvGbdT89b69slvZll6gZVRCotIXCwwjM',
                        'page' => 'pages/order-detail/index?id=' . $this['order_id'],
                        'data' => [
                            'first' => '您有一条待审核的订单，请注意查看！',
                            'keyword1' => $this['created_at'],
                            'keyword2' => $type,
                            'keyword3' => $status_name,
                            'keyword4' => $source,
                            'keyword5' => $detail,
                            'remark' => '点击进入小程序查看详情，请及时处理。',
                        ]
                    ]
                ];
            } else if($this['status'] == 3) {
                return [
                    'name' => '租赁审批驳回通知',
                    'content' => '你有一条设备租赁申请被驳回，请确认相关信息：',
                    'official' => [
                        'template_id' => 'dlRsvUWqeziBvGbdT89b69slvZll6gZVRCotIXCwwjM',
                        'page' => '/pages/create-order/index?id=' . $order->project_id . '&order_id=' .  $order->id . '&type=edit',
                        'data' => [
                            'first' => '您有一个订单已被驳回，请注意查看！',
                            'keyword1' => $this['created_at'],
                            'keyword2' => $type,
                            'keyword3' => $status_name,
                            'keyword4' => $source,
                            'keyword5' => $detail,
                            'remark' => '点击进入小程序查看详情，请及时处理。',
                        ]
                    ]
                ];
            } else if($this['status'] == 4) {
                return [
                    'name' => '租赁时间到期通知',
                    'content' => '你有一条设备租赁已到期消息，请确认相关信息：',
                    'official' => [
                        'template_id' => 'dlRsvUWqeziBvGbdT89b69slvZll6gZVRCotIXCwwjM',
                        'page' => 'pages/order-detail/index?id=' . $this['order_id'],
                        'data' => [
                            'first' => '您有一个设备租赁订单即将到期，请注意查看',
                            'keyword1' => $this['created_at'],
                            'keyword2' => $type,
                            'keyword3' => $status_name,
                            'keyword4' => $source,
                            'keyword5' => $detail,
                            'remark' => '你租赁的设备将于' . $days . '天后到期，请进入小程序查看
',
                        ]
                    ]
                ];
            } else if($this['status'] == 5) {
                return [
                    'name' => '租赁完成通知',
                    'content' => '你有一条设备租赁已完成消息，请确认相关信息：',
                    'official' => [
                        'template_id' => 'dlRsvUWqeziBvGbdT89b69slvZll6gZVRCotIXCwwjM',
                        'page' => 'pages/order-detail/index?id=' . $this['order_id'],
                        'data' => [
                            'first' => '有一个订单已完成，请注意查看！',
                            'keyword1' => $this['created_at'],
                            'keyword2' => $type,
                            'keyword3' => $status_name,
                            'keyword4' => $source,
                            'keyword5' => $detail,
                            'remark' => '点击进入小程序查看详情。',
                        ]
                    ]
                ];
            }
        } else {
            $detail = OrderDevice::where('order_id', $order->id)->count() . '个设备';
            $type = '设备调用订单';
            if($this['status'] == 1) {
                return [
                    'name' => '调用审批成功通知',
                    'content' => '你的设备调用申请已通过，请确认相关信息：',
                    'official' => [
                        'template_id' => 'dlRsvUWqeziBvGbdT89b69slvZll6gZVRCotIXCwwjM',
                        'page' => '/pages/create-order-inner/index?id=' . $order->project_id . '&order_id=' .  $order->id . '&type=edit',
                        'data' => [
                            'first' => '您有一个订单已通过审核，请注意查看！',
                            'keyword1' => $this['created_at'],
                            'keyword2' => $type,
                            'keyword3' => $status_name,
                            'keyword4' => $source,
                            'keyword5' => $detail,
                            'remark' => '点击进入小程序查看详情。',
                        ]
                    ]
                ];
            } else if($this['status'] == 2) {
                return [
                    'name' => '调用审批待处理通知',
                    'content' => '你有一条设备调用申请待审批，请确认相关信息：',
                    'official' => [
                        'template_id' => 'dlRsvUWqeziBvGbdT89b69slvZll6gZVRCotIXCwwjM',
                        'page' => '/pages/create-order-inner/index?id=' . $order->project_id . '&order_id=' .  $order->id . '&type=edit',
                        'data' => [
                            'first' => '您有一条待审核的订单，请注意查看！',
                            'keyword1' => $this['created_at'],
                            'keyword2' => $type,
                            'keyword3' => $status_name,
                            'keyword4' => $source,
                            'keyword5' => $detail,
                            'remark' => '点击进入小程序查看详情，请及时处理。',
                        ]
                    ]
                ];
            } else if($this['status'] == 3) {
                return [
                    'name' => '调用审批驳回通知',
                    'content' => '你有一条设备调用申请被驳回，请确认相关信息：',
                    'official' => [
                        'template_id' => 'dlRsvUWqeziBvGbdT89b69slvZll6gZVRCotIXCwwjM',
                        'page' => '/pages/create-order-inner/index?id=' . $order->project_id . '&order_id=' .  $order->id . '&type=edit',
                        'data' => [
                            'first' => '您有一个订单已被驳回，请注意查看！',
                            'keyword1' => $this['created_at'],
                            'keyword2' => $type,
                            'keyword3' => $status_name,
                            'keyword4' => $source,
                            'keyword5' => $detail,
                            'remark' => '点击进入小程序查看详情，请及时处理。',
                        ]
                    ]
                ];
            } else if($this['status'] == 4) {
                return [
                    'name' => '调用时间到期通知',
                    'content' => '你有一条设备调用已到期消息，请确认相关信息：',
                    'official' => [
                        'template_id' => 'dlRsvUWqeziBvGbdT89b69slvZll6gZVRCotIXCwwjM',
                        'page' => '/pages/create-order-inner/index?id=' . $order->project_id . '&order_id=' .  $order->id . '&type=edit',
                        'data' => [
                            'first' => '您有一个设备租赁订单即将到期，请注意查看',
                            'keyword1' => $this['created_at'],
                            'keyword2' => $type,
                            'keyword3' => $status_name,
                            'keyword4' => $source,
                            'keyword5' => $detail,
                            'remark' => '你租赁的设备将于' . $days . '天后到期，请进入小程序查看
',
                        ]
                    ]
                ];
            } else if($this['status'] == 5) {
                return [
                    'name' => '调用完成通知',
                    'content' => '你有一条设备调用已完成消息，请确认相关信息：',
                    'official' => [
                        'template_id' => 'dlRsvUWqeziBvGbdT89b69slvZll6gZVRCotIXCwwjM',
                        'page' => '/pages/create-order-inner/index?id=' . $order->project_id . '&order_id=' .  $order->id . '&type=edit',
                        'data' => [
                            'first' => '有一个订单已完成，请注意查看！',
                            'keyword1' => $this['created_at'],
                            'keyword2' => $type,
                            'keyword3' => $status_name,
                            'keyword4' => $source,
                            'keyword5' => $detail,
                            'remark' => '点击进入小程序查看详情。',
                        ]
                    ]
                ];
            } else if($this['status'] == 6) {
                return [
                    'name' => '调用退回通知',
                    'content' => '你有一条设备调用已归还消息，请确认相关信息：',
                    'official' => [
                        'template_id' => 'dlRsvUWqeziBvGbdT89b69slvZll6gZVRCotIXCwwjM',
                        'page' => '/pages/create-order-inner/index?id=' . $order->project_id . '&order_id=' .  $order->id . '&type=edit',
                        'data' => [
                            'first' => '有一个设备调用订单已完成，请注意查看',
                            'keyword1' => $this['created_at'],
                            'keyword2' => $type,
                            'keyword3' => $status_name,
                            'keyword4' => $source,
                            'keyword5' => $detail,
                            'remark' => '请进入小程序查看详情',
                        ]
                    ]
                ];
            } else if($this['status'] == 7) {
                return [
                    'name' => '调用修改通知',
                    'content' => '你有一条设备调用被修改消息，请确认相关信息：'
                ];
            }
        }
        return ['name' => '', 'content' => ''];
    }
}
