<?php
namespace App\Http\Controllers;

use App\Exceptions\IcException;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
use Log;
use App\Model\TemplateListModel;
use App\Model\SaleOrderListsModel;
use App\Model\TmplRelationsModel;
use App\Model\TemplateExtendModel;

Class AjaxController extends Controller
{
    public $erp;
    // 统一入口
    public function entrance(Request $request, $id)
    {
       return $this->$id($request);
    }

    // 模板列表
    public function labelList($request)
    {
        $page = $request->input("page",1);
        $limit = $request->input("limit",10);
        $template_name = $request->input("template_name",'');
        $create_username = $request->input("create_username",'');
        $status = $request->input("status",'all');
        $begin_time = $request->input("begin_time",'');
        $end_time = $request->input("end_time",'');
        $userType = $request->input("userType",0);//1只显示系统模板
        $admin_id = $request->user->userId;
        $perm = new PermController;
        // 用户角色
        $role = $perm->getUserRole($request);
        $query = TemplateListModel::select('*')->CreateUserId($admin_id,$role,$create_username,$userType)->TemplateName($template_name)
            ->Status($status)
            ->SearchTime($begin_time,$end_time)
            ->OrderBy("id","desc");
        $query = $query->paginate($limit,[],'page',$page);
        $list = $query->toArray();
//        dump($list);
        return ['code'=>0, 'count'=>$list['total'],'data'=>$list["data"]];
    }

    // 标签使用记录
    public function record($request)
    {
        $page = $request->input("page",1);
        $limit = $request->input("limit",10);
        $sale_order_sn = $request->input("sale_order_sn",'');
        $goods_type = $request->input("goods_type",'');
        $status = $request->input("status",'all');
        $begin_time = $request->input("begin_time",'');
        $end_time = $request->input("end_time",'');


        $perm = new PermController;
        // 用户角色
        $role = $perm->getUserRole($request);
        $admin_id = $request->user->userId;
        $query = TmplRelationsModel::select('*')->with("saleOrder")->CreateUserId($admin_id,$role)
            ->SaleOrderSn($sale_order_sn,$goods_type)->SearchTime($begin_time,$end_time)
            ->OrderBy("id","desc");
//        dump($query->toSql());
        $list = $query->paginate($limit,[],'page',$page);
//        dump($list);
        $arr = [];
        foreach($list as $k=>$item){
            $arr[$k]["id"] = $item->id;
            $arr[$k]["template_name"] = $item->template ? $item->template->template_name : '';
            $arr[$k]["sale_order_sn"] = $item->saleOrder ? $item->saleOrder->sale_order_sn : '';
            $arr[$k]["goods_type"] =  $item->saleOrder ? $item->saleOrder->goods_type : '';
            $arr[$k]["createUser"] =  $item->saleOrder ? $item->saleOrder->createUser : '';
            $arr[$k]["print_nums"] = $item->print_nums;
            $arr[$k]["create_time"] = date("Y-m-d h:i:s",$item->create_time);
            $arr[$k]["print_time"] = date("Y-m-d h:i:s",$item->print_time);
        }
        return ['code'=>0, 'count'=>collect($list)->get("total"),'data'=>$arr];
    }


    /*
     * 模板列表修改状态
     */
    public function template_status($request){
        $id = $request->input("id",0);
        $status = $request->input("status",0);
        $perm = new PermController;
        // 用户角色
        $role = $perm->getUserRole($request);
        $tmpl = TemplateListModel::where("create_userid",$request->user->userId)->find(intval($id));
        if($tmpl){
            $tmpl->status = ($tmpl->status == -1) ? 1 :-1;
            $tmpl->save();
            //此处推送到erp
            if(!$this->pushTemplateErp(intval($id))){
                return $this->ajaxReturn(-1,"模板信息推送至erp失败");
            }
            return $this->ajaxReturn(0,"修改成功");
        }else{
            return $this->ajaxReturn(-1,"没找到与自己对应的模板");
        }
    }

    /*
     * 模板列表修改状态
     */
    public function edit_template_info($request){
        $id = $request->input("id",0);
        $template_name = $request->input("template_name",'');
        if(!$template_name){
            return $this->ajaxReturn(-1,"模板名称必填");
        }
        $tmpl = TemplateListModel::where("create_userid",$request->user->userId)->find(intval($id));
        if(!$tmpl){
            return $this->ajaxReturn(-1,"您只能修改自己创建的模板哦!");
        }

        $count = TemplateListModel::where(["create_userid"=>$request->user->userId,"template_name"=>$template_name])->count();
        if($count > 0){
            return $this->ajaxReturn(-1,"模板名称不能重复哟!");
        }

        $tmpl->template_name = $template_name;
        $bk = $tmpl->save();
        if($bk === false){
            return $this->ajaxReturn(-1,"修改模板失败!");
        }

        //此处推送到erp
        if(!$this->pushTemplateErp(intval($id))){
            return $this->ajaxReturn(-1,"模板信息推送至erp失败");
        }


        return $this->ajaxReturn(0,"修改成功");
    }



    protected function ajaxReturn($code,$msg="",$data=[]){
        return [
            "err_code"=>$code,
            "err_msg"=>$msg,
            "data"=>$data,
        ];
    }


    /*
     * 推送模板消息到erp
     */
    protected function pushTemplateErp($t_id=0){
//        return true;
        try{
            $template = TemplateListModel::find($t_id);
//dump($template);
            //登录
            $soap = new \SoapClient(env("ERP_DOMAIN").'/ormrpc/services/EASLogin?wsdl');
            $res = $soap->login( 'TC', 'unicom', 'eas', env('ERP_DB_NAME'),  'L2', 1, 'BaseDB');
            //接口
            $this->erp = new \SoapClient(ENV("ERP_DOMAIN").'/ormrpc/services/WSIchuntjKFacade?wsdl');
            $res = $this->erp->createIssueLabel(json_encode([
                "templateId"=>$template->id,
                "templateNmae"=>$template->template_name,
                "createUser"=>$template->create_username,
                "status"=>intval($template->status),
            ]));
            if($res){
                $res = \GuzzleHttp\json_decode($res,true);
                if(isset($res["0000"])){
                    return true;
                }
            }
            return false;
        }catch(\Exception $e){
            Log::info(sprintf("模板更新信息推送到erp失败:%s",$e->getMessage()));
            return false;
        }
    }


    /*
     * 添加模板
     */
    public function add_template($request){
        $template_name = $request->input("designName",'');
        $html = $request->input("htmlp",'');
        $lableBg = $request->input("lableBg",'');
        $lableBorder = $request->input("lableBorder",'');
        $lableSize = $request->input("lableSize",'');
        if(!$template_name){
            return $this->ajaxReturn(-1,"请填写模板名称!");
        }

        if(!$html){
            return $this->ajaxReturn(-1,"模板标签是空!");
        }

        $attribute["lableBg"] = $lableBg;
        $attribute["lableBorder"] = $lableBorder;
        $attribute["lableSize"] = $lableSize;

        $data['template_name'] = $template_name;
        $data['html'] = $html;
        $data['attribute'] = $attribute;


        $id  = $request->input("t_id",0);
        if(intval($id) > 0){
//----------------------------修改模板------------------------------------------------------------------
            $count = TemplateListModel::where("id",intval($id))->where("create_userid",$request->user->userId)->count("id");
            if($count <= 0){
                return $this->ajaxReturn(-1,"没找到属于您的模板信息");
            }
            $templateInfo = TemplateListModel::where("id",intval($id))->select("id","template_name","status")->first();
            if($templateInfo->status <= 0){
                return $this->ajaxReturn(-1,"该模板已经被主人禁用了");
            }

            if($template_name != $templateInfo->template_name){
                $count = TemplateListModel::where("create_userid",$request->user->userId)->where("template_name",$template_name)->count("id");
                if($count > 0){
                    return $this->ajaxReturn(-1,"模板名称已经存在,请修改模板名称再提交!");
                }
            }

            $data['t_id'] = intval($id);
            try{
                DB::Connection("label")->transaction(function () use($data,$request) {
                    //创建模板
                    $templateList = TemplateListModel::where(["id"=>$data['t_id']])->update([
                        "template_name"=>trim($data['template_name']),
                        "update_time"=>time(),
                    ]);
                    if($templateList === false){
                        throw new \Exception("修改模板名称失败",-1);
                    }
                    //创建模板扩展信息 属性
                    $templateExtend = TemplateExtendModel::where(["template_id"=>$data['t_id']])->update([
                        "html"=>$data['html'],
                        "attribute"=>json_encode($data['attribute']),
                    ]);
                    if($templateExtend === false){
                        throw new \Exception("修改模板属性失败",-1);
                    }

                    //此处推送到erp
                    if(!$this->pushTemplateErp($data['t_id'])){
                        throw new \Exception("模板信息推送至erp失败",-1);
                    }
                });
                return $this->ajaxReturn(0,"修改模板成功");
            }catch(\Exception $e){
                return $this->ajaxReturn(-1,$e->getMessage());
            }
            exit;
        }

// --------------------------新增模板------------------------------------------------------------

        //新增模板
        $count = TemplateListModel::where("template_name",trim($data['template_name']))
            ->where(function($q) use($request){
                $q->where(["create_userid"=>$request->user->userId])->orWhere(["create_userid"=>1000]);
            })->count("id");
        if($count){
            return $this->ajaxReturn(-1,"模板名称已经存在,请修改模板名称再提交!");
        }
        try{
            DB::Connection("label")->transaction(function () use($data,$request) {
                //创建模板
                $templateList = TemplateListModel::create([
                    "template_name"=>trim($data['template_name']),
                    "create_userid"=>$request->user->userId,
                    "create_username"=>$request->user->name,
                    "create_time"=>time(),
                    "update_time"=>time(),
                ]);
                if(!$templateList){
                    throw new \Exception("添加模板失败",-1);
                }
                //创建模板扩展信息 属性
                $templateExtend = TemplateExtendModel::create([
                    "template_id"=>$templateList->id,
                    "html"=>$data['html'],
                    "attribute"=>json_encode($data['attribute']),
                ]);
                if(!$templateExtend){
                    throw new \Exception("添加模板失败",-1);
                }
                //此处推送到erp
                if(!$this->pushTemplateErp($templateList->id)){
                    throw new \Exception("模板信息推送至erp失败",-1);
                }
            });
            return $this->ajaxReturn(0,"添加模板成功");
        }catch(\Exception $e){
            return $this->ajaxReturn(-1,$e->getMessage());
        }


    }

    /*
     * 推送模板信息到erp
     */
    public function push_template_erp($request){
        $id  = $request->input("t_id",0);
        $template = TemplateListModel::where(["create_userid"=>$request->user->userId])->find($id);
        if(!$template){
            return $this->ajaxReturn(-1,"没找到属于您的模板相关信息");
        }
        //此处推送到erp
        if(!$this->pushTemplateErp($template->id)){
            return $this->ajaxReturn(-1,"模板信息推送至erp失败");
        }
        return $this->ajaxReturn(0,"推送模板成功");
    }


    /*
     * 复制模板
     */
    public function copy_template($request){
        $id  = $request->input("t_id",0);
        $copyTemplate = TemplateListModel::find($id);
        if(!$copyTemplate){
            return $this->ajaxReturn(-1,"没找到该模板相关信息");
        }
        try{
           DB::Connection("label")->transaction(function () use($copyTemplate,$request) {
               $templateList = TemplateListModel::create([
                    "template_name"=>$copyTemplate->template_name."_copy"."_".date("Ymdhis"),
                    "create_userid"=>$request->user->userId,
                    "create_username"=>$request->user->name,
                    "create_time"=>time(),
                    "update_time"=>time(),
                ]);
               if(!$templateList){
                   throw new \Exception("复制模板失败",-1);
               }

               //创建模板扩展信息 属性
               $templateExtend = TemplateExtendModel::create([
                   "template_id"=>$templateList->id,
                   "html"=>$copyTemplate->template_extend->html,
                   "attribute"=>$copyTemplate->template_extend->attribute,
               ]);
               if(!$templateExtend){
                   throw new \Exception("复制模板失败",-1);
               }
               //此处推送到erp
               if(!$this->pushTemplateErp($templateList->id)){
                   throw new \Exception("模板信息推送至erp失败",-1);
               }

            });
            $data = [];
            if($copyTemplate->create_userid == "1000"){
                $data = ["redictUrl"=>"/web/labelList"];
            }
            return $this->ajaxReturn(0,"复制模板成功",$data);
        }catch(\Exception $e){
            return $this->ajaxReturn(-1,$e->getMessage());
        }

    }


    /**
     * 编辑模板 获取模板详情
     */
    public function getTemplateDetail($request){
        $id  = $request->input("t_id",0);
        $count = TemplateListModel::where("id",intval($id))->where("create_userid",$request->user->userId)->count("id");
        if($count <= 0){
            return $this->ajaxReturn(-1,"没找到属于您的模板信息");
        }
        $templateInfo = TemplateListModel::where("id",intval($id))->select("id","template_name","status")->first();
        if($templateInfo->status <= 0){
            return $this->ajaxReturn(-1,"该模板已经被主人禁用了");
        }
        $templateInfo->template_extend = isset($templateInfo->template_extend) ? $templateInfo->template_extend : null;
        return $this->ajaxReturn(0,"ok",$templateInfo);
    }


}