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

namespace app\common\logic;

use app\common\model\ManagerHonor as mManagerHonor;
use app\common\model\Manager as mManager;
use app\common\validate\Honor as vHonor;
use app\common\model\Honor as mHonor;

class Honor extends Base
{

    /**
     * @获取荣誉列表
     *
     * @return array
     *
     * @author: zsl
     * @since: 2019/6/1 15:50
     */
    public function lists($param)
    {
        $result = ['code' => 200, 'msg' => '请求成功', 'data' => []];
        $page = empty($param['page']) ? 1 : $param['page'];
        $limit = empty($param['limit']) ? 1 : $param['limit'];
        $field = 'h.*,m.name manager_name';
        $where = [];
        $where[] = ['h.status', 'in', '0,1'];
        $mHonor = new mHonor();
        $result['count'] = $mHonor -> alias('h') -> where($where) -> count();
        $result['page'] = $page;
        $result['limit'] = $limit;
        $honorList = $mHonor -> alias('h')
                -> field($field)
                -> join(['oa_manager' => 'm'], 'm.id = h.manager_id', 'left')
                -> where($where)
                -> order('h.honor_num')
                -> page($page, $limit)
                -> select() -> toArray();
        if (!empty($honorList)) {
            foreach ($honorList as &$v) {
                if (!empty($v['privilege'])) {
                    $v['privilege'] = json_decode($v['privilege'], true);
                    foreach ($v['privilege'] as &$privilege) {
                        if (!empty($privilege['title']) && !empty($privilege['icon'])) {
                            $privilege['icon_url'] = get_image_url($privilege['icon']);
                        }
                    }
                }
            }
            unset($v);
            $result['data'] = $honorList;
        }
        return $result;
    }

    /**
     * @新建荣誉等级
     *
     * @param $param
     *
     * @return array
     *
     * @author: zsl
     * @since: 2019/6/1 15:54
     */
    public function create($param)
    {
        $result = ['code' => 200, 'msg' => '新增成功', 'data' => []];
        $vHonor = new vHonor();
        if (!$vHonor -> scene('create') -> check($param)) {
            $result['code'] = 14001;
            $result['msg'] = $vHonor -> getError();
            return $result;
        }
        try {
            $mHonor = new mHonor();
            $mHonor -> name = $param['name'];
            $mHonor -> rank = $param['rank'];
            $mHonor -> honor_num = $param['honor_num'];
            if (isset($param['privilege'])) {
                $mHonor -> privilege = json_encode($param['privilege'], JSON_UNESCAPED_UNICODE);
            }
            $mHonor -> manager_id = $this -> getManagerId();
            $mHonor -> status = 1;
            $mHonor -> isUpdate(false) -> save();
        } catch (\Exception $e) {
            $result['code'] = 14002;
            $result['msg'] = $this -> errorCode(14002);
        }
        return $result;
    }

    /**
     * @荣誉等级详情
     *
     * @param $param
     *
     * @return array
     *
     * @author: zsl
     * @since: 2019/6/1 16:13
     */
    public function detail($param)
    {
        $detail = [];
        if (!empty($param['id'])) {
            $mHonor = new mHonor();
            $where = [];
            $where[] = ['status', 'in', '0,1'];
            $where[] = ['id', '=', $param['id']];
            $detail = $mHonor -> where($where) -> find();
            if (!empty($detail)) {
                $detail['privilege'] = json_decode($detail['privilege'], true);
                $detail['manager_name'] = db('manager') -> where(['id' => $detail['manager_id']]) -> value('name');
                $new_privilege = [];
                if (!empty($detail['privilege'])) {
                    foreach ($detail['privilege'] as $k => $privilege) {
                        $new_privilege[$k] = $privilege;
                        if (!empty($privilege['title']) && !empty($privilege['icon'])) {
                            $new_privilege[$k]['icon_url'] = get_image_url($privilege['icon']);
                        }
                    }
                }
                $detail['privilege'] = $new_privilege;
            }
        }
        return $detail;
    }

    /**
     * @更新荣誉等级
     *
     * @param $param
     *
     * @author: zsl
     * @since: 2019/6/1 16:13
     */
    public function update($param)
    {
        $result = ['code' => 200, 'msg' => '更新成功', 'data' => []];
        $vHonor = new vHonor();
        if (!$vHonor -> scene('update') -> check($param)) {
            $result['code'] = 14001;
            $result['msg'] = $vHonor -> getError();
            return $result;
        }
        $mHonor = $this -> detail(['id' => $param['id']]);
        if (empty($mHonor)) {
            $result['code'] = 14003;
            $result['msg'] = $this -> errorCode(14003);
            return $result;
        }
        try {
            $mHonor -> name = $param['name'];
            $mHonor -> rank = $param['rank'];
            $mHonor -> honor_num = $param['honor_num'];
            $mHonor -> manager_id = $this -> getManagerId();
            if (isset($param['privilege'])) {
                $mHonor -> privilege = json_encode($param['privilege'], JSON_UNESCAPED_UNICODE);
            }
            $mHonor -> manager_id = $this -> getManagerId();
            $mHonor -> isUpdate(true) -> save();
        } catch (\Exception $e) {
            $result['code'] = 14004;
            $result['msg'] = $this -> errorCode(14004);
        }
        return $result;
    }


