<?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\ShopService;
use app\modules\logic\services\CommonService;
use app\modules\logic\model\UsersModel;
use app\modules\logic\model\UsersShopInfoModel;
use Yii;
use yii\web\Controller;

class AccountController extends MiddleController {
	/**
	 * 返回
	 * @param $code
	 * @param string $info
	 * @param string $controller
	 * @param string $total
	 */
	protected function response($code, $info = '', $total = '', $controller = 'account') {
		return parent::response($code, $info, $total, $controller);
	}
	/**
	 * [actionList 账号列表]
	 * @apiDoc
	 * @api     v1/account/list
	 * @group   account
	 * @name    账号/分店列表
	 * @desc    门店APP-账号管理-账号列表
	 * @method  POST
	 * @author JOHN.W
	 * @version [1.0]
	 * @return  json
		{
		"code": "000000",
		"msg": "获取成功",
		"info": [
		{
		"user_id": "3",
		"realname": "",
		"mobile": "18782041250",
		"role_id": "0",
		"role_name": "高级管理"
		}
		]
		}
	 */
	public function actionList(){
		if (empty($this->user_id)) {
            return $this->response('para_miss_user', '未能识别用户标志');
        }
        $account = UserService::getShopAccountInfo($this->user_id);
        switch ($account['shop_type']) {
        	case '1':
        		$where = [
					'cols'=>['user_id','realname','mobile'],
					'parent_id' =>$this->user_id
				];
				$Users = new UsersModel();
				$data = $Users->getWidgetRows($where);
				$UsersShopInfo = new UsersShopInfoModel();
				foreach ($data as &$value) {
					$shop_info = $UsersShopInfo->getWidgetRow(['cols'=>['name','door_pic','verify_status','shop_confirm'],'user_id'=>$value['user_id']]);
					$value['shop_name'] = isset($shop_info['name'])?$shop_info['name']:'-';
					$value['door_pic'] = isset($shop_info['door_pic'])?Helper::getImageUrl($shop_info['door_pic']):'';
					$value['verify_status'] = isset($shop_info['verify_status'])?Helper::getVerifyStatusName($shop_info['verify_status']):'';
					$value['shop_confirm'] = isset($shop_info['shop_confirm'])?$shop_info['shop_confirm']:'1';
				}
        		break;
        	case '2':
				$where = [
					'cols'=>['user_id','realname','mobile','role_id'],
					'parent_id' =>$this->user_id
				];
				$Users = new UsersModel();
				$data = $Users->getWidgetRows($where);
				foreach ($data as &$value) {
					$value['role_name'] = Helper::getSpRoleName($value['role_id']);
				}
        		break;
        	default:
        		$data = [];
        }
        
        return $this->response('deal_succ', '获取成功',$data);
	}
	/**
	 * [actionConfirm 集团确认]
	 * @apiDoc
	 * @api     v1/account/confirm
	 * @group   account
	 * @name    集团确认
	 * @desc    门店APP-账号管理-集团确认
	 * @method  POST
	 * @param  user_id int 分店ID req
	 * @param shop_confirm tinyint 确认状态【1,成功;2，失败】 req
	 * @author JOHN.W
	 * @version [1.0]
	 * @return  json
		{
		"code": "000000",
		"msg": "添加成功",
		"info": "true"
		}
	 */
	public function actionConfirm(){
		if (empty($this->user_id)) {
            return $this->response('para_miss_user', '未能识别用户标志');
        }
        if(empty($this->para['user_id'])){
        	return $this->response('para_miss', '确认分店ID不能为空');
        }
        if(empty($this->para['shop_confirm']) || !in_array($this->para['shop_confirm'], ['1','2'])){
        	return $this->response('para_miss', '确认状态不能为空');
        }
        $UsersShopInfo = new UsersShopInfoModel();
        $res = $UsersShopInfo->saveUs(['shop_confirm'=>$this->para['shop_confirm']],$this->para['user_id']);
        if($res){
        	 return $this->response('deal_succ', '操作成功',$res);
        }else{
        	return $this->response('deal_false', '操作失败');
        }
	}
	/**
	 * [actionAdd 添加账号]
	  * @apiDoc
	 * @api     v1/account/add
	 * @group   account
	 * @name    添加/修改门店/员工
	 * @desc    门店APP-添加账号
	 * @method  POST
	 * @param username string 账号 req
	 * @param password string 密码 req
	 * @param realname string 姓名 req
	 * @param mobile string 手机号 req
	 * @param role_id int 角色ID req
	 * @param user_id int 用户ID[修改必填] noreq
	 * @author JOHN.W
	 * @version [1.0]
	 * @return  json
	 {
		"code": "000000",
		"msg": "添加成功",
		"info": "10"
		}
	 */
	public function actionAdd(){
		if (empty($this->user_id)) {
            return $this->response('para_miss_user', '未能识别用户标志');
        }
        $res = UserService::getShopAccountInfo($this->user_id);
        if(!isset($res) || !in_array($res['shop_type'], ['2'])){
        	return $this->response('para_miss', '您不能添加员工#IS3');
        }
        $user_id = isset($this->para['user_id'])?(int)$this->para['user_id']:0;
        if(empty($this->para['username'])){
        	return $this->response('para_miss', '账号不能为空');
        }
        if(empty($user_id)){
        	if(empty($this->para['password'])){
        		return $this->response('para_miss', '密码不能为空');
        	}
        	//校验账号是否存在
			$phone_flag = UserService::userPhoneExists($this->para['username']);
			if ($phone_flag) {
				return $this->response('para_miss', '账号已存在');
			}
        }
        
        if(empty($this->para['mobile']) || !Verify::verifyMobile($this->para['mobile'])){
        	return $this->response('para_miss', '手机号不正确');
        }
        if(empty($this->para['realname'])){
        	return $this->response('para_miss', '姓名不能为空');
        }
        if(empty($this->para['role_id'])){
        	return $this->response('para_miss', '角色ID不能为空');
        }
        
        $data = Helper::elements(['username','password','realname','mobile','role_id'],$this->para,'');
        $salt = Helper::genSalt();
        $password = md5(md5($data['password']) . $salt);
        $insert_data = array(
            'username' => $data['username'],
            'mobile' => $data['mobile'],
            'realname' => $data['realname'],
            'parent_id' => $this->user_id,
            'password' => $password,
            'salt' => $salt,
            'status' => 0,
            'reg_time' => time(),
            'type' => 'shop',
            'role_id' => $data['role_id'],
            'shop_type'=>$res['shop_type']==1?2:3,
            'addip' => Helper::getUserIp(),
        );
        if(!empty($user_id)){
        	if(empty($this->para['password'])){
        		unset($insert_data['password']);
        		unset($insert_data['salt']);
        	}
        	unset($insert_data['status']);
        }
        $User = new UsersModel();
        $uid = $User->saveUs($insert_data,$user_id);
        if(empty($user_id)){
        	//更新员工编码
        	$User->saveUs(['user_code'=>Helper::autoCtUserCode($uid,3)],$uid);
        }
        if($uid || !empty($user_id)){
        	 return $this->response('deal_succ', '操作成功',$uid);
        }else{
        	return $this->response('deal_false', '操作失败');
        }

	}
	/**
	 * [actionDetail 员工明细]
	  * @apiDoc
	 * @api     v1/account/detail
	 * @group   account
	 * @name    员工明细
	 * @desc    门店APP-员工明细
	 * @method  POST
	 * @param user_id int 员工ID req
	 * @author JOHN.W
	 * @version [1.0]
	 * @return  json
		{
		"code": "000000",
		"msg": "获取成功",
		"info": {
		"username": "15067462246",
		"mobile": "15067462246",
		"realname": "张三",
		"role_id": "0",
		"role_name": "高级管理员"
		}
		}
	 */
	public function actionDetail(){
		if (empty($this->user_id)) {
            return $this->response('para_miss_user', '未能识别用户标志');
        }
        if(empty($this->para['user_id'])){
        	return $this->response('para_miss', '员工ID不能为空');
        }
		$User = new UsersModel();
		$row = $User->getWidgetRow(['cols'=>['username','mobile','realname','role_id'],'user_id'=>$this->para['user_id']]);
		$row['role_name'] = Helper::getSpRoleName($row['role_id']);
 		return $this->response('deal_succ', '获取成功',$row);
	}
	/**
	 * [actionAddshop 添加分店]
	  * @apiDoc
	 * @api     v1/account/addshop
	 * @group   account
	 * @name    添加门店
	 * @desc    门店APP-新建分店
	 * @method  POST
	 * @param  username string 账号 req
	 * @param  name string 店铺名称 req
	 * @param  address string 地址 req
	 * @param  realname string 店长姓名 req
	 * @param  mobile string 手机号 req
	 * @param  tel string 固定电话 req
	 * @param  merch_type_id int 商户性质ID req
	 * @param  door_pic int 门头照 req
	 * @param  license int 营业执照图 req
	 * @param  operate_scope string 经营范围 req
	 * @author JOHN.W
	 * @version [1.0]
	 * @return  json
		{
		"code": "000000",
		"msg": "操作成功",
		"info": "9"
		}
	 */
	public function actionAddshop(){
		if (empty($this->user_id)) {
            return $this->response('para_miss_user', '未能识别用户标志');
        }
        return $this->response('para_miss_user', '暂未开放');
        $res = UserService::getShopAccountInfo($this->user_id);
        if(!isset($res) || !in_array($res['shop_type'], ['1'])){
        	return $this->response('para_miss', '您不能添加分店#NoP');
        }
        $flag = CommonService::verifyUsername($this->para['username']);
		if($flag){
			return $this->response('para_miss', '账号已存在');
		}
		$flagm = CommonService::verifyMobile($this->para['mobile']);
		if($flagm){
			return $this->response('para_miss', '手机号已存在');
		}
		//生成账号
		$param = Helper::elements(['username','mobile','realname'],$this->para,'');
		$param['shop_type'] = 2;
		$param['password'] = "666666";
		$param['parent_id'] = $this->user_id;
		$uid = ShopService::createUsers($param);
		if(!empty($uid)){
			$data = Helper::elements(['name','address','tel','merch_type_id','door_pic','license','operate_scope'],$this->para,'');
			$data['user_id'] = $uid;
			$res = ShopService::createUsersinfo($data);
		}
		if(isset($uid)){
        	 return $this->response('deal_succ', '操作成功',$uid);
        }else{
        	return $this->response('deal_false', '操作失败');
        }
	}
	/**
	 * [actionAddshop 分店详情]
	  * @apiDoc
	 * @api     v1/account/detailshop
	 * @group   account
	 * @name    分店详情
	 * @desc    门店APP-分店详情
	 * @method  POST
	 * @param  user_id int 分店ID req
	 * @author JOHN.W
	 * @version [1.0]
	 * @return  json
		{
		"code": "000000",
		"msg": "获取成功",
		"info": {
		"user_id": "11",
		"username": "fen12",
		"realname": "张三",
		"mobile": "18755554444",
		"name": "1分店",
		"address": "成都市XXX区",
		"tel": "028-5655622",
		"merch_type_id_show": "二手车整备",
		"operate_scope": "经营范围",
		"license_show": "http://img.repucar.test/uploads/app/images/201909/tech_20190904_5d6f7e5f52a45.jpg",
		"door_pic_show": "http://img.repucar.test/uploads/app/images/201909/tech_20190904_5d6f7e5f52a45.jpg"
		}
		}
	 */
	public function actionDetailshop(){
		if (empty($this->user_id)) {
            return $this->response('para_miss_user', '未能识别用户标志');
        }
        if(empty($this->para['user_id'])){
        	return $this->response('para_miss', '分店ID不能为空');
        }
        $Users = new UsersModel();
        $row = $Users->getWidgetRow(['cols'=>['user_id','username','realname','mobile'],'user_id'=>$this->para['user_id']]);
        $row_info = ShopService::getShopDetail($this->para['user_id']);
        $row_use = Helper::elements(['name','address','tel','merch_type_id_show','operate_scope','license_show','door_pic_show'],$row_info['info'],'');
        return $this->response('deal_succ', '获取成功',array_merge($row,$row_use));
	}
	/**
	 * [actionModshop 修改分店]
	  * @apiDoc
	 * @api     v1/account/modshop
	 * @group   account
	 * @name    修改分店信息
	 * @desc    门店APP-修改分店信息
	 * @method  POST
	 * @param  user_id int 分店ID req
	 * @param  username string 账号 noreq
	 * @param  name string 店铺名称 noreq
	 * @param  address string 地址 noreq
	 * @param  realname string 店长姓名 noreq
	 * @param  mobile string 手机号 noreq
	 * @param  tel string 固定电话 noreq
	 * @param  merch_type_id int 商户性质ID noreq
	 * @param  door_pic int 门头照 noreq
	 * @param  license int 营业执照图 noreq
	 * @param  operate_scope string 经营范围 noreq
	 * @author JOHN.W
	 * @version [1.0]
	 * @return  json
	 */
	public function actionModshop(){
		if (empty($this->user_id)) {
            return $this->response('para_miss_user', '未能识别用户标志');
        }
        return $this->response('para_miss_user', '暂未开放');
        if(empty($this->para['user_id'])){
        	return $this->response('para_miss', '分店ID不能为空');
        }
        $user_id = (int)$this->para['user_id'];
        $res = UserService::getShopAccountInfo($this->user_id);
        if(!isset($res) || !in_array($res['shop_type'], ['1'])){
        	return $this->response('para_miss', '您不能修改分店#NoP');
        }
        if(isset($this->para['username'])){
        	$flag = CommonService::verifyUsername($this->para['username'],$user_id);
			if($flag){
				return $this->response('para_miss', '账号已存在');
			}
        }
        if(isset($this->para['mobile'])){
        	$flagm = CommonService::verifyMobile($this->para['mobile'],$user_id);
			if($flagm){
				return $this->response('para_miss', '手机号已存在');
			}
        }
    	//生成账号
		$param = Helper::elements(['username','mobile','realname'],$this->para,'');
		$param =array_filter($param);
		if(!empty($param)){
			$uid = ShopService::createUsers($param,$user_id);
		}
		$data = Helper::elements(['name','address','tel','merch_type_id','door_pic','license','operate_scope'],$this->para,'');
		$data =array_filter($data);
		if(!empty($data)){
			$res = ShopService::createUsersinfo($data,$user_id);
		}
		return $this->response('deal_succ', '修改成功',$user_id);
	}
}