<?php
namespace app\bsadmin\controller;
use think\facade\Cache;
use think\facade\View;
use think\facade\Db;
use think\facade\Validate;
use app\common\model\Vip as VipModel;
use app\common\model\VipRule as VipRuleModel;
use app\common\model\VipRuleValue as VipRuleValueModel;
use app\common\model\VipValueAdded as VipValueAddedModel;
use app\common\model\VipValueAddedDiscount as VipValueAddedDiscountModel;
use app\common\model\StatusAlias as StatusAliasModel;
class Vip extends Base
{
    public function index()
    {
        if (request()->isAjax()) {
            $Data=VipModel::alias('vip')
                ->field('vip.*')
                ->order('id desc')->paginate(100)->each(function($v){
                    $v['start_time']=$v['start_time']?date('Y-m-d',$v['start_time']):'';
                    $v['end_time']=$v['end_time']?date('Y-m-d',$v['end_time']):'';
                    $v['icon']=$v['icon']?config('web.imgurl').$v['icon']:'';
	                $v['rule']=VipRuleValueModel::alias('value')
	                ->join(config('databse.prefix').'vip_rule rule','rule.rid=value.id AND rule.vid='.$v['id'],'LEFT')
	                ->field('rule.id,rule.value,value.unit,value.id as rid,value.title,value.alias,value.value as vvalue,value.desc,value.type')
	                ->withAttr('value',function($v,$data){
	                    if ($v===null) {
	                        return $data['vvalue'];
	                    }else{
	                        return $v;
	                    }
	                })
	                ->select();
                    $v['vip']=VipValueAddedDiscountModel::alias('discount')
                    ->where(['discount.vid'=>$v['id']])
                    ->where(['type.alias'=>'vip/value_added_type'])
                    ->join('status_alias type','type.value=discount.type','LEFT')
                    ->field('type.title,discount.discount')->select();
                    return $v;
                });
            if ($Data->items()) {
                return $this->ajaxReturn('',0,$Data);
            }else{
                return $this->ajaxReturn('暂无数据~',-100);
            }
        }else{
	    	return View::fetch();
        }
    }
    /**
     * 编辑套餐
     */
    public function edit($id)
    {
        if(request()->isPost()){
            $D=request()->post();
            $rule =   [
                'title'         => 'require|max:30',
                'is_company'    => 'require',
                'status'        => 'require',
                'price'         => 'require',
                'discount'      => 'require',
                'va_discount'   => 'require',
                'stock'         => 'require',
                'level'         => 'require',
            ];
            $msg  =   [
                'title.require'     => '名称不能为空', 
                'title.max'         => '名称不能超过30个字符',
                'is_company.require'=> '请选择套餐类型',
                'status.require'    => '请选择套餐状态',
                'price.require'     => '请输入售价',
                'discount.require'  => '请输入折扣',
                'va_discount.require'=> '请输入增值服务折扣',
                'stock.require'     => '请输入库存',
                'level.require'     => '优先级不能为空',
            ];
            $Validate=Validate::rule($rule)->message($msg);
            $result = $Validate->check($D);
            if(!$result){return $this->ajaxReturn($Validate->getError(),-100);}
            $VipModel=VipModel::find($id);
            $VipModel->title        = $D['title'];
            $VipModel->icon         = $D['icon'];
            $VipModel->is_company   = $D['is_company'];
            $VipModel->status       = $D['status'];
            $VipModel->level        = $D['level'];
            $VipModel->price        = $D['price'];
            $VipModel->discount     = $D['discount'];
            $VipModel->va_discount  = $D['va_discount'];
            if (intval($D['add_stock'])) {
                $VipModel->stock        = $VipModel->stock+intval($D['add_stock']);
                $VipModel->surplus_stock= $VipModel->surplus_stock+intval($D['add_stock']);
            }
            if ($D['cancel_stock']) {
                $VipModel->stock        = 0;
                $VipModel->surplus_stock= 0;
            } 
            if (intval($D['sold']))
                $VipModel->sold        = intval($D['sold']);

            if (strtotime($D['start_time'])){
                $VipModel->start_time= strtotime($D['start_time'].' 08:00:00');
            }else{
                $VipModel->start_time= null;
            }
            if (strtotime($D['end_time'])){
                $VipModel->end_time= strtotime($D['end_time'].' 23:59:59');
            }else{
                $VipModel->end_time= null;
            }
            $VipRule=[];
            if (!empty($D['rule'])) {
	            $VipRuleModel=new VipRuleModel;
	            foreach ($D['rule'] as $k => $v) {
	            	$VipRule[$k]=[
	            		'rid'	=>	$v['rid'],
	            		'value'	=>	$v['value']
	            	];
	            	if($v['id'])
	            		$VipRule[$k]['id']=$v['id'];
	            }
            }
            $Discount=[];
            if (!empty($D['va'])) {
                $VipValueAddedDiscountModel=new VipValueAddedDiscountModel;
                foreach ($D['va'] as $k => $v) {
                    if ($v['is_company']==$D['is_company']) {
                        $Discount[$k]=[
                            'type'      =>  $v['value'],
                            'discount'  =>  empty($v['discount'])?$D['va_discount']:$v['discount']
                        ];
                        if($v['id'])
                            $Discount[$k]['id']=$v['id'];
                    }
                }
            }
            // 启动事务
            Db::startTrans();
            try {
                $VipModel->save();
	            if (!empty($VipRule)) {
	                array_walk($VipRule,function(&$v,$k)use($VipModel){
	                    $v['vid']=$VipModel->id;
	                    krsort($v);
	                });
	                $VipRuleModel->saveAll($VipRule);
	            }
                if (!empty($Discount)) {
                    array_walk($Discount,function(&$v,$k)use($VipModel){
                        $v['vid']=$VipModel->id;
                        krsort($v);
                    });
                    $VipValueAddedDiscountModel->saveAll($Discount);
                }
                // 提交事务
                Db::commit();
                return $this->ajaxReturn('保存成功');
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $this->ajaxReturn('保存失败，请重试',-200);
            }
        }else{
            $VipRuleValue=VipRuleValueModel::where(['status'=>1])->field('id as rid,title,alias,value,desc,type')->select();
            View::assign('VipRuleValue',$VipRuleValue);
            $Find=VipModel::where(['id'=>$id])
                ->withAttr('start_time',function($v,$d){
                    return $v?date('Y-m-d',$v):'';
                })
                ->withAttr('end_time',function($v,$d){
                    return $v?date('Y-m-d',$v):'';
                })->find();
            $Find->add_stock='';
            $Find->cancel_stock=0;
            if ($Find){
                $Find->rule=VipRuleValueModel::alias('value')
                ->join(config('databse.prefix').'vip_rule rule','rule.rid=value.id AND rule.vid='.$id,'LEFT')
                ->field('rule.id,rule.value,value.id as rid,value.title,value.alias,value.value as vvalue,value.unit,value.desc,value.type')
                ->withAttr('value',function($v,$data){
                    if ($v===null) {
                        return $data['vvalue'];
                    }else{
                        return $v;
                    }
                })
                ->select();
                $Find->va=StatusAliasModel::alias('type')
                ->where(['type.alias'=>'vip/value_added_type'])
                ->join('vip_value_added_discount discount','discount.type=type.value AND discount.vid='.$id,'LEFT')
                ->field('discount.id,type.title,type.value,type.is_company,discount.discount')
                ->order('type.value asc')->select();
            }
            if (request()->isAjax())
                return $this->ajaxReturn('',0,$Find);
            View::assign('Find',$Find);
            return View::fetch('add');
        }
    }
    /**
     * 创建套餐
     */
    public function add()
    {
        if(request()->isPost()){
            $D=request()->post();
            $rule =   [
                'title'         => 'require|max:30',
                'is_company'    => 'require',
                'status'        => 'require',
                'price'         => 'require',
                'discount'      => 'require',
                'va_discount'   => 'require',
                'stock'         => 'require',
	            'level'         => 'require',
            ];
            $msg  =   [
                'title.require'     => '名称不能为空', 
                'title.max'         => '名称不能超过30个字符',
	            'is_company.require'=> '请选择套餐类型',
                'status.require'    => '请选择套餐状态',
                'price.require'     => '请输入售价',
                'discount.require'  => '请输入折扣',
                'va_discount.require'=> '请输入增值服务折扣',
                'stock.require'     => '请输入库存',
                'level.require'     => '优先级不能为空',
            ];
            $Validate=Validate::rule($rule)->message($msg);
            $result = $Validate->check($D);
            if(!$result){return $this->ajaxReturn($Validate->getError(),-100);}
            $VipModel=new VipModel;
            $VipModel->title        = $D['title'];
            $VipModel->icon         = $D['icon'];
            $VipModel->is_company   = $D['is_company'];
            $VipModel->status       = $D['status'];
            $VipModel->level   	    = $D['level'];
            $VipModel->price   	    = $D['price'];
            $VipModel->discount     = $D['discount'];
            $VipModel->va_discount  = $D['va_discount'];
            $VipModel->stock        = intval($D['stock']);
            $VipModel->surplus_stock= intval($D['stock']);
            $VipModel->sold         = 0;
            if (intval($D['surplus_stock']))
                $VipModel->surplus_stock        = intval($D['surplus_stock']);
            if (intval($D['stock'])&&intval($D['surplus_stock']))
                $VipModel->sold        = intval($D['stock'])-intval($D['surplus_stock']);
            if (strtotime($D['start_time']))
                $VipModel->start_time= strtotime($D['start_time'].' 08:00:00');
            if (strtotime($D['end_time']))
                $VipModel->end_time= strtotime($D['end_time'].' 23:59:59');
            $VipRule=[];
            if (!empty($D['rule'])) {
	            $VipRuleModel=new VipRuleModel;
	            foreach ($D['rule'] as $k => $v) {
	            	$VipRule[]=[
	            		'rid'	=>	$v['rid'],
	            		'value'	=>	$v['value']
	            	];
	            }
            }
            $Discount=[];
            if (!empty($D['va'])) {
                $VipValueAddedDiscountModel=new VipValueAddedDiscountModel;
                foreach ($D['va'] as $k => $v) {
                    if ($v['is_company']==$D['is_company']) {
                        $Discount[]=[
                            'type'      =>  $v['value'],
                            'discount'  =>  empty($v['discount'])?$D['va_discount']:$v['discount']
                        ];
                    }
                }
            }
            // 启动事务
            Db::startTrans();
            try {
                $VipModel->save();
	            if (!empty($VipRule)) {
	                array_walk($VipRule,function(&$v,$k)use($VipModel){
	                    $v['vid']=$VipModel->id;
	                    krsort($v);
	                });
	                $VipRuleModel->saveAll($VipRule);
	            }
                if (!empty($Discount)) {
                    array_walk($Discount,function(&$v,$k)use($VipModel){
                        $v['vid']=$VipModel->id;
                        krsort($v);
                    });
                    $VipValueAddedDiscountModel->saveAll($Discount);
                }
                // 提交事务
                Db::commit();
                return $this->ajaxReturn('保存成功');
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $this->ajaxReturn('保存失败，请重试',-200);
            }
        }else{
            $VipValueAdded=StatusAliasModel::where(['alias'=>'vip/value_added_type'])
            ->field('title,value,is_company')
            ->order('value asc')->select();
            View::assign('VipValueAdded',$VipValueAdded);
            $VipRuleValue=VipRuleValueModel::where(['status'=>1])->field('id as rid,title,unit,alias,value,desc,type')->select();
            View::assign('VipRuleValue',$VipRuleValue);
            return View::fetch();
        }
    }
    /**
     * 设置套餐状态
     */
    public function setStatus($id,$status)
    {
        $VipModel=VipModel::find($id);
        $VipModel->status=$status;
        if ($VipModel->save()) {
            return $this->ajaxReturn();
        }else{
            return $this->ajaxReturn('保存失败，请重试',-100);
        }
    }
    public function setDefault($id)
    {
        $VipModel=VipModel::find($id);
        $VipModel->default=1;
        $VipDefault=VipModel::where(['default'=>1,'is_company'=>$VipModel->is_company])->find();
        if ($VipDefault)
            $VipDefault->default=0;
        // 启动事务
        Db::startTrans();
        try {
            $VipModel->save();
            if($VipDefault)$VipDefault->save();
            // 提交事务
            Db::commit();
            return $this->ajaxReturn('保存成功');
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return $this->ajaxReturn('保存失败，请重试',-200);
        }
    }
    public function vipRule()
    {
        if (request()->isAjax()) {
            $Data=VipRuleValueModel::select();
            if ($Data) {
                return $this->ajaxReturn('',0,$Data);
            }else{
                return $this->ajaxReturn('暂无数据~',-100);
            }
        }else{
            return View::fetch();
        }
    }
    public function editVipRule($id)
    {
        if(request()->isPost()){
            $D=request()->post();
            $rule =   [
                'title'         => 'require|max:30',
                'alias'         => 'require|unique:vipRuleValue',
                'status'        => 'require',
                'value'         => 'require',
                'type'          => 'require',
            ];
            $msg  =   [
                'title.require'     => '名称不能为空', 
                'title.max'         => '名称不能超过30个字符',
                'alias.require'     => '请输入规则别名',
                'alias.unique'      => '规则别名已存在',
                'status.require'    => '请选择规则状态',
                'value.require'     => '请输入默认值',
                'type.require'      => '请选择规则类型',
            ];
            $Validate=Validate::rule($rule)->message($msg);
            $result = $Validate->check($D);
            if(!$result){return $this->ajaxReturn($Validate->getError(),-100);}
            $VipRuleValueModel=VipRuleValueModel::where(['id'=>$id])->find();
            $VipRuleValueModel->title        = $D['title'];
            $VipRuleValueModel->alias        = $D['alias'];
            $VipRuleValueModel->status       = $D['status'];
            $VipRuleValueModel->unit         = $D['unit'];
            $VipRuleValueModel->value        = $D['value'];
            $VipRuleValueModel->type         = $D['type'];
            $VipRuleValueModel->desc         = $D['desc'];
            $VipRuleValueModel->tips         = $D['tips'];
            // 启动事务
            Db::startTrans();
            try {
                $VipRuleValueModel->save();
                // 提交事务
                Db::commit();
                return $this->ajaxReturn('保存成功');
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $this->ajaxReturn('保存失败，请重试',-200);
            }
        }else{
            $VipRuleValueModel=VipRuleValueModel::where(['id'=>$id])->find();
            View::assign('Find',$VipRuleValueModel);
            return View::fetch('add_vip_rule');
        }
    }
    public function addVipRule()
    {
        if(request()->isPost()){
            $D=request()->post();
            $rule =   [
                'title'         => 'require|max:30',
                'alias'         => 'require|unique:vipRuleValue',
                'status'        => 'require',
                'value'         => 'require',
                'type'          => 'require',
            ];
            $msg  =   [
                'title.require'     => '名称不能为空', 
                'title.max'         => '名称不能超过30个字符',
                'alias.require'     => '请输入规则别名',
                'alias.unique'      => '规则别名已存在',
                'status.require'    => '请选择规则状态',
                'value.require'     => '请输入默认值',
                'type.require'      => '请选择规则类型',
            ];
            $Validate=Validate::rule($rule)->message($msg);
            $result = $Validate->check($D);
            if(!$result){return $this->ajaxReturn($Validate->getError(),-100);}
            $VipRuleValueModel=new VipRuleValueModel;
            $VipRuleValueModel->title        = $D['title'];
            $VipRuleValueModel->alias        = $D['alias'];
            $VipRuleValueModel->status       = $D['status'];
            $VipRuleValueModel->value        = $D['value'];
            $VipRuleValueModel->unit         = $D['unit'];
            $VipRuleValueModel->type         = $D['type'];
            $VipRuleValueModel->desc         = $D['desc'];
            $VipRuleValueModel->tips         = $D['tips'];
            // 启动事务
            Db::startTrans();
            try {
                $VipRuleValueModel->save();
                // 提交事务
                Db::commit();
                return $this->ajaxReturn('保存成功');
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $this->ajaxReturn('保存失败，请重试',-200);
            }
        }else{
            return View::fetch();
        }
    }
    /**
     * 设置套餐状态
     */
    public function setVipRuleStatus($id,$status)
    {
        $VipRuleValueModel=VipRuleValueModel::find($id);
        $VipRuleValueModel->status=$status;
        if ($VipRuleValueModel->save()) {
            return $this->ajaxReturn();
        }else{
            return $this->ajaxReturn('保存失败，请重试',-100);
        }
    }
    public function valueAdded()
    {
        if (request()->isAjax()) {
            $Data=VipValueAddedModel::alias('va')
                ->where(['type.alias'=>'vip/value_added_type'])
                ->join(config('databse.prefix').'status_alias type','type.value=va.type')
                ->field('va.*,type.title as type_text,type.type as unit')
                ->order('type asc,level asc,id asc')->paginate(100)->each(function($v){
                    $v['start_time']=$v['start_time']?date('Y-m-d',$v['start_time']):'';
                    $v['end_time']=$v['end_time']?date('Y-m-d',$v['end_time']):'';
                    return $v;
                });
            if ($Data->items()) {
                return $this->ajaxReturn('',0,$Data);
            }else{
                return $this->ajaxReturn('暂无数据~',-100);
            }
        }else{
            $ValueAddedType=StatusAliasModel::where(['alias'=>'vip/value_added_type'])->field('title as text,value,type')->select();
            View::assign('ValueAddedType',$ValueAddedType);
            return View::fetch();
        }
    }
    public function editValueAdded($id)
    {
        if(request()->isPost()){
            $D=request()->post();
            $rule =   [
                'title'         => 'require|max:30',
                'type'          => 'require',
                'is_company'    => 'require',
                'effective_day' => 'require',
                'value'         => 'require',
                'status'        => 'require',
                'price'         => 'require',
                'stock'         => 'require',
                'level'         => 'require',
            ];
            $msg  =   [
                'title.require'     => '名称不能为空', 
                'title.max'         => '名称不能超过30个字符',
                'type.require'      => '请选择类型',
                'is_company.require'=> '请选择类型',
                'effective_day.require'=> '有效期不能为空',
                'value.require'     => '数量不能为空',
                'status.require'    => '请选择状态',
                'price.require'     => '请输入售价',
                'stock.require'     => '请输入库存',
                'level.require'     => '优先级不能为空',
            ];
            $Validate=Validate::rule($rule)->message($msg);
            $result = $Validate->check($D);
            if(!$result){return $this->ajaxReturn($Validate->getError(),-100);}
            $VipValueAddedModel=VipValueAddedModel::where(['id'=>$id])->find();
            $VipValueAddedModel->title        = $D['title'];
            $VipValueAddedModel->type         = $D['type'];
            $VipValueAddedModel->is_company   = $D['is_company'];
            $VipValueAddedModel->value        = $D['value'];
            $VipValueAddedModel->status       = $D['status'];
            $VipValueAddedModel->level        = $D['level'];
            $VipValueAddedModel->price        = $D['price'];
            $VipValueAddedModel->stock        = intval($D['stock']);
            $VipValueAddedModel->surplus_stock= intval($D['stock']);
            $VipValueAddedModel->effective_day= intval($D['effective_day']);
            if (intval($D['add_stock'])) {
                $VipValueAddedModel->stock          = $VipValueAddedModel->stock+intval($D['add_stock']);
                $VipValueAddedModel->surplus_stock  = $VipValueAddedModel->surplus_stock+intval($D['add_stock']);
            }
            if ($D['cancel_stock']) {
                $VipValueAddedModel->stock          = 0;
                $VipValueAddedModel->surplus_stock  = 0;
            } 
            if (intval($D['sold']))
                $VipValueAddedModel->sold           = intval($D['sold']);

            if (strtotime($D['start_time'])){
                $VipValueAddedModel->start_time     = strtotime($D['start_time'].' 08:00:00');
            }else{
                $VipValueAddedModel->start_time     = null;
            }
            if (strtotime($D['end_time'])){
                $VipValueAddedModel->end_time       = strtotime($D['end_time'].' 23:59:59');
            }else{
                $VipValueAddedModel->end_time       = null;
            }
            // 启动事务
            Db::startTrans();
            try {
                $VipValueAddedModel->save();
                // 提交事务
                Db::commit();
                return $this->ajaxReturn('保存成功');
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $this->ajaxReturn('保存失败，请重试',-200);
            }
        }else{
            $ValueAddedType=StatusAliasModel::where(['alias'=>'vip/value_added_type'])->field('title,value,type,is_company')->select();
            View::assign('ValueAddedType',$ValueAddedType);
            $Find=VipValueAddedModel::where(['id'=>$id])
                ->withAttr('start_time',function($v,$d){
                    return $v?date('Y-m-d',$v):'';
                })
                ->withAttr('end_time',function($v,$d){
                    return $v?date('Y-m-d',$v):'';
                })->find();
            $Find->add_stock='';
            $Find->cancel_stock=0;
            if (request()->isAjax())
                return $this->ajaxReturn('',0,$Find);
            View::assign('Find',$Find);
            return View::fetch('add_value_added');
        }
    }
    public function addValueAdded()
    {
        if(request()->isPost()){
            $D=request()->post();
            $rule =   [
                'title'         => 'require|max:30',
                'type'          => 'require',
                'is_company'    => 'require',
                'effective_day' => 'require',
                'value'         => 'require',
                'status'        => 'require',
                'price'         => 'require',
                'stock'         => 'require',
                'level'         => 'require',
            ];
            $msg  =   [
                'title.require'     => '名称不能为空', 
                'title.max'         => '名称不能超过30个字符',
                'type.require'      => '请选择类型',
                'is_company.require'=> '请选择类型',
                'effective_day.require'=> '有效期不能为空',
                'value.require'     => '数量不能为空',
                'status.require'    => '请选择状态',
                'price.require'     => '请输入售价',
                'stock.require'     => '请输入库存',
                'level.require'     => '优先级不能为空',
            ];
            $Validate=Validate::rule($rule)->message($msg);
            $result = $Validate->check($D);
            if(!$result){return $this->ajaxReturn($Validate->getError(),-100);}
            $VipValueAddedModel=new VipValueAddedModel;
            $VipValueAddedModel->title        = $D['title'];
            $VipValueAddedModel->type         = $D['type'];
            $VipValueAddedModel->is_company   = $D['is_company'];
            $VipValueAddedModel->value        = $D['value'];
            $VipValueAddedModel->status       = $D['status'];
            $VipValueAddedModel->level        = $D['level'];
            $VipValueAddedModel->price        = $D['price'];
            $VipValueAddedModel->stock        = intval($D['stock']);
            $VipValueAddedModel->surplus_stock= intval($D['stock']);
            $VipValueAddedModel->sold         = 0;
            $VipValueAddedModel->effective_day= intval($D['effective_day']);
            if (intval($D['surplus_stock']))
                $VipValueAddedModel->surplus_stock        = intval($D['surplus_stock']);
            if (intval($D['stock'])&&intval($D['surplus_stock']))
                $VipValueAddedModel->sold        = intval($D['stock'])-intval($D['surplus_stock']);
            if (strtotime($D['start_time']))
                $VipValueAddedModel->start_time= strtotime($D['start_time'].' 08:00:00');
            if (strtotime($D['end_time']))
                $VipValueAddedModel->end_time= strtotime($D['end_time'].' 23:59:59');
            // 启动事务
            Db::startTrans();
            try {
                $VipValueAddedModel->save();
                // 提交事务
                Db::commit();
                return $this->ajaxReturn('保存成功');
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return $this->ajaxReturn('保存失败，请重试',-200);
            }
        }else{
            $ValueAddedType=StatusAliasModel::where(['alias'=>'vip/value_added_type'])->field('title,value,type,is_company')->select();
            View::assign('ValueAddedType',$ValueAddedType);
            return View::fetch();
        }
    }
    /**
     * 设置套餐状态
     */
    public function setValueAddedStatus($id,$status)
    {
        $VipValueAddedModel=VipValueAddedModel::find($id);
        $VipValueAddedModel->status=$status;
        if ($VipValueAddedModel->save()) {
            return $this->ajaxReturn();
        }else{
            return $this->ajaxReturn('保存失败，请重试',-100);
        }
    }
}
