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

namespace app\api\controller\workorder;

use app\api\controller\Base;
use think\Db;


class Workorder extends Base
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];
    
    public $model = null;
    public function _initialize(){
        parent::_initialize();
        $this->model = new \app\common\model\bbfxshop\Workorder;
    }
    
    public function submit(){
        $params = $this->param(["category_id/d",'title/s','content/s','images/a','form/a']);

        $config = $this->model->getSet();
        if($config['status'] != 1){
            __success("工单未开启");
        }

        $category = Db::name("bbfx_workorder_category")->where(['id'=>$params['category_id']])->find();
        
        if(empty($category)){
            __error("分类信息错误");
        }
        if(empty($params['title'])){
            __error("请填写工单标题");
        }
        if(empty($params['content'])){
            __error("请填写问题描述");
        }

        $form_content = $params['form'];
        if(empty($form_content)){
            __error("请提交表单内容");
        }
        foreach ($form_content as $key => &$val){
            if($val['required'] && empty($val['value'])){
                if($val['type'] == 'image' || $val['type'] == 'images'){
                    __error("请上传".$val['label']);
                }
                else if($val['type'] == 'select' || $val['type'] == 'radio'){
                    __error("请选择".$val['label']);
                }
                else{
                    __error("请填写".$val['label']);
                }
            }
            if($val['type'] == 'image'){
                $val['value'] = replaceSiteroot($val['value']);
            }
            else if($val['type'] == 'images'){
                foreach($val['value'] as $k => &$v){
                    $v = replaceSiteroot($v);
                }
                unset($v);
            }
        } 
        unset($val);

        $data = [
            'uniacid'=>UNIACID,
            'user_id'=>$this->user['id'],
            'category_id'=>$category['id'],
            'title'=>$params['title'],
            'content'=>$params['content'],
            "images"=>iserializer(replaceSiteroots($params['images'])),
            'form'=>iserializer($form_content),
            'info'=>iserializer($category)
        ];

        $item = Db::name("bbfx_workorder")->where($data)->find();

        try { 
            Db::startTrans();

            $data['createtime'] = time();
            $id = Db::name("bbfx_workorder")->insertGetId($data);

            $probe_data = [
                'uniacid'=>UNIACID,
                'type'=>1,
                'user_id'=>$data['user_id'],
                'fz_user_id'=>0,
                'pid'=>$id,
                'content'=>$data['content'],
                'images'=>$data['images'],
                'createtime'=>time()
            ];

            Db::name("bbfx_workorder_probe")->insertGetId($probe_data);

            $this->model->addLog($id,"提交工单","用户提交工单到后台。",$this->user['nickname']);

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            __error($e->getMessage());
        }
         
        // $this->model->allocate($id);

        $this->model->sendNewOrderNotice($id);

        __success("操作成功");
    }

    public function probe(){
        $params = $this->param(["id/d",'content/s','images/a']);

        $item = Db::name("bbfx_workorder")->where(['id'=>$params['id']])->find();
        if(empty($item)){
            __error("工单信息错误");
        }
        if($item['status'] == 3){
            __error("工单已关单，请重新提交工单！");
        }
        if($item['status'] < 2){
            // __error("工单处理中，请稍后追问");
        }
        if(empty($params['content'])){
            __error("请填写追问问题");
        }

        $probe = Db::name("bbfx_workorder_probe")->where(['uniacid'=>UNIACID,'pid'=>$item['id'],'status'=>0])->find();
        if(!empty($probe)){
            // __error("您上次追问的工单还在处理中，请稍后追问");
        }

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

        $fz_user = Db::name("bbfx_workorder_user")->where(['id'=>$item['fz_user_id']])->find();

        try { 
            $id = Db::name("bbfx_workorder_probe")->insertGetId($data);
            Db::name("bbfx_workorder")->where(['id'=>$item['id']])->update(['is_check'=>0,'is_reply'=>0]);
            
            $this->model->addLog($item['id'],"用户追问","用户提交工单追问。",$this->user['nickname']);
            if(!empty($fz_user)){
                $this->model->sendNotice($fz_user['user_id'],"用户追问","用户提交新问题，请尽快查看问题内容！","/plugin/work_order/detail?id=".$item['id']."&role=1");
            }
            
        } catch (\Exception $e) {
            __error($e->getMessage());
        }

        __success("操作成功");
    }

    
    public function close(){
        $id = $this->param("id/d");
        $result = $this->model->close($id,$this->user['id'],2);
        __result($result);
    }
    
    public function getList(){
        $list = Db::name("bbfx_workorder")->where(['uniacid'=>UNIACID,'user_id'=>$this->user['id']])->field("id,title,status,is_reply,is_check,content,createtime")->order("id desc")->select();
    
        foreach($list as $key => &$val){
            $prob_count = Db::name("bbfx_workorder_probe")->where(['uniacid'=>UNIACID,'pid'=>$val['id']])->count();
            $val['prob_count'] = intval($prob_count);
            $val['createtime'] = date("Y-m-d H:i:s",$val['createtime']);
            $val['status_text'] = $this->model->getStatusText($val['status'],$val['is_check'],$val['is_reply'],$val['prob_count']);
            if($val['status'] == 0){
                // $this->model->allocate($val['id']);
            }
        }
        unset($val);

        __success("操作成功",['list'=>$list]);
    }

    public function detail(){
        $id = $this->param("id/d");
        $info = Db::name("bbfx_workorder")->where(['uniacid'=>UNIACID,'id'=>$id,'user_id'=>$this->user['id']])->find();
        if(empty($info)){
            __error("工单不存在");
        }
        $info['createtime'] = date("Y-m-d H:i:s",$info['createtime']);
        if($info['status'] > 0) $info['cltime'] = date("Y-m-d H:i:s",$info['cltime']);
        if($info['status'] > 1) $info['completetime'] = date("Y-m-d H:i:s",$info['completetime']);
        if($info['status'] > 2) $info['closetime'] = date("Y-m-d H:i:s",$info['closetime']);
        $info['images'] = cdnurls(iunserializer($info['images']));

        if($info['is_check'] == 0){
            $info['is_check'] = 1;
            $info['checktime'] = date("Y-m-d H:i:s",$info['checktime']);
            Db::name("bbfx_workorder")->where(['id'=>$info['id']])->update(['is_check'=>1,'checktime'=>time()]);
        }
        $prob_count = Db::name("bbfx_workorder_probe")->where(['uniacid'=>UNIACID,'pid'=>$info['id']])->count();
        $info['prob_count'] = intval($prob_count);
        $info['status_text'] = $this->model->getStatusText($info['status'],$info['is_check'],$info['is_reply'],$info['prob_count']);
        $info['form'] = iunserializer($info['form']);
        foreach($info['form'] as $key => &$val){
            if($val['type'] == 'image'){
                $val['value'] = cdnurl($val['value']);
            }
            else if($val['type'] == 'images'){
                foreach($val['value'] as $k => &$v){
                    $v = cdnurl($v);
                }
                unset($v);
            }
        }
        unset($val);

        $probe_list = Db::name("bbfx_workorder_probe")->alias("a")->join("bbfx_workorder_user b","a.fz_user_id=b.id","LEFT")->join("bbfx_user c","b.user_id=c.id","LEFT")->where(['a.uniacid'=>UNIACID,'a.pid'=>$info['id']])->field("a.*,b.name as username,c.avatar")->order("a.id asc")->select();
        foreach($probe_list as $key => &$val){
            $val['images'] = cdnurls(iunserializer($val['images']));
            $val['avatar'] = cdnurl($val['avatar']);
            $val['createtime'] = date("Y-m-d H:i:s",$val['createtime']);
            if($val['replytime'] > 0){
                $val['replytime'] = date("Y-m-d H:i:s",$val['replytime']);
            }
            else{
                $val['replytime'] = '';
            }
        }
        unset($val);

        $info['probe_list'] = $probe_list;
        $where = ['a.uniacid'=>UNIACID,'a.id'=>$info['fz_user_id']];
        $fz_user = Db::name("bbfx_workorder_user")->alias("a")->join("bbfx_user b","a.user_id=b.id","LEFT")->where($where)->field("a.name,b.nickname,b.avatar")->find();
        if(empty($fz_user['avatar'])){
            $fz_user['avatar'] = "/assets/images/avatar.jpg";
        }
        if(empty($fz_user['nickname'])){
            $fz_user['nickname'] = $fz_user['name'];
        }
        $fz_user['avatar'] = cdnurl($fz_user['avatar']);
        $info['fz_user'] = $fz_user;
        $info['user'] = ['nickname'=>$this->user['nickname'],'avatar'=>$this->user['avatar']];

        __success("操作成功",$info);
    }
}