<?php
/**
 * @Copyright (c) 2019  XIGU Inc. All rights reserved.
 * @Link https://www.vlcms.com
 * @License江苏溪谷网络科技有限公司版权所有
 */

namespace app\common\logic;

use app\common\validate\Notic as vNotic;
use app\common\model\Notic as mNotic;
use app\common\model\ManagerAuth as mManagerAuth;

class Notic extends Base
{
    public function lists($param)
    {
        $result = ['code' => '200', 'msg' => '请求成功', 'data' => []];
        $page = empty($param['page']) ? 1 : $param['page'];
        $limit = empty($param['limit']) ? 1 : $param['limit'];
        $where = [];
        if (!empty($param['title'])) {
            $where[] = ['title', 'like', '%' . $param['title'] . '%'];
        }
        $status = input('status');
        if ($status === '0' || $status === '1') {
            $where[] = ['status', '=', $status];
        } else {
            $where[] = ['status', 'in', '0,1'];
        }
        if (!empty($param['start_time'])) {
            $where[] = ['update_time', ['>=', $param['start_time']], ['=', 0], 'or'];
        }
        if (!empty($param['end_time'])) {
            $where[] = ['update_time', ['<=', $param['end_time']], ['=', 0], 'or'];
        }
        if (!empty($param['category'])) {
            $where[] = ['category', '=', $param['category']];
        }
        $mNotic = new mNotic();
        $result['count'] = $mNotic -> where($where) -> count();
        $result['page'] = $page;
        $result['limit'] = $limit;
        $noticLists = $mNotic -> where($where) -> page($page, $limit) -> order('sort desc,create_time') -> select();
        if (!empty($noticLists)) {
            $result['data'] = $noticLists;
        }
        return $result;
    }

    public function studioNotic($param)
    {
        $result = ['code' => '200', 'msg' => '请求成功', 'data' => []];
        $page = empty($param['page']) ? 1 : $param['page'];
        $limit = empty($param['limit']) ? 1 : $param['limit'];
        $managerId = $this -> getManagerId();
        $mManagerAuth = new mManagerAuth();
        $role_id = $mManagerAuth -> where('manager_id', '=', $managerId) -> value('role_id');
        $base_role = config('base_role');
        $where = [];
        $where[] = ['status', 'in', '0,1'];
        $where[] = ['start_time', 'lt', time()];
        $where[] = ['end_time', ['gt', time()], ['=', 0], 'or'];
        $mNotic = new mNotic();
        if ($managerId == config('administrators_id') || $role_id == $base_role['admin']) {
            $result['count'] = $mNotic -> where($where) -> count();
            $noticLists = $mNotic
                    -> where($where)
                    -> page($page, $limit)
                    -> order('sort desc,create_time desc')
                    -> select();
        } else {
            $result['count'] = $mNotic
                    -> where($where)
                    -> whereExp('', 'find_in_set(' . $role_id . ',role_ids) or role_ids = 0')
                    -> count();
            $noticLists = $mNotic
                    -> where($where)
                    -> whereExp('', 'find_in_set(' . $role_id . ',role_ids) or role_ids = 0')
                    -> page($page, $limit)
                    -> order('sort desc,create_time desc')
                    -> select();
        }
        $result['page'] = $page;
        $result['limit'] = $limit;
        if (!empty($noticLists)) {
            $result['data'] = $noticLists;
        }
        return $result;
    }


    /**
     * @分类公告通知
     *
     * @author: zsl
     * @since: 2019/6/5 14:35
     */
    public function categoryNotic($param)
    {
        $result = ['code' => 200, 'msg' => '请求成功', 'data' => []];
        $category = empty($param['category']) ? 'gonggao' : $param['category'];
        $managerId = $this -> getManagerId();
        $mManagerAuth = new mManagerAuth();
        $role_id = $mManagerAuth -> where('manager_id', '=', $managerId) -> value('role_id');
        $mNotic = new mNotic();
        $field = 'id,category,title,description,content,status';
        $where = [];
        $where[] = ['status', '=', '1'];
        $where[] = ['category', '=', $category];
        $where[] = ['start_time', 'lt', time()];
        $where[] = ['end_time', ['gt', time()], ['=', 0], 'or'];
        if ($managerId == config('administrators_id')) {
            $result['count'] = $mNotic -> where($where) -> count();
            $noticLists = $mNotic
                    -> field($field)
                    -> where($where)
                    -> order('sort desc,create_time desc')
                    -> limit(8)
                    -> select();
        } else {
            $result['count'] = $mNotic
                    -> where($where)
                    -> whereExp('', 'find_in_set(' . $role_id . ',role_ids) or role_ids = 0')
                    -> count();
            $noticLists = $mNotic
                    -> field($field)
                    -> where($where)
                    -> whereExp('', 'find_in_set(' . $role_id . ',role_ids) or role_ids = 0')
                    -> order('sort desc,create_time desc')
                    -> limit(8)
                    -> select();
        }
        if (!empty($noticLists)) {
            $result['data'] = $noticLists;
        }
        return $result;
    }


