<?php
/**
 * Created by PhpStorm.
 * User: zhc
 * Date: 2019/10/18
 * Time: 11:28
 */

namespace Logic;

use exception\LogicException;
use think\Db;
use think\facade\Log;
use exception\ResponsableException;
use think\Exception;
use exception\BaseException;
class KefuLogic
{
    /**
     * 获取客服列表
     * @param $where 查询条件
     * @param $filed 显示字段
     * @param $page 页码
     * @param$limit  条数
     * @return array
     */
    public static function getKefuByPage($where, $filed = "*", $limit = 20)
    {
        try {
            return Db::name('kefu_info')->field($filed)->where($where)->paginate($limit);

        } catch (Exception $e) {
            throw new ResponsableException('信息错误', 404);
        }

    }
    /**
     * 添加客服
     * @param $param
     * @return boolean
     */
    public static function addKefu($name,$password)
    {
        try {
            Db::startTrans();
            $info = Db::name('kefu_info')->where('kefu_name', $name)->find();
            if ($info) {
                throw new LogicException('客服名已被使用', 1001);
            }
            $kf['kefu_code'] = 'kefu' . uniqid();
            $kf['kefu_name'] = $name;
            $kf['kefu_avatar'] = '/static/common/images/kefu.jpg';
            $kf['kefu_password'] = strtoupper(md5($password));
            $kf['online_status'] = 2;
            $kf['create_time'] = date('Y-m-d H:i:s');
            $kf['update_time'] = date('Y-m-d H:i:s');
            Db::name('kefu_info')->insert($kf);
            Db::commit();
            return true;
        } catch (BaseException $be) {
            Db::rollback();
            throw new ResponsableException($be->getMessage(), $be->getCode());
        } catch (Exception $e) {
            Db::rollback();
            dump($e->getMessage());
            throw new ResponsableException('添加失败', 404);
        }
    }
    /**
     * 删除客服
     * @param $id 主键id
     * @return boolean
     */
    public static function delKefu($id)
    {
        try {
            Db::startTrans();
            $info = Db::name('kefu_info')->where('kefu_id', $id)->find();
            if (!$info) {
                throw new LogicException('客服不存在', 1001);
            }
            //删除账号信息
            Db::name('kefu_info')->where('kefu_id', $info['kefu_id'])->delete();
            Db::commit();
            return true;
        } catch (BaseException $be) {
            Db::rollback();
            throw new ResponsableException($be->getMessage(), $be->getCode());
        } catch (Exception $e) {
            Db::rollback();
            throw new ResponsableException('删除失败', 404);
        }
    }
    /**
     * 编辑客服
     * @param $param
     * @return boolean
     */
    public static function saveKefu($id,$name)
    {
        try {
            Db::startTrans();
            $kinfo= Db::name('kefu_info')->where('kefu_id',$id)->find();
            if(!$kinfo){
                throw new LogicException('记录不存在', 1001);
            }
            $info = Db::name('kefu_info')->whereNotIn('kefu_id',$id)->where('kefu_name', $name)->find();
            if ($info) {
                throw new LogicException('客服名已被使用', 1001);
            }
            $kf['kefu_name'] = $name;
            $kf['update_time'] = date('Y-m-d H:i:s');
            Db::name('kefu_info')->where('kefu_id',$id)->update($kf);
            Db::commit();
            return true;
        } catch (BaseException $be) {
            Db::rollback();
            throw new ResponsableException($be->getMessage(), $be->getCode());
        } catch (Exception $e) {
            Db::rollback();
            throw new ResponsableException($e->getMessage(), 404);
        }
    }

    /**
     * 修改客服密码
     * @param $id 主键id
     * @return boolean
     */
    public static function resetPassword($id,$password)
    {
        try {
            $info = Db::name('kefu_info')->where('kefu_id', $id)->find();
            if (!$info) {
                throw new LogicException('客服不存在', 1001);
            }
            $kf['kefu_password'] = strtoupper(md5($password));
            $kf['update_time'] = date('Y-m-d H:i:s');
            return Db::name('kefu_info')->where('kefu_id', $id)->update($kf);
        } catch (BaseException $be) {
            throw new ResponsableException($be->getMessage(), $be->getCode());
        } catch (Exception $e) {
            throw new ResponsableException('修改密码失败', 404);
        }
    }
    /**
     * 获取客服数量
     * @param $kefu_code  客服编码
     */
    public  static  function kefuCount($where=[]){
        return Db::name('kefu_info')->where($where)->count();
    }
    /**
     * 查找在线客服
     * @param $kefu_code  客服编码
     */
    public static function findKefuByCodeOnline($code)
    {
        return Db::name('kefu_info')->where('kefu_code', $code)->find();
    }

    /**
     * 查找激活并在线的客服
     * @param $kefu_code  客服编码
     */
    public static function getKefuByGroupId($group_id)
    {
        return Db::name('kefu_info')->where('group_id', $group_id)->where('kefu_status', 1)->where('online_status', 1)->select();
    }


    /**
     * 设置客服在线 离线
     * @param $uid  客服编码
     */
    public static function setKefuOnlineStatus($kefu_code, $fd, $status = 1)
    {
        if (!in_array($status, [0, 1, 2])) {
            throw new LogicException('客服状态错误', 8001);
        }
        $kefu_info = Db::name('kefu_info')->where('kefu_code', $kefu_code)->find();

        if (!$kefu_info) {
            throw new LogicException('客服不存在', 8002);
        }
        $update['online_status'] = $status;
        if ($status == 1) {
            $update['client_id'] = $fd;
        } else {
            $update['client_id'] = '';
        }
        $result = Db::name('kefu_info')->where('kefu_code', $kefu_code)->update($update);
        if ($result === false) {
            throw new LogicException('客服状态更新失败', 8003);
        }
        return array_merge($kefu_info, $update);

    }

    /**
     * 分配客服
     */
    public static function distributionKefu($data)
    {
        if (empty($data)) {
            throw new LogicException('参数缺失', 8001);
        }
        Log::record('分配参数' . json_encode($data));
        //指定分配
        $kefu_info = self::findKefu($data);
        return $kefu_info;
    }

    public static function findKefu($data)
    {

        $customer_info = Visitor::getCustomerInfoOnlineByCustomerId($data['visitor_id']);
        if (empty($customer_info)) {
            throw new LogicException('暂无游客登录信息', 8004);
        }
        $kefu_info = self::findKefuByCodeOnline($data['kefu_code']);
        if (empty($kefu_info)) {
            Log::record('客服不存在 或者 客服不在线 匹配客服');
            return ['code' => 201, 'data' => [
            ], 'msg' => '客服不在线'];

        }
        return ['code' => 200, 'data' => [
            'kefu_id' => $kefu_info['kefu_id'],
            'kefu_code' => 'KF_' . $kefu_info['kefu_code'],
            'kefu_name' => $kefu_info['kefu_name'],
            'kefu_avatar' => $kefu_info['kefu_avatar'],
            'kefu_client_id' => $kefu_info['client_id'],
        ], 'msg' => '客服正常服务'];

    }

}



