<?php

/**
 * 控制器:后台系统门店管理
 * date:2019-08-31
 */

namespace app\modules\manage\v1\controllers;
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 app\modules\common\Helper;
use Yii;
use yii\web\Controller;

class ShopController extends MiddleController {
	/**
	 * 返回
	 * @param $code
	 * @param string $info
	 * @param string $controller
	 * @param string $total
	 */
	protected function response($code, $info = '', $total = '', $controller = 'shop') {
		return parent::response($code, $info, $total, $controller);
	}
	/**
	 * [actionAddshop 添加/修改门店]
	 * @apiDoc
	 * @api     v1/shop/addshop
	 * @group   shop
	 * @name    添加门店
	 * @desc    后台管理-门店管理-添加/修改门店
	 * @method  POST
	 * @param  username string 账号 req
	 * @param  password string 密码 req
	 * @param  mobile string 手机号 req
	 * @param  door_pic int 门头照 req
	 * @param  license int 营业执照图 req
	 * @param  name string 名称 req
	 * @param  address string 地址 req
	 * @param  legal_person string 法人 req
	 * @param  info_mobile string 法人电话 req
	 * @param  merch_type_id int 商户性质ID req
	 * @param  operate_scope string 经营范围 req
	 * @param  tel string 固定电话 req
	 * @param  prov_id int 省ID req
	 * @param  city_id int 市ID req
	 * @param  area_id int 区ID noreq
	 * @param  parent_id int 上级ID noreq
	 * @param  credit_pay_id int 付款权限ID noreq
	 * @param  shop_type int 门店类型【1，集团，2，分公司，3门店，4员工】 noreq
	 * @param  user_id id 用户ID【修改必填】 noreq
	 * @author JOHN.W
	 * @version [1.0]
	 * @return  json
		{
		"code": "000000",
		"msg": "操作成功",
		"info": true
		}
	 */
	public function actionAddshop(){
		if (!isset($this->para['username']) || empty($this->para['username'])) {
            return $this->response('para_miss', '手机号不能为空');
        }
		if (!isset($this->para['mobile']) || empty($this->para['mobile'])) {
            return $this->response('para_miss', '手机号不能为空');
        }
        if (empty($this->para['prov_id']) || !is_numeric($this->para['prov_id'])) {
            return $this->response('para_miss', '请输入省ID');
        }
        if (empty($this->para['city_id']) || !is_numeric($this->para['city_id'])) {
            return $this->response('para_miss', '请输入市ID');
        }
        if (!isset($this->para['password']) || empty($this->para['password'])) {
            return $this->response('para_miss', '初始密码不能为空');
        }
        $user_id = isset($this->para['user_id'])?(int)$this->para['user_id']:0;
        if(empty($user_id)){
        	return $this->response('para_miss', '修改用户ID不能为空');
        }
		$flag = CommonService::verifyUsername($this->para['username'],$user_id);
		if($flag){
			return $this->response('para_miss', '手机号已存在');
		}
		//$res = ShopService::createShop($this->para);
		$res = true;
		if($res){
			return $this->response('deal_succ', $res);
		}else{
			return $this->response('deal_false', $res);
		}
	}
	/**
	 * [actionListshop 门店管理列表]
	 * @apiDoc
	 * @api     v1/shop/listshop
	 * @group   shop
	 * @name    门店列表
	 * @desc    后台管理-门店管理-门店列表
	 * @method  POST
	 * @param  user_code string 门店编码 noreq
	 * @param  name string 姓名 noreq
	 * @param  parent_id int 上级ID noreq
	 * @param  verify_status int 审核状态【0，待，1通过，2未通过】 noreq
	 * @param currentPage string 当前页 noreq 1
	 * @param pageSize string 每页条数 noreq 15
	 * @author JOHN.W
	 * @version [1.0]
	 * @return  json
		 {
    "code": "000000",
    "msg": "操作成功",
    "total": "101",
    "info": [
        {
            "user_id": "3",//门店ID
            "status": "正常",//运行状态
            "username": "18782041250",//管理员账号
            "reg_time": "2019-09-10 14:49:17",//注册时间
            "name": "众合汽修",//商户名称
            "address": "成都市新光路99号",//地址
            "legal_person": "1",//法人代表姓名
            "info_mobile": "15067462246",//联系方式
            "tel": "082",//固定电话
            "created": "1970-01-01 08:00:00",//审核日期
            "verify_status_show": "待审核",//审核状态
            "prov_id_show": "四川省",//省
            "city_id_show": "成都市",//市
            "area_id_show": "--",//区
            "merch_type_id_show": "二手车整备",//商户性质
            "pay_purv": "记账",//支付权限
            "credit_pay": "-"//授信权限
        },
        {
            "user_id": "20",
            "status": "正常",
            "username": "18200143935",
            "reg_time": "2019-10-19 10:32:12",
            "name": "啊我也",
            "address": ",",
            "legal_person": "张三",
            "info_mobile": "18980647855",
            "tel": "02815064777",
            "created": "1970-01-01 08:00:00",
            "verify_status_show": "已审核",
            "prov_id_show": "四川省",
            "city_id_show": "成都市",
            "area_id_show": "青羊区",
            "merch_type_id_show": "二手车整备",
            "pay_purv": "单笔",
            "credit_pay": "100天/1单/5000.00元"
        }
        
    ]
}
	 */
	public function actionListshop(){
		$_where = "";
		$_where .= " and p1.type= 'shop' and p1.shop_type=2 ";
        if (!empty($this->para['user_code'])) {
            $_where .= " and p1.user_code= '" . $this->para['user_code'] . "' ";
        }
        if (isset($this->para['parent_id'])) {
            $_where .= " and p1.parent_id= '" . $this->para['parent_id'] . "' ";
        }
        if (!empty($this->para['name'])) {
            $_where .= " and p2.name= '" . $this->para['name'] . "' ";
        }
        if (isset($this->para['verify_status'])) {
            $_where .= " and p2.verify_status= '" . $this->para['verify_status'] . "' ";
        }
        $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'];
        }

