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

namespace app\common\logic;

use app\common\model\Honor as mHonor;
use app\common\model\HonorApply as mHonorApply;
use app\common\model\Manager as mManager;
use think\Db;

class HonorApply extends Base
{


    /**
     * @特权申请列表
     *
     * @param $param
     *
     * @return array
     *
     * @author: zsl
     * @since: 2019/6/3 14:36
     */
    public function lists($param)
    {
        $result = ['code' => 200, 'msg' => '请求成功', 'current_honor_num' => 0, 'data' => []];
        $page = empty($param['page']) ? 1 : $param['page'];
        $limit = empty($param['limit']) ? 1 : $param['limit'];
        $managerId = $this -> getManagerId();
        //查询用户当前荣誉值
        $mManager = new mManager();
        $current_honor_num = $mManager -> honor() -> where(['manager_id' => $managerId]) -> value('current_honor_num');
        $result['current_honor_num'] = empty($current_honor_num) ? 0 : $current_honor_num;
        //查询荣誉列表
        $mHonor = new mHonor();
        $field = 'h.id,h.name,h.rank,h.honor_num,h.privilege,ha.manager_id,ha.status apply_status';
        $where = [];
        $where[] = ['h.status', 'in', '0,1'];
        $honorTable = $mHonor -> alias('h')
                -> field($field)
                -> join(['oa_honor_apply' => 'ha'], 'h.id = ha.honor_id and ha.manager_id = ' . $managerId . '', 'left')
                -> where($where)
                -> order('apply_status')
                -> buildSql();
        $result['count'] = Db ::table($honorTable . ' as honor') -> group('id') -> count();
        $honorList = Db ::table($honorTable . ' as honor') -> group('id') -> order('honor_num,id') -> page($page, $limit) -> select();
        $result['page'] = $page;
        $result['limit'] = $limit;
        if (!empty($honorList)) {
            foreach ($honorList as &$v) {
                if (empty($v['manager_id'])) {
                    //未申请过
                    if ($v['honor_num'] < $current_honor_num) {
                        $v['apply_status'] = - 1;
                    } else {
                        $v['apply_status'] = - 2;
                    }
                }
                $v['privilege'] = json_decode($v['privilege'], true);
                if (!empty($v['privilege'])) {
                    $new_privilege = [];
                    foreach ($v['privilege'] as $k => $privilege) {
                        $new_privilege[$k] = $privilege;
                        $new_privilege[$k]['icon_url'] = get_image_url($privilege['icon']);
                    }
                    $v['privilege'] = $new_privilege;
                }
            }
            $result['data'] = $honorList;
        }
        return $result;
    }


