<?php
/**
 * 首页控制器
 */
namespace app\modules\shops\v1\controllers;
use app\modules\common\Helper;
use app\modules\common\Verify;
use app\modules\logic\services\UserService;
use app\modules\logic\services\AccountService;
use app\modules\logic\services\CouponService;
use app\modules\logic\model\NoticeModel;
use app\modules\logic\model\OrderModel;
use app\modules\logic\model\UsersShopInfoModel;
use app\modules\logic\model\UsersModel;
use app\modules\logic\model\AccountLogModel;
use app\modules\logic\model\UsersCouponModel;
use app\modules\logic\model\CouponListModel;
use Yii;
use yii\web\Controller;

class HomeController extends MiddleController {
	/**
	 * 返回
	 * @param $code
	 * @param string $info
	 * @param string $controller
	 * @param string $total
	 */
	protected function response($code, $info = '', $total = '', $controller = 'home') {
		return parent::response($code, $info, $total, $controller);
	}
	/**
	 * [actionIndex 获取首页配置]
	 * @apiDoc
	 * @api     v1/home/index
	 * @group   home
	 * @name    获取首页配置
	 * @desc    获取门店App首页配置
	 * @method  POST
	 * @author JOHN.W
	 * @version [1.0]
	 * @return  json
		{
		"code": "000000",
		"msg": "获取成功",
		"info": {
		"account": {
		    "total_amount": "-29.02",
		    "frost_amount": "0.00",
		    "use_amount": "-29.02",
		    "total_gold": "79.98",
		    "user_id": "2"
		},
		"credit": {
		    "use_amount": -29.02
		},
		"coupon": {
		    "total": 0,
		    "list": []
		},
		"wait_pay_num": "0",
		"wait_confirm_num": "0",
		"wait_comment_num": "0",
		"wait_rece_num": "0",//待接单
		"wait_order_list": [
		    {
		        "order_id": "1",
		        "status": "0",
		        "plate_no": "川A12356",
		        "carmodel_id": "2",
		        "pro_extra": "1",
		        "abn_status": "0",
		        "pro_extra_show": "美容-保养",
		        "carmodel_id_show": "越野车",
		        "status_show": "待付款"
		    },
		    {
		        "order_id": "2",
		        "status": "1",
		        "plate_no": "川A12357",
		        "carmodel_id": "2",
		        "pro_extra": "1",
		        "abn_status": "0",
		        "pro_extra_show": "美容-保养",
		        "carmodel_id_show": "越野车",
		        "status_show": "待接单"
		    }
		]
		}
		}
	 */
	public function actionIndex(){
		if (empty($this->user_id)) {
            return $this->response('para_miss_user', '未能识别用户标志');
        }
        //获取账户信息
        $data = AccountService::getAccount($this->user_id);
        //获取优惠券信息
        $data['coupon'] = CouponService::getUseCou($this->user_id);
        //获取订单数量
        $Order = new OrderModel();

        $shop_ids=AccountService::shopAccout($this->user_id);
        //待支付订单
		$data['wait_pay_num'] = $Order->getWidgetTotal(['in'=>['shop_user_id'=>$shop_ids],'status'=>0]);
		//待确认订单数量
		$data['wait_confirm_num'] = $Order->getWidgetTotal(['in'=>['shop_user_id'=>$shop_ids],'status'=>3,'scope'=>['neq'=>['comp_time'=>0]],'confirm_time'=>0]);
		//待评价订单数量
		$data['wait_comment_num'] = $Order->getWidgetTotal(['in'=>['shop_user_id'=>$shop_ids],'status'=>4]);

		$data['wait_rece_num'] = $Order->getWidgetTotal(['in'=>['shop_user_id'=>$shop_ids],'status'=>1,'re_time'=>0]);
		//获取待完成订单列表
		$data['wait_order_list'] = $Order->find()->select(['{{%order}}.order_id','status','plate_no','carmodel_id','pro_extra','carmodel_id','abn_status'])->leftJoin("{{%order_info}}", '{{%order}}.`order_id` = {{%order_info}}.`order_id`')->where(['in','status',['0','4']])->andWhere(['in','shop_user_id',$shop_ids])->limit(10)->orderBy("order_id desc")->asArray()->all();
		if(!empty($data['wait_order_list'])){
			foreach ($data['wait_order_list'] as &$value) {
				$value['pro_extra_show']= Helper::getProExtraNameById($value['pro_extra']);
        		$value['carmodel_id_show']= Helper::getCarModelName($value['carmodel_id']);
        		if($value['abn_status']==1){
        		$value['status_show'] = '异常订单';
        	}else{
        		$value['status_show'] = Helper::getOrderSta($value['status']);
        	}
			}
		}
		$data['is_pop'] = !empty($this->isPop())?1:0;
        return $this->response('deal_succ', '获取成功', $data);
	}
	private function isPop(){
		$CouponList = new CouponListModel();
        $list = $CouponList->find()->select(['id','name','money'])->where(['<=','star_valid',time()])->andWhere(['>','end_valid',time()])->andWhere(['in','id',[4,5,6]])->asArray()->all();
        if(!empty($list)){
            $UsersCoupon = new UsersCouponModel();
            $user_id = !empty($this->user_id)?$this->user_id:0;
            if(empty($user_id)) return true;
            foreach ($list as $value) {
            	$flg_rv = $UsersCoupon->getWidgetRow(['cols'=>['id'],'user_id'=>$user_id,'cid'=>$value['id']]);
                if(empty($flg_rv)) return true;
            }
            return false;
        }else{
           return false;
        }
	}
	/**
	 * [actionAccount 我的账户]
	 * @apiDoc
	 * @api     v1/home/account
	 * @group   home
	 * @name    我的账户
	 * @desc    门店APP-我的账户/授信账户
	 * @method  POST
	 * @author JOHN.W
	 * @version [1.0]
	 * @return  json
		{
		"code": "000000",
		"msg": "获取成功",
		"info": {
		"account": {
		    "total_amount": "-29.02",
		    "frost_amount": "0.00",
		    "use_amount": "-29.02",
		    "total_gold": "79.98",
		    "user_id": "2"
		},
		"credit": {
		    "amount": "5000.00",
		    "day": "100",
		    "total": "1",
		    "use_amount": 4970.98,
		    "used_amount": 0
		},
		"coupon": {
		    "total": 0,
		    "list": []
		}
		}
		}
	 */
	public function actionAccount(){
		if (empty($this->user_id)) {
            return $this->response('para_miss_user', '未能识别用户标志');
        }
        //获取账户信息
        $data = AccountService::getAccount($this->user_id);
        //获取优惠券信息
        $data['coupon'] = CouponService::getUseCou($this->user_id);
        return $this->response('deal_succ', '获取成功', $data);
	}
	/**
	 * [actionGetuserinfo ]
	 * @apiDoc
	 * @api     v1/home/getuserinfo
	 * @group   home
	 * @name    获取用户基本信息
	 * @desc    获取账号基本信息
	 * @method  POST
	 * @author JOHN.W
	 * @version [1.0]
	 * @return  json
		{
		"code": "000000",
		"msg": "获取成功",
		"info": {
		"base": {
		    "user_id": "2",
		    "parent_id": "0",//上级ID
		    "username": "15067462246",//用户名
		    "wx_nick": null,//微信昵称
		    "wx_openid": null,//微信openID
		    "realname": "",//真实姓名
		    "mobile": "15067462246",//手机号
		    "credit_pay_id": "0",//支付授权ID
		    "longitude": null,//经度
		    "latitude": null,//纬度
		    "role_id": "0",//角色ID 0超级管理
		    "role_name": "管理员",//角色名称
		    "shop_type": "1",//账号类型1集团,2门店,3普通员工
		},
		"info": {
		    "door_pic": "http://img.repucar.test/uploads/app/images/201909/tech_20190904_5d6f8094c212c.jpg",//门头照-头像
		    "verify_status": "0"//审核状态
		    "name": "众合汽修"//门店名称
		},
        "purview": [  //权限显示
            "account",
            "role"
        ]
		}
		}
	 */
	public function actionGetuserinfo(){
		if (empty($this->user_id)) {
            return $this->response('para_miss_user', '未能识别用户标志');
        }
		$res = UserService::getShopUserInfo($this->user_id);
		return $this->response('deal_succ', '获取成功', $res);
	}
	/**
	 * [actionAccountdetail 收支明细]
	 * @apiDoc
	 * @api     v1/home/accountdetail
	 * @group   home
	 * @name    收支明细
	 * @desc    门店APP-收支明细
	 * @method  POST
	 * @param currentPage string 当前页 noreq 1
	 * @param pageSize string 每页条数 noreq 15
	 * @author JOHN.W
	 * @version [1.0]
	 * @return  josn
		{
		"code": "000000",
		"msg": "获取成功",
		"info": [
		{
		    "money": "-0.01",
		    "money_type": "gold",
		    "remark": "支付订单",
		    "nid": "201909132334265050535098426",
		    "created": "2019-09-23 19:24:58",
		    "op_type": "pay_order"
		},
		{
		    "money": "-0.01",
		    "money_type": "gold",
		    "remark": "支付订单",
		    "nid": "201909132334265050535098426",
		    "created": "2019-09-23 19:26:36",
		    "op_type": "pay_order"
		},
		{
		    "money": "-0.01",
		    "money_type": "money",
		    "remark": "支付订单",
		    "nid": "201909132334265050535098426",
		    "created": "2019-09-23 19:33:23",
		    "op_type": "pay_order"
		}
		]
		}
	 */
	public function actionAccountdetail(){
		if (empty($this->user_id)) {
            return $this->response('para_miss_user', '未能识别用户标志');
        }
        //获取账户信息
        $data = AccountService::getAccount($this->user_id);
        //获取账户流水
        $user_id = isset($data['account']['user_id'])?$data['account']['user_id']:0;
        /*分页处理*/
		$currentPage = 1;
		$pageSize = 15;
		if (isset($this->para['currentPage']) && !empty($this->para['currentPage']) && is_numeric($this->para['currentPage'])) {
			$currentPage = $this->para['currentPage'];
		}
		if (isset($this->para['pageSize']) && !empty($this->para['pageSize']) && is_numeric($this->para['pageSize'])) {
			$pageSize = $this->para['pageSize'];
		}

        $AccountLog = new AccountLogModel();
        $_where = ['cols'=>['money','money_type','remark','nid','created','op_type'],'user_id'=>$user_id,'order'=>['id' => 'desc']];
        $list = $AccountLog->getWidgetPages($_where, $pageSize, $pageSize * ($currentPage - 1));
        if (!empty($list)) {
			foreach ($list as &$value) {
				$value['created'] = date("Y-m-d H:i:s", $value['created']);
			}
		}
		return $this->response('deal_succ', '获取成功', $list);
	}
	/**
	 * [actionMycenter 个人中心]
	 * @apiDoc
	 * @api     v1/home/mycenter
	 * @group   home
	 * @name    个人中心
	 * @desc    门店APP-个人中心
	 * @method  POST
	 * @author JOHN.W
	 * @version [1.0]
	 * @return  josn
		{
			"code": "000000",
			"msg": "获取成功",
			"info": {
			"door_pic": "http://img.repucar.test/uploads/app/images/201909/tech_20190904_5d6f8094c212c.jpg",
			"address": "成都市新光路99号",
			"name": "众合汽修",
			"tel": "082",
			"mobile": "15067462246",
			"pay_type": "--"
		}
		}
	 */
	public function actionMycenter(){
		if (empty($this->user_id)) {
            return $this->response('para_miss_user', '未能识别用户标志');
        }
        $user_id = $this->user_id;
        $Users= new UsersModel();
        $UsersShopInfo= new UsersShopInfoModel();
        $u_where = [
            'cols'=>['user_id','parent_id','realname','mobile','shop_type','pay_type'],
            'user_id'=>$user_id,
            'type'=>'shop',
        ];
        $row = $Users->getWidgetRow($u_where);
        switch ($row['shop_type']) {
        	case '1':
        		$pay_type = Helper::getPayType($row['pay_type']);
        		break;
        	case '2':
        		# code...
        		break;
        	case '3':
        		$user_id = $row['parent_id'];
        		break;	
        }
        $base = $UsersShopInfo->find()->select(['door_pic','address','name','tel'])->where(['user_id'=>$user_id])->asArray()->one();
        $base['door_pic'] = Helper::getImageUrl($base['door_pic']);
        $base['mobile'] = $row['mobile'];
        $base['pay_type'] = isset($pay_type)?$pay_type:'';

       return $this->response('deal_succ', '获取成功', $base);
	}
	/**
	 * [actionModcenter 个人中心修改]
	 * @apiDoc
	 * @api     v1/home/modcenter
	 * @group   home
	 * @name    个人中修改
	 * @desc    门店APP-个人中心修改/-集团账户/门店状态方可修改
	 * @method  POST
	 * @param name string 门店名称 noreq
	 * @param address string 门店地址 noreq
	 * @param tel string 门店固定电话 noreq
	 * @param pay_type string 支付方式[集团账号] noreq
	 * @author JOHN.W
	 * @version [1.0]
	 * @return  json
	 {
		"code": "000000",
		"msg": "修改成功",
		"info": ""
		}
	 */
	public function actionModcenter(){
		if (empty($this->user_id)) {
            return $this->response('para_miss_user', '未能识别用户标志');
        }
        $user_id = $this->user_id;
        $Users= new UsersModel();
        $UsersShopInfo= new UsersShopInfoModel();
        $u_where = [
            'cols'=>['user_id','parent_id','realname','mobile','shop_type','pay_type'],
            'user_id'=>$user_id,
            'type'=>'shop',
        ];
        $row = $Users->getWidgetRow($u_where);
        if(empty($row) || !in_array($row['shop_type'], ['1','2'])){
        	return $this->response('para_miss', '您没有权限修改');
        }
        $param = Helper::elements(['name','address','tel'],$this->para,'');
        $param =array_filter($param);
        $res = $UsersShopInfo->saveUs($param,$user_id);
        if($row['shop_type']==1){
        	$param_p = Helper::elements(['pay_type'],$this->para,'');
        	$param_p =array_filter($param_p);
        	if(!empty($param_p)) $Users->saveUs($$param,$user_id);
        }
        if($res){
        	return $this->response('deal_succ', '修改成功');
        }else{
        	return $this->response('deal_false', '修改失败');
        }
	}
	/**
	 * [actionMsglist  通知消息列表]
	 * @apiDoc
	 * @api     v1/home/msglist
	 * @group   home
	 * @name    消息列表
	 * @desc    门店APP-消息通知中心-系统通知/交易提醒/活动通知
	 * @method  POST
	 * @param msg_type int 消息类型【1.系统通知，2.交易提醒，3.活动通知】 req
	 * @param currentPage string 当前页 noreq 1
     * @param pageSize string 每页条数 noreq 15
	 * @author JOHN.W
	 * @version [1.0]
	 * @return  json
		{
		"code": "000000",
		"msg": "获取成功",
		"info": [
		{
		    "content": "test",
		    "created": "2019-09-19 11:55:57",
		    "extra": null
		},
		{
		    "content": "通知消息来拉",
		    "created": "2019-09-09 11:09:40",
		    "extra": null
		}
		]
		}
	 */
	public function actionMsglist(){
		if (empty($this->user_id)) {
            return $this->response('para_miss_user', '未能识别用户标志');
        }
        if (empty($this->para['msg_type'])) {
            return $this->response('para_miss', '消息类型不能为空');
        }
		$_where = [];
        $_where['order'] = ['id' => 'desc'];
        $_where['cols'] = ['content','created','extra'];
        $_where['msg_type'] = $this->para['msg_type'];
        /*分页处理*/
        $currentPage = 1;
        $pageSize = 15;
        if (isset($this->para['currentPage']) && !empty($this->para['currentPage']) && is_numeric($this->para['currentPage'])) {
            $currentPage = $this->para['currentPage'];
        }
        if (isset($this->para['pageSize']) && !empty($this->para['pageSize']) && is_numeric($this->para['pageSize'])) {
            $pageSize = $this->para['pageSize'];
        }
        $Notice = new NoticeModel();
        $list = $Notice->getWidgetPages($_where, $pageSize, $pageSize * ($currentPage - 1));
        if (!empty($list)) {
            foreach ($list as &$value) {
                $value['created'] = date("Y-m-d H:i:s", $value['created']);
            }
        }
        return $this->response('deal_succ','获取成功', $list);
	}
	/**
	 * [actionSetbase 设置页面接口]
	 * @apiDoc
	 * @api    v1/home/setbase
	 * @group  home
	 * @name   设置中心
	 * @desc   门店APP-设置中心->支付密码是否设置->微信是否绑定
	 * @method POST
	 * @return [type]          [description]
	 */
	public function actionSetbase(){
		if (empty($this->user_id)) {
            return $this->response('para_miss_user', '未能识别用户标志');
        }
        $Users = new UsersModel();
        $res = $Users->getWidgetRow(['cols'=>['shop_type'],'user_id'=>$user_id,'type'=>'shop']);
	}
	/**
	 * [actionBindwx 绑定微信]
	 * @apiDoc
	 * @api    v1/home/bindwx
	 * @group  home
	 * @name   绑定微信登录
	 * @desc   个人中心绑定微信登录
	 * @method POST
	 * @param wx_openid string 微信openid req
	 * @param wx_nick string 微信昵称 noreq
	 * @return json
	 {
		"code": "000000",
		"msg": "操作成功",
		"info": ""
		}
	 */
	public function actionBindwx(){
		if (empty($this->user_id)) {
            return $this->response('para_miss_user', '未能识别用户标志');
        }
        if (empty($this->para['wx_openid'])) {
            return $this->response('para_miss', '微信openid不能为空');
        }
        $Users = new UsersModel();
        //判断微信是否已绑定
        $row = $Users->getWidgetRow(['cols'=>['wx_openid'],'user_id'=>$this->user_id]);
        if(isset($row) && !empty($row['wx_openid'])){
        	return $this->response('para_miss', '已绑定微信登录');
        }
        //校验微信是否已绑定其他账号
        $flag = $Users->getWidgetRow(['cols'=>['user_id'],'wx_openid'=>$this->para['wx_openid']]);
        if(isset($flag) && !empty($flag['user_id'])){
        	return $this->response('para_miss', '微信已绑定过其他账号');
        }
        $param = Helper::elements(['wx_nick','wx_openid'],$this->para,'');
        $res = $Users->saveUs($param,$this->user_id);
        if($res){
        	return $this->response('deal_succ', '操作成功');
        }else{
        	return $this->response('deal_false', '操作失败');
        }
	}
}