        $limit_start = ($currentPage - 1) * $pageSize;
        $_limit = " limit " . $limit_start . " , " . $pageSize;
        $_order = " order by p1.user_id desc";
        /*数据库链接*/
        $conn = Yii::$app->db;
        //记录总数
        $sql_total = "select count(1) as total_num from {{%users}} as p1 left join {{%users_shop_info}} as p2  on p1.user_id=p2.user_id where 1  " . $_where;
        $cmd_total = $conn->createCommand($sql_total);
        $res_total = $cmd_total->queryOne();
        $total_records = $res_total['total_num'];

        //当前记录
        $sql = "select p1.user_id,p1.prov_id,p1.city_id,p1.area_id,p1.status,p1.username,p1.reg_time,p1.credit_pay_id,p2.name,p2.address,p2.legal_person,p2.info_mobile,p2.tel,p2.verify_status,p2.merch_type_id,p2.created
		from {{%users}} as p1 left join {{%users_shop_info}} as p2  on p1.user_id=p2.user_id where 1 " . $_where . $_order . $_limit;
        $cmd = $conn->createCommand($sql);
        $data = $cmd->queryAll();
        foreach ($data as &$value) {
        	$value['verify_status_show'] = Helper::getVerifyStatusName($value['verify_status']);
        	$value['prov_id_show'] = Helper::getRegion($value['prov_id']);
        	$value['city_id_show'] = Helper::getRegion($value['city_id']);
        	$value['area_id_show'] = Helper::getRegion($value['area_id']);
        	$value['merch_type_id_show'] = Helper::getMerchNameById($value['merch_type_id']);
        	$value['status'] = $value['status']==0?'正常':'禁用';
        	$value['pay_purv'] = ($value['credit_pay_id']>0)?'记账':'单笔';
        	$value['credit_pay'] = Helper::getShopCreditPay($value['credit_pay_id']);
        	$value['created'] = !empty($value['created'])?date("Y-m-d H:i:s",$value['created']):'-';
        	$value['reg_time'] = date("Y-m-d H:i:s",$value['reg_time']);
        	unset($value['prov_id']);
        	unset($value['city_id']);
        	unset($value['area_id']);
        	unset($value['merch_type_id']);
        	unset($value['credit_pay_id']);
        	unset($value['verify_status']);
        }
 		$conn->close();
        return $this->response('search_succ', $data, $total_records);
	}
	/**
	 * [actionDetailshop 门店详情]
	 * @apiDoc
	 * @api     v1/shop/detailshop
	 * @group   shop
	 * @name    门店详情
	 * @desc    后台管理-门店管理-详情
	 * @method  POST
	 * @param  user_id int 门店ID req
	 * @author JOHN.W
	 * @version [1.0]
	 * @return  json
		{
		"code": "000000",
		"msg": "操作成功",
		"info": {
		"info": {
		    "user_id": "1",
		    "name": "哈哈",
		    "address": "222",
		    "legal_person": "1",
		    "info_mobile": "15067462246",
		    "tel": "082",
		    "license": "2",
		    "door_pic": "2",
		    "merch_type_id": "1",
		    "operate_scope": "经营范围",
		    "verify_status": "0",
		    "created": "0",
		    "license_show": "http://img.repucar.test/uploads/app/images/201909/tech_20190904_5d6f8094c212c.jpg",
		    "door_pic_show": "http://img.repucar.test/uploads/app/images/201909/tech_20190904_5d6f8094c212c.jpg",
		    "verify_status_show": "待审核"
		}
		}
		}
	 */
	public function actionDetailshop(){
		if (empty($this->para['user_id']) || !is_numeric($this->para['user_id'])) {
            return $this->response('para_miss', '门店ID不能为空');
        }
        $data = ShopService::getShopDetail($this->para['user_id']);
        return $this->response('deal_succ', $data);
	}
	/**
	 * [actionVerifyshop 门店审核]
	 * @apiDoc
	 * @api     v1/shop/verifyshop
	 * @group   shop
	 * @name    门店审核
	 * @desc    后台管理-门店管理-门店审核
	 * @method  POST
	 * @param   user_id int 用户ID req
	 * @param   merch_type_id int 商户性质ID req
	 * @param   verify_notice string 审核意见 noreq
	 * @param   verify_status int 审核状态【1，通过2，未通过】 req
	 * @param   credit_pay_id int 付款权限ID noreq 0
	 * @param   longitude string 经度 req
	 * @param   latitude string 纬度 req
	 * @author JOHN.W
	 * @version [1.0]
	 * @return  json
	 {
		"code": "000000",
		"msg": "操作成功",
		"info": true
	 }
	 */
	public function actionVerifyshop(){
		if (empty($this->para['user_id']) || !is_numeric($this->para['user_id'])) {
            return $this->response('para_miss', '用户ID不能为空');
        }
        if (empty($this->para['verify_status']) || !in_array($this->para['verify_status'], ['1','2'])) {
            return $this->response('para_miss', '审核状态不正确');
        }
        if (!isset($this->para['longitude']) || empty($this->para['longitude'])) {
            return $this->response('para_miss', '经度不能为空');
        }
        if (!isset($this->para['latitude']) || empty($this->para['latitude'])) {
            return $this->response('para_miss', 'latitude不能为空');
        }
        $UsersShopInfo = new UsersShopInfoModel();
        //查找用户是否未审核
        $flag = $UsersShopInfo->getWidgetRow(['cols'=>['verify_status'],'user_id'=>$this->para['user_id']]);
        if(isset($flag['verify_status']) && !in_array($flag['verify_status'],['0','2'])){
        	return $this->response('para_miss', '已审核通过');
        }
        $shop_info  = ['verify_status'=>$this->para['verify_status'],'created'=>time()];
        if(!empty($this->para['merch_type_id'])){
        	$shop_info['merch_type_id'] = $this->para['merch_type_id'];
        }
        if(!empty($this->para['verify_notice'])){
        	$shop_info['verify_notice'] = $this->para['verify_notice'];
        }
        /*更新经纬度以及付款权限*/
        $user = [];
        if(!empty($this->para['credit_pay_id'])){
        	$user['credit_pay_id'] = $this->para['credit_pay_id'];
        }
        if(!empty($this->para['longitude'])){
        	$user['longitude'] = $this->para['longitude'];
        }
        if(!empty($this->para['latitude'])){
        	$user['latitude'] = $this->para['latitude'];
        }
        //门店审核经纬度，自动获取该门店的省市区
        if(!empty($user['longitude']) && !empty($user['latitude'])){
			$region = Helper::getAddress($user['longitude'],$user['latitude']);
			$region_ids = Helper::GetProvinceCityByName($region['province'],$region['city'],$region['district']);
			if(!empty($region_ids)){
				$user['prov_id'] = isset($region_ids['prov_id'])?$region_ids['prov_id']:0;
				$user['city_id'] = isset($region_ids['city_id'])?$region_ids['city_id']:0;
				$user['area_id'] = isset($region_ids['district_id'])?$region_ids['district_id']:0;
			}
        }
        if(!empty($user)){
        	$Users = new UsersModel();
        	$Users->saveUs($user,$this->para['user_id']);
        }
        $res = $UsersShopInfo->saveUs($shop_info,$this->para['user_id']);
		if($res){
			return $this->response('deal_succ', $res);
		}else{
			return $this->response('deal_false', $res);
		}
	}
}