    /**
     * @申请特权
     *
     * @param $param
     *L
     *
     * @return array
     *
     * @author: zsl
     * @since: 2019/6/3 17:37
     */
    public function doApply($param)
    {
        $result = ['code' => 200, 'msg' => '申请成功', 'data' => []];
        Db ::startTrans();
        try {
            $mHonorApply = new mHonorApply();
            $managerId = $this -> getManagerId();
            //驳回特权再次申请
            $again = $mHonorApply -> where(['honor_id' => $param['id'], 'manager_id' => $managerId, 'status' => 2]) -> find();
            if (!empty($again)) {
                $again -> status = 0;
                $again -> save();
            } else {
                $mHonor = new mHonor();
                $honorInfo = $mHonor -> find($param['id']);
                $mManager = new mManager();
                $managerHonor = $mManager -> honor() -> where(['manager_id' => $managerId]) -> find();
                //验证荣誉值数量
                if ($managerHonor['current_honor_num'] < $honorInfo['honor_num']) {
                    $result['code'] = 15003;
                    $result['msg'] = $this -> errorCode(15003);
                    return $result;
                }
                //验证是否有未完成的申请
                $notDown = $mHonorApply -> where(['honor_id' => $param['id'], 'manager_id' => $managerId, 'status' => ['in', '0,1']]) -> count();
                if (!empty($notDown)) {
                    $result['code'] = 15002;
                    $result['msg'] = $this -> errorCode(15002);
                    return $result;
                }
                //插入申请记录
                $mHonorApply -> manager_id = $managerId;
                $mHonorApply -> honor_id = $honorInfo['id'];
                $mHonorApply -> privilege = $honorInfo['privilege'];
                $mHonorApply -> honor_num = $honorInfo['honor_num'];
                $mHonorApply -> current_honor_num = $managerHonor['current_honor_num'] - $honorInfo['honor_num'];
                $mHonorApply -> status = 0;
                $mHonorApply -> isUpdate(false) -> save();
                //扣除用户荣誉值
                $managerHonor -> current_honor_num = $managerHonor['current_honor_num'] - $honorInfo['honor_num'];
                //增加已用荣誉值
                $managerHonor -> use_honor_num = $managerHonor['use_honor_num'] + $honorInfo['honor_num'];
                $managerHonor -> isUpdate(true) -> save();
            }
            Db ::commit();

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

    /**
     * @申请记录
     *
     * @author: zsl
     * @since: 2019/6/3 19:40
     */
    public function applyRecord($param)
    {
        $result = ['code' => 200, 'msg' => '请求成功', 'data' => []];
        $page = empty($param['page']) ? 1 : $param['page'];
        $limit = empty($param['limit']) ? 1 : $param['limit'];
        $mHonorApply = new mHonorApply();
        $field = 'ha.id,ha.manager_id,m.name as manager_name,ha.privilege,ha.honor_num,ha.current_honor_num,ha.create_time,ha.status';
        $where = [];
        if (!empty($param['name'])) {
            $where[] = ['m.name', 'like', '%' . $param['name'] . '%'];
        }
        if (isset($param['status']) && $param['status'] !== '') {
            $where[] = ['ha.status', '=', $param['status']];
        }
        if (!empty($param['start_time'])) {
            $where[] = ['ha.create_time', ['>', strtotime($param['start_time'])], ['=', 0], 'or'];
        }
        if (!empty($param['end_time'])) {
            $where[] = ['ha.create_time', ['<', strtotime($param['end_time']) + 86400 - 1], ['=', 0], 'or'];
        }
        $result['count'] = $mHonorApply -> alias('ha')
                -> join(['oa_manager' => 'm'], 'ha.manager_id = m.id', 'left')
                -> join(['oa_manager_auth' => 'ma'], 'm.id = ma.manager_id', 'left')
                -> join(['oa_manager_item' => 'mi'], 'm.id = mi.manager_id', 'left')
                -> where($where)
                -> count();
        $result['page'] = $page;
        $result['limit'] = $limit;
        $applyLists = $mHonorApply -> alias('ha')
                -> field($field)
                -> join(['oa_manager' => 'm'], 'ha.manager_id = m.id', 'left')
                -> join(['oa_manager_auth' => 'ma'], 'm.id = ma.manager_id', 'left')
                -> join(['oa_manager_item' => 'mi'], 'm.id = mi.manager_id', 'left')
                -> where($where)
                -> page($page, $limit)
                -> order('ha.create_time desc')
                -> select();
        if (!empty($applyLists)) {
            foreach ($applyLists as &$v) {
                $v['privilege'] = json_decode($v['privilege'], true);
                if (!empty($v['privilege'])) {
                    $new_privilege = [];
                    foreach ($v['privilege'] as $k => $privilege) {
                        $new_privilege[$k] = $privilege;
                        $new_privilege[$k]['icon_url'] = get_image_url($privilege['icon']);
                    }
                    $v['privilege'] = $new_privilege;
                }
            }
            $result['data'] = $applyLists;
        }
        return $result;
    }


    /**
     * @通过申请
     *
     * @param $param
     *
     * @return array
     *
     * @author: zsl
     * @since: 2019/6/4 13:32
     */
    public function pass($param)
    {
        $result = ['code' => 200, 'msg' => '审核成功', 'data' => []];
        $where = [];
        if (!empty($param['id'])) {
            $where[] = ['id', '=', $param['id']];
            $where[] = ['status', 'in', '0,2'];
        }
        if (!$this -> reStatus($where, 1)) {
            $result['code'] = 15004;
            $result['msg'] = $this -> errorCode(15004);
        }
        return $result;
    }

    /**
     * @驳回申请
     *
     * @param $param
     *
     * @author: zsl
     * @since: 2019/6/4 13:46
     */
    public function reject($param)
    {
        $result = ['code' => 200, 'msg' => '驳回成功', 'data' => []];
        $where = [];
        if (!empty($param['id'])) {
            $where[] = ['id', '=', $param['id']];
            $where[] = ['status', '=', 0];
        }
        if (!$this -> reStatus($where, 2)) {
            $result['code'] = 15005;
            $result['msg'] = $this -> errorCode(15005);
        }
        return $result;
    }


    /**
     * @发放特权
     *
     * @param $param
     *
     * @author: zsl
     * @since: 2019/6/4 13:46
     */
    public function grant($param)
    {
        $result = ['code' => 200, 'msg' => '发放成功', 'data' => []];
        $where = [];
        if (!empty($param['id'])) {
            $where[] = ['id', '=', $param['id']];
            $where[] = ['status', '=', 1];
            //发送短信
            $field = 'm.id,m.name,m.mobile,ha.privilege';
            $where2 = [];
            $where2[] = ['ha.id', '=', $param['id']];
            $where2[] = ['ha.status', '=', 1];
            $mHonorApply = new mHonorApply();
            $applyInfo = $mHonorApply -> alias('ha')
                    -> field($field)
                    -> join(['oa_manager' => 'm'], 'm.id = ha.manager_id', 'left')
                    -> where($where2)
                    -> find();
            if (!empty($applyInfo['privilege'])) {
                $applyInfo['privilege'] = json_decode($applyInfo['privilege'], true);
                $privilege = '';
                if (!empty($applyInfo['privilege'])) {
                    foreach ($applyInfo['privilege'] as $item) {
                        $privilege .= $item['title'] . ' ';
                    }
                }
                //自动短信通知
                $sendData = ['account' => $applyInfo['name'], 'privilege' => $privilege];
                send_grant_msg($applyInfo['mobile'], json_encode($sendData));
            }
        }
        if (!$this -> reStatus($where, 3)) {
            $result['code'] = 15006;
            $result['msg'] = $this -> errorCode(15006);
        }
        return $result;
    }

    /**
     * @发送通知短信
     *
     * @author: zsl
     * @since: 2019/6/15 12:00
     */
    public function sendSms($param)
    {
        $result = ['code' => 200, 'msg' => '发送成功', 'data' => []];
        if (!empty($param['id'])) {
            //发送短信
            $field = 'm.id,m.name,m.mobile,ha.privilege';
            $where = [];
            $where[] = ['ha.id', '=', $param['id']];
            $where[] = ['ha.status', '=', 3];
            $mHonorApply = new mHonorApply();
            $applyInfo = $mHonorApply -> alias('ha')
                    -> field($field)
                    -> join(['oa_manager' => 'm'], 'm.id = ha.manager_id', 'left')
                    -> where($where)
                    -> find();
            if (!empty($applyInfo['privilege'])) {
                $applyInfo['privilege'] = json_decode($applyInfo['privilege'], true);
                $privilege = '';
                if (!empty($applyInfo['privilege'])) {
                    foreach ($applyInfo['privilege'] as $item) {
                        $privilege .= $item['title'] . ' ';
                    }
                }
                send_grant_msg($applyInfo['mobile'], '' . $applyInfo['name'] . ',' . $privilege . '');
            }
        }
        return $result;
    }

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

    /**
     * @查看用户兑换记录
     *
     * @author: zsl
     * @since: 2019/6/4 14:26
     */
    public function showManagerRecord($param)
    {
        $result = ['code' => 200, 'msg' => '请求成功', 'data' => []];
        if (!empty($param['id'])) {
            $mHonorApply = new mHonorApply();
            $field = 'id,create_time,privilege,honor_num,status';
            $where = [];
            $where[] = ['manager_id', '=', $param['id']];
            $applyList = $mHonorApply -> field($field) -> where($where) -> select();
            if (!empty($applyList)) {
                foreach ($applyList as &$v) {
                    $v['privilege'] = json_decode($v['privilege'], true);
                }
                unset($v);
                $result['data'] = $applyList;
            }

        }
        return $result;
    }


    private function errorCode($code)
    {
        $errorCode = [
                15001 => '',
                15002 => '申请失败',
                15003 => '荣誉值不足',
                15004 => '通过失败',
                15005 => '驳回失败',
                15006 => '发放失败',
        ];
        return empty($errorCode[$code]) ? '系统繁忙,请稍候再试' : $errorCode[$code];
    }


}
