<?php
/*
 本代码由 焕岱科技 创建
 技术支持 WX：15285007200
 严禁反编译、逆向等任何形式的侵权行为，违者将追究法律责任
*/

namespace app\common\model\bbfxshop;

use think\Model;
use think\Db;
use app\common\model\bbfxshop\User;
use app\common\model\bbfxshop\Message;
use app\common\model\bbfxshop\Notice;

class Workorder extends Model
{
    public static function getSet(){
        global $_W;
        $base = $_W['base'];
        if(empty($base)){
            $base = \app\common\model\bbfxshop\Common::getConfig(true);
        }
        
        return $base['workorder'];
    }

    public static function sendNotice($user_id,$title,$content,$link=""){
        if(is_array($user_id)){
            $notice_user_id = $user_id;
        }
        else{
            $notice_user_id = [$user_id];
        }
        $params = ['title'=>$title,'user_id'=>$notice_user_id,'type'=>6,'itype'=>1,'content'=>$content,'link'=>$link];

        $result = Notice::send($params);

        return $result;
    }


    public static function sendNewOrderNotice($id){
        $item = Db::name("bbfx_workorder")->where(['id'=>$id])->find();
        if(empty($item)){
            return __json(0,"工单不存在");
        }
        if($item['status'] > 0){
            return __json(0,"工单已被接单");
        }
        $user_list = Db::name("bbfx_workorder_user")->where(['uniacid'=>UNIACID,'category_id'=>$item['category_id']])->select();
        if(empty($user_list)){
            return __json(0,"未找到可分配成员");
        }

        foreach($user_list as $key => $user){
            self::sendNotice($user['user_id'],"新工单通知","用户已提交新工单，请尽快前往接单！","/plugin/work_order/public");
        }

        return __json(1,"操作成功");
    }
    
    // 分配
    public static function allocate($id,$user_id=0){
        $item = Db::name("bbfx_workorder")->where(['id'=>$id])->find();
        if(empty($item)){
            return __json(0,"工单不存在");
        }
        if($item['status'] == 3){
            return __json(0,"工单已关单");
        }
        if($item['status'] !== 0){
            // return __json(0,"工单已分配");
        }
        $user = Db::name("bbfx_workorder_user")->where(['id'=>$user_id])->find();
        if($item['status'] > 0 && empty($user)){
            return __json(0,"请选择转单用户");
        }

        if($item['status'] == 0 && empty($user)){
            $user_list = Db::name("bbfx_workorder_user")->where(['uniacid'=>UNIACID,'category_id'=>$item['category_id']])->select();
            if(empty($user_list)){
                return __json(0,"未找到可分配成员");
            }

            foreach($user_list as $key => $val){
                $num1 = Db::name("bbfx_workorder")->where(['uniacid'=>UNIACID,'fz_user_id'=>$item['user_id']])->count();
                $val['num1'] = intval($num1);
                $num2 = Db::name("bbfx_workorder")->where(['uniacid'=>UNIACID,'fz_user_id'=>$item['user_id'],'status'=>['<',3]])->count();
                $val['num2'] = intval($num2);
            }

            $num1 = array_column($user_list,'num2');
            array_multisort($num1,SORT_ASC,$user_list);

            $user = $user_list[0];
        }
        else{
            if($user['id'] == $item['fz_user_id']){
                return __json(0,"不能转给自己");
            }
        }
        
        if(empty($user)){
            return __json(0,"工单用户信息错误");
        }

        if($user['category_id'] != $item['category_id']){
            return __json(0,"不是工单分类下的工单用户");
        }

        if($item['status'] == 0){
            $res = Db::name("bbfx_workorder")->where(['id'=>$item['id'],'status'=>0])->update(['status'=>1]);
            if(empty($res)){
                return __json(0,"修改状态失败");
            }
        }
        

        Db::name("bbfx_workorder")->where(['id'=>$item['id']])->update(['cltime'=>time(),'fz_user_id'=>$user['id']]);
        Db::name("bbfx_workorder_probe")->where(['uniacid'=>UNIACID,'pid'=>$item['id'],'fz_user_id'=>0])->update(['fz_user_id'=>$user['id']]);
        $notice_user_id = [$user['user_id']];
        if($item['status'] > 0){
            $user = Db::name("bbfx_workorder_user")->where(['id'=>$item['fz_user_id']])->find();
            self::addLog($item['id'],"工单转单","工单转给指定分类下其他的成员。",$user['name']);
            $notice_content = "【{$user['name']}】转单，请尽快处理！";
            $title = "工单转单";
        }
        else{
            self::addLog($item['id'],"分配工单","分配工单给指定分类下的成员。","平台");
            $notice_content = "新的工单已分配，请尽快处理！";
            $title = "分配工单";
        }

        Message::sendWorkorderAllocateMsg($item['id']);

        self::sendNotice($notice_user_id,$title,$notice_content,"/plugin/work_order/detail?id=".$item['id']."&role=1");

        return __json(1,"操作成功");
    }