    public function create($param)
    {
        $result = ['code' => '200', 'msg' => '新增成功', 'data' => []];
        $vNotic = new vNotic();
        if (!$vNotic -> scene('create') -> check($param)) {
            $result['code'] = 1100001;
            $result['msg'] = $vNotic -> getError();
            return $result;
        }
        try {

            if (empty($param['start_time']) || !is_numeric($param['start_time'])) {
                $param['start_time'] = 0;
            }
            if (empty($param['end_time']) || !is_numeric($param['end_time'])) {
                $param['end_time'] = 0;
            }
            $mNotic = new mNotic();
            $mNotic -> isUpdate(false) -> allowField(true) -> save($param);
        } catch (\Exception $e) {
            $result['code'] = 1100002;
            $result['msg'] = $this -> errorCode(1100002);
        }
        return $result;
    }

    public function detail($param)
    {
        $detail = [];
        if (!empty($param['id'])) {

            $where = [];
            $where[] = ['id', '=', $param['id']];
            $where[] = ['status', 'in', '0,1'];
            $mNotic = new mNotic();
            $detail = $mNotic -> where($where) -> find();
        }
        return $detail;
    }

    public function update($param)
    {
        $result = ['code' => '200', 'msg' => '更新成功', 'data' => []];
        $vNotic = new vNotic();
        if (!$vNotic -> scene('update') -> check($param)) {
            $result['code'] = 1100001;
            $result['msg'] = $vNotic -> getError();
            return $result;
        }
        $mNotic = $this -> detail(['id' => $param['id']]);
        if (empty($mNotic)) {
            $result['code'] = 1100004;
            $result['msg'] = $this -> errorCode(1100004);
            return $result;
        }
        try {
            if (!empty($param['content'])) {
                $mNotic -> content = $param['content'];
            }
            $mNotic -> role_ids = empty($param['role_ids']) ? 0 : $param['role_ids'];
            if (!empty($param['sort'])) {
                $mNotic -> sort = $param['sort'];
            }
            $mNotic -> is_push = empty($param['is_push']) ? 0 : 1;
            $mNotic -> title = $param['title'];
            $mNotic -> description = $param['description'];
            $mNotic -> start_time = $param['start_time'];
            $mNotic -> end_time = $param['end_time'];
            $mNotic -> category = $param['category'];
            $mNotic -> isUpdate(true) -> allowField(true) -> save();

        } catch (\Exception $e) {
            $result['code'] = 1100003;
            $result['msg'] = $this -> errorCode(1100003);
        }
        return $result;
    }

    public function enable($param)
    {
        $result = ['code' => 200, 'msg' => '公告启用成功', 'data' => []];
        $where = [];
        if (!empty($param['id'])) {
            $where[] = ['id', '=', $param['id']];
        }
        if (!$this -> reStatus($where, 1)) {
            $result['code'] = 1100006;
            $result['msg'] = $this -> errorCode(1100006);
        }
        return $result;
    }

    public function disable($param)
    {
        $result = ['code' => 200, 'msg' => '公告禁用成功', 'data' => []];
        $where = [];
        if (!empty($param['id'])) {
            $where[] = ['id', '=', $param['id']];
        }
        if (!$this -> reStatus($where, 0)) {
            $result['code'] = 1100007;
            $result['msg'] = $this -> errorCode(1100007);
        }
        return $result;
    }

    public function delete($param)
    {
        $result = ['code' => 200, 'msg' => '公告删除成功', 'data' => []];
        $where = [];
        if (!empty($param['id'])) {
            $where[] = ['id', '=', $param['id']];
        }
        if (!$this -> reStatus($where, - 1)) {
            $result['code'] = 1100010;
            $result['msg'] = $this -> errorCode(1100010);
        }
        return $result;
    }

    public function sort($param)
    {
        $result = ['code' => '200', 'msg' => '修改成功', 'data' => []];
        $mNotic = $this -> detail(['id' => $param['id']]);
        if (empty($mNotic)) {
            $result['code'] = 1100004;
            $result['msg'] = $this -> errorCode(1100004);
            return $result;
        }
        try {
            $mNotic -> sort = empty($param['sort']) ? 0 : $param['sort'];
            $mNotic -> save();
        } catch (\Exception $e) {
            $result['code'] = 1100011;
            $result['msg'] = $this -> errorCode(1100011);
        }
        return $result;
    }

    private function reStatus($where, $status)
    {
        try {
            $mNotic = new mNotic();
            $mNotic -> where($where) -> update(['status' => $status]);
            return true;
        } catch (\Exception $e) {
            return false;
        }
    }

    private function errorCode($code)
    {
        $errorCode = [
                1100001 => '',
                1100002 => '公告添加失败',
                1100003 => '公告修改失败',
                1100004 => '公告不存在，或已被删除',
                1100006 => '公告启用失败',
                1100007 => '公告禁用失败',
                1100010 => '公告删除失败',
                1100011 => '修改失败',
        ];
        return empty($errorCode[$code]) ? '系统繁忙,请稍候再试' : $errorCode[$code];
    }

}