    /**
     * @删除荣誉等级
     *
     * @return array
     *
     * @author: zsl
     * @since: 2019/6/3 10:15
     */
    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'] = 14005;
            $result['msg'] = $this -> errorCode(14005);
        }
        return $result;
    }


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


    /**
     * @设置荣誉值比例
     *
     * @param array $param
     *
     * @return array
     *
     * @author: zsl
     * @since: 2019/6/1 15:26
     */
    public function setRatio($param = [])
    {
        $result = ['code' => 200, 'msg' => '设置成功', 'data' => []];
        $option['price_ratio'] = empty($param['price_ratio']) ? 1 : $param['price_ratio'];
        set_option('honor_ratio', $option);
        return $result;
    }

    /**
     * @获取荣誉值比例
     *
     * @param $param
     *
     * @return array
     *
     * @author: zsl
     * @since: 2019/6/1 15:26
     */
    public function getRatio()
    {
        $result = ['code' => '200', 'msg' => '请求成功', 'data' => []];
        $option = get_option('honor_ratio');
        if (empty($option)) {
            $this -> setRatio();
            $option = ('site_info');
        }
        $result['data'] = $option;
        return $result;
    }


    /**
     * @查看用户荣誉信息
     *
     * @param $param
     *
     * @return array
     *
     * @author: zsl
     * @since: 2019/6/3 11:31
     */
    public function managerHonor($param)
    {
        $result = ['code' => 200, 'msg' => '请求成功', 'data' => []];
        $page = empty($param['page']) ? 1 : $param['page'];
        $limit = empty($param['limit']) ? 1 : $param['limit'];
        $managerId = $this -> getManagerId();
        $mManagerHonor = new mManagerHonor();
        $field = 'm.id,m.name,h.name as honor_name,mh.total_honor_num,mh.use_honor_num,mh.current_honor_num,m.mobile,count(ha.id) as apply_num';
        $where = [];
//        $where[] = ['mh.honor_id', '<>', '0'];
        //非超级管理员,只可查看
        if ($managerId != config('administrators_id')) {
            $stat = new Stat();
            $managerIds = $stat -> getSubManagerIds($managerId);
            $where[] = ['m.id', 'in', $managerIds];
        }
        if (!empty($param['name'])) {
            $where[] = ['m.name', 'like', '%' . $param['name'] . '%'];
        }
        $result['count'] = $mManagerHonor -> alias('mh')
                -> join(['oa_manager' => 'm'], 'mh.manager_id = m.id', 'left')
                -> where($where) -> count();
        $result['page'] = $page;
        $result['limit'] = $limit;
        $managerHonorList = $mManagerHonor -> alias('mh')
                -> join(['oa_manager' => 'm'], 'mh.manager_id = m.id', 'left')
                -> join(['oa_honor' => 'h'], 'mh.honor_id = h.id', 'left')
                -> join(['oa_honor_apply' => 'ha'], 'ha.manager_id = m.id', 'left')
                -> field($field)
                -> where($where)
                -> page($page, $limit)
                -> group('id')
                -> select();
        if (!empty($managerHonorList)) {
            $result['data'] = $managerHonorList;
        }
        return $result;
    }


    /**
     * @荣誉等级发送短信通知
     *
     * @param $param
     *
     * @author: zsl
     * @since: 2019/6/4 16:35
     */
    public function sendSms($param)
    {
        $result = ['code' => 200, 'msg' => '发送成功', 'data' => []];
        try {
            $mManager = new mManager();
            $field = 'm.id,m.name,m.mobile,h.rank,mh.current_honor_num,mh.total_honor_num,h.privilege';
            $where = [];
            $where[] = ['m.id', '=', $param['id']];
            $where[] = ['m.status', 'in', '0,1'];
            $managerInfo = $mManager -> alias('m')
                    -> field($field)
                    -> join(['oa_manager_honor' => 'mh'], 'm.id = mh.manager_id', 'left')
                    -> join(['oa_honor' => 'h'], 'mh.honor_id = h.id', 'left')
                    -> where($where)
                    -> find();
            if (!empty($managerInfo)) {

                $managerInfo['privilege'] = json_decode($managerInfo['privilege'], true);
                $privilege = '';
                if (!empty($managerInfo['privilege'])) {
                    foreach ($managerInfo['privilege'] as $v) {
                        $privilege .= $v['title'] . ' ';
                    }
                }
                $mobile = $managerInfo['mobile'];
                $sendData = [
                        'account' => $managerInfo['name'],
                        'level' => $managerInfo['rank'],
                        'total' => $managerInfo['total_honor_num'],
                        'balance' => $managerInfo['current_honor_num'],
                        'privilege' => $privilege,
                ];
                $res = send_honor_msg($mobile, json_encode($sendData));
                if ($res == '2') {
                    $result['code'] = 14007;
                    $result['msg'] = $this -> errorCode(14007);
                    return $result;
                }
            }
        } catch (\Exception $e) {
            $result['code'] = 14006;
            $result['msg'] = $this -> errorCode(14006);
        }
        return $result;
    }


    private function errorCode($code)
    {
        $errorCode = [
                14001 => '',
                14002 => '新增荣誉等级失败',
                14003 => '荣誉等级不存在或已被删除',
                14004 => '更新荣誉等级失败',
                14005 => '删除失败',
                14006 => '发送失败',
                14007 => '短信已关闭',
        ];
        return empty($errorCode[$code]) ? '系统繁忙,请稍候再试' : $errorCode[$code];
    }


}