    // 完成
    public static function complete($id,$content,$images=[],$reply_id=0,$user_id=0){
        $item = Db::name("bbfx_workorder")->where(['id'=>$id])->find();
        if(empty($item)){
            return __json(0,"工单不存在");
        }

        if($item['status'] == 3){
            return __json(0,"工单已关单");
        }
        if($item['status'] == 0){
            return __json(0,"工单未分配");
        }

        if(empty($content)){
            return __json(0,"请填写回复内容");
        }

        $user = Db::name("bbfx_workorder_user")->where(['uniacid'=>UNIACID,'id'=>$item['fz_user_id']])->find();
        if($user_id > 0 && $user['user_id'] != $user_id){
            return __json(0,"无权限操作");
        }

        $data = [
            'uniacid'=>UNIACID,
            'type'=>2,
            'user_id'=>$item['user_id'],
            'fz_user_id'=>$item['fz_user_id'],
            'pid'=>$item['id'],
            'content'=>$content,
            'images'=>iserializer(replaceSiteroots($images)),
            'createtime'=>time()
        ];

        Db::name("bbfx_workorder_probe")->insert($data);

        Db::name("bbfx_workorder")->where(['id'=>$item['id']])->update(['status'=>2,'is_reply'=>1,'completetime'=>time()]);
        
        self::addLog($item['id'],"完成工单","成员完成工单回复。",$user['name']);

        Message::sendWorkorderCompleteMsg($item['id']);

        self::sendNotice($item['user_id'],'工单回复',"您提交的问题已处理，请注意查看回复内容！","/plugin/work_order/detail?id=".$item['id']."&role=2");

        return __json(1,"操作成功");

    }

    // 24小时无追问自动关单
    public static function autoClose(){
        $time = strtotime(date('Y-m-d H:i:s')." -1 day");
        $list = Db::name("bbfx_workorder")->where(['uniacid'=>UNIACID,'status'=>2,'is_reply'=>1,'completetime'=>['<',$time]])->find();
        if(empty($list)){
            return __json(0,"没有可关闭工单");
        }
        foreach($list as $key => $val){
            try {
                
                self::close($val);
            } 
            catch (\Exception $e) {
                
            }
        }
        
        return __json(1,"操作成功");
    }

    // 关单
    public static function close($id,$user_id=0,$type=1){

        if(is_array($id)){
            $item = $id;
        }
        else{
            $item = Db::name("bbfx_workorder")->where(['id'=>$id])->find();
        }
        
        if(empty($item)){
            return __json(0,"工单不存在");
        }

        if($item['status'] < 2){
            return __json(0,"工单未完成");
        }
        if($item['status'] == 3){
            return __json(0,"工单已关单");
        }
        if($item['is_check'] != 1){
            return __json(0,"用户还未查看，不可关单");
        }

        if($type == 1){
            $user = Db::name("bbfx_workorder_user")->where(['uniacid'=>UNIACID,'id'=>$item['fz_user_id']])->find();
            if($user_id > 0 && $user['user_id'] != $user_id){
                return __json(0,"无权限操作");
            }

            if(!empty($user)){
                $username = $user['name'];
            }
            else{
                $username = "平台";
            }
        }
        else{
            if($item['user_id'] != $user_id){
                return __json(0,"无权限操作");
            }
            $username = Db::name("bbfx_user")->where(['id'=>$item['user_id']])->value("nickname");
        }

        $res = Db::name("bbfx_workorder")->where(['id'=>$item['id'],'status'=>2])->update(['status'=>3]);
        if(empty($res)){
            return __json(0,"修改状态失败");
        }

        Db::name("bbfx_workorder")->where(['id'=>$item['id']])->update(['closetime'=>time()]);

        self::addLog($item['id'],"关闭工单","工单已完成，关闭工单。",$username);

        self::sendNotice($item['user_id'],'关闭工单',"您提交的工单已处理完成！","/plugin/work_order/detail?id=".$item['id']."&role=2");

        return __json(1,"操作成功");
    }

    // 添加日志
    public static function addLog($id,$title,$content,$username){
        $item = Db::name("bbfx_workorder")->where(['id'=>$id])->find();
        if(empty($item)){
            return __json(0,"工单不存在");
        }
        if(empty($title)){
            return __json(0,"标题不能为空");
        }
        if(empty($item)){
            return __json(0,"内容不能为空");
        }
        $probe_id = 0;
        if($title == '用户追问' || $title == '完成工单'){
            $probe = Db::name("bbfx_workorder_probe")->where(['uniacid'=>UNIACID,'pid'=>$item['id']])->order("id desc")->find();
            if(!empty($probe)){
                $item['probe'] = $probe;
                $probe_id = $probe['id'];
            }
        }
        
        $data = [
            'uniacid'=>UNIACID,
            'pid'=>$item['id'],
            'probe_id'=>$probe_id,
            'user_id'=>$item['user_id'],
            'fz_user_id'=>$item['fz_user_id'],
            'username'=>$username,
            'title'=>$title,
            'content'=>$content,
            'info'=>iserializer($item),
            'createtime'=>time()
        ];

        try {
            Db::name("bbfx_workorder_log")->insert($data);
        } catch (\Exception $e) {
            return __json(0,"内容不能为空");
        }

        return __json(1,"操作成功");
    }

    public static function getStatusText($status,$is_check,$is_reply,$num=0){
        $status_list = ['0'=>'待处理','1'=>'处理中','2'=>'已完成','3'=>'已关单'];

        if($status == 2){
            if($is_reply == 0){
                return "处理中（追问）";
            }
            else{
                if($is_check == 1){
                    return "已查看";
                }
                else{
                    return "未查看";
                }
            }
        }
        else if($status == 1){
            if($is_reply == 0 && $num > 1){
                return "处理中（追问）";
            }
        }

        return $status_list[$status];
    }
}