<?php

/**
 * 控制器:提现管理
 * date:2019-10-30
 */

namespace app\modules\manage\v1\controllers;

use app\modules\common\Helper;
use app\modules\common\Redis;
use app\modules\logic\model\OrderModel;
use app\modules\logic\model\AccountCashModel;
use app\modules\logic\model\PayLogModel;
use app\modules\logic\services\OrderService;
use app\modules\logic\services\AccountService;
use app\modules\third\payment\Wxpay;
use Yii;
use yii\web\Controller;

class CashController extends MiddleController {
	/**
	 * 返回
	 * @param $code
	 * @param string $info
	 * @param string $controller
	 * @param string $total
	 */
	protected function response($code, $info = '', $total = '', $controller = 'cash') {
		return parent::response($code, $info, $total, $controller);
	}
	/**
	 * [actionList 提现列表]
	 * @apiDoc
	 * @api    v1/cash/list
	 * @group  cash
	 * @name   提现列表
	 * @desc   管理后台-财务管理-提现管理
	 * @method POST
	 * @param currentPage string 当前页 noreq 1
	 * @param pageSize string 每页条数 noreq 15
	 * @param nid string 订单号 noreq
	 * @param status string 提现状态 noreq
	 * @param addtime_from string 查询时间【开始】 noreq
	 * @param addtime_to string 查询时间【结束】 noreq
	 * @return json
		{
		"code": "000000",
		"msg": "操作成功",
		"total": "1",
		"info": [
		{
		    "id": "1",
		    "user_id": "1",
		    "nid": "xxx",
		    "total": "100.00",
		    "money": "100.00",
		    "fee": "0.00",
		    "status": "0",
		    "add_time": "2019-09-25 11:50:28",
		    "verify_time": "",
		    "bank": "",
		    "bank_id": "0",
		    "bank_card": "",
		    "branch": "",
		    "addip": null,
		    "remark": "提现申请",
		    "cash_type": "1",
		    "wx_openid": "xx",
		    "wx_nickname": "bbb",
		    "status_name": "处理中"
		}
		]
		}
	 */
	public function actionList(){
		$_where = [];
		$_where['order'] = ['id' => 'desc'];
		/*订单号搜索*/
		if (!empty($this->para['nid'])) {
			$_where['nid'] = $this->para['nid'];
		}
		/*状态搜索*/
		if (isset($this->para['status']) && $this->para['status']!='all') {
			$_where['status'] = $this->para['status'];
		}
		/*查询时间搜索*/
		if (!empty($this->para['addtime_from'])) {
			$_where['scope']['ltt']['add_time'] = strtotime($this->para['addtime_from']);
		}
		if (!empty($this->para['addtime_to'])) {
			$_where['scope']['mtt']['add_time'] = strtotime($this->para['addtime_to']);
		}
		/*分页处理*/
		$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'];
		}
		$AccountCash = new AccountCashModel();
		$total = $AccountCash->getWidgetTotal($_where);
		$list = $AccountCash->getWidgetPages($_where, $pageSize, $pageSize * ($currentPage - 1));
		if (!empty($list)) {
			foreach ($list as &$value) {
				$value['status_name'] = Helper::getCashStatusByKey($value['status']);
				$value['add_time'] = date("Y-m-d H:i:s", $value['add_time']);
				$value['verify_time'] = !empty($value['verify_time'])?date("Y-m-d H:i:s", $value['verify_time']):'';
			}
		}
		return $this->response('search_succ', $list, $total);
	}
	/**
	 * [actionVycash 提现审核]
	 * @apiDoc
	 * @api    v1/cash/vycash
	 * @group  cash
	 * @name   提现审核
	 * @desc   管理后台-提现审核
	 * @method POST
	 * @param id int 提现ID req
	 * @param status int 审核状态【1,成功;2,失败】 req
	 * @param remark string 打款备注 noreq
	 * @return json
		{
			"code": "000000",
			"msg": "操作成功",
			"info": "审核成功"
		}
	 */
	public function actionVycash(){
		if (empty($this->para['id']) || !is_numeric($this->para['id'])) {
            return $this->response('para_miss', '提现ID不能为空');
        }
        if (empty($this->para['status']) || !in_array($this->para['status'], ['1','2'])) {
            return $this->response('para_miss', '审核状态不正确');
        }
        
        $number = rand(1, 1000000);
        $key = 'Lock:' . md5('back_cash_edit' . $this->para['id']);
        $re = Redis::lock($key, $number);
        if (!$re) {
            return $this->response('para_miss', '提交记录正在被审核，请勿重复审核');
        }
        $connection = Yii::$app->db;
        $command = $connection->createCommand('SELECT * FROM {{%account_cash}} WHERE id=:id and status=0');
        $command->bindValue(':id', $this->para['id']);
        $account_cash = $command->queryOne();
        if (!$account_cash) {
            Redis::unlock($key, $number);
            return $this->response('para_miss', '提现记录不存在或已审核');
        }
        //微信提款
        if (empty($account_cash['wx_openid'])) {
            Redis::unlock($key, $number);
            return $this->response('para_miss', '未能找到用户微信号');
        }
        $data = [
        	'status'=>$this->para['status'],
        	'notice'=>isset($this->para['remark'])?$this->para['remark']:'',
        	'verify_time'=>time(),
        ];
        if($this->para['status']==1){
        	$wx = new Wxpay('2.83');
			$wx_tixian = $wx->tiXian($account_cash['nid'], $account_cash['money'] * 100, $account_cash['wx_openid']);
			if(!is_array($wx_tixian)){
				$data['wxdk_status'] = 2;//打款失败
				$data['notice'] = $wx_tixian;//打款失败
			}else{
				$data['wxdk_status'] = 1;//打款成功
				$data['notice'] = json_encode($wx_tixian);//打款成功
			}
        }else{
        	//直接失败-退回账户余额
        	$log_info = [];
			$log_info["user_id"] = $account_cash['user_id'];//操作用户id
			$log_info["nid"] = $account_cash['nid'];//订单号
			$log_info["money"] = $account_cash['total'];//操作金额
			$log_info["money_type"] = 'money';//操作资金类型
			$log_info["op_type"] = "cash_fal";//提现失败
			$log_info["remark"] = $data['notice'];//备注
			AccountService::addAccountLog($log_info);
        }
        $AccountCash = new AccountCashModel();
        $result = $AccountCash->saveUs($data,$this->para['id']);
        Redis::unlock($key, $number);
        /*============================操作日志==========================================*/
       /* $action_log = array();
        $action_log['operator_id'] = $this->rec_role['operator_id'];
        $action_log['username'] = $this->rec_role['username'];
        $action_log['terminal_type'] = $this->para['terminalType'];
        $action_log['data_before'] = serialize($account_cash);
        $action_log['data_after'] = serialize($data);
        $action_log['addtime'] = time();
        $action_log['addip'] = Helper::getUserIp();
        $connection->createCommand()->insert('{{%operator_actionlog}}', $action_log)->execute();*/
        if ($result) {
            return $this->response('deal_succ', '审核成功');
        } else {
            return $this->response('server_error', '审核失败');
        }

	}
	/**
	 * [actionRechange 充值列表]
	 * @apiDoc
	 * @api    v1/cash/rechangelist
	 * @group  cash
	 * @name   充值列表
	 * @desc   后台管理-财务管理，充值列表
	 * @method POST
	 * @param currentPage string 当前页 noreq 1
	 * @param pageSize string 每页条数 noreq 15
	 * @param status string 充值状态【0,待支付;1,成功;2,失败】 noreq
	 * @param addtime_from string 查询时间【开始】 noreq
	 * @param addtime_to string 查询时间【结束】 noreq
     * @param user_id int 商户ID【搜】 noreq
     * @param name string 商户名称【搜】 noreq
	 * @return json
		{
    "code": "000000",
    "msg": "操作成功",
    "total": "337",
    "info": [
        {
            "pay_money": "0.01",//个数/金额
            "nid": "BCN20191218120225d152227df386690",//订单号
            "user_id": "66",//门店ID
            "status": "0",//状态码
            "created": "2019-12-18 12:02:25",//支付时间
            "sp_user_id": "66",//发起充值人ID
            "user_info": {
                "realname": null,//充值人姓名
                "mobile": "13810001002"//充值人账号
            },
            "shop_name": "1",//门店名称
            "prov_id": "四川省",//省
            "city_id": "成都市",//市
            "area_id": "青羊区",//区/县
            "status_name": "未支付",//支付状态
            "total_gold": "0",//账户总币数
            "pay_way": "微信",//支付方式
            "username": "123456"//门店账号
        },
        {
            "pay_money": "0.01",
            "nid": "BCN20191218120146da9d55dade24844",
            "user_id": "66",
            "status": "0",
            "created": "2019-12-18 12:01:46",
            "sp_user_id": "66",
            "user_info": {
                "realname": null,
                "mobile": "13810001002"
            },
            "shop_name": "1",
            "prov_id": "四川省",
            "city_id": "成都市",
            "area_id": "青羊区",
            "status_name": "未支付",
            "total_gold": "0",
            "pay_way": "微信"
        },
        {
            "pay_money": "0.01",
            "nid": "BCN201912181201435d79d99a5fb4139",
            "user_id": "66",
            "status": "0",
            "created": "2019-12-18 12:01:46",
            "sp_user_id": "66",
            "user_info": {
                "realname": null,
                "mobile": "13810001002"
            },
            "shop_name": "1",
            "prov_id": "四川省",
            "city_id": "成都市",
            "area_id": "青羊区",
            "status_name": "未支付",
            "total_gold": "0",
            "pay_way": "微信"
        }
    ]
}
	 */
	public function actionRechangelist(){
		$_where = ['cols'=>['pay_money','nid','user_id','status','created','sp_user_id'],'order_type'=>2];
		$_where['order'] = ['id' => 'desc'];
		/*状态搜索*/
		if (isset($this->para['status']) && $this->para['status']!='all') {
			$_where['status'] = $this->para['status'];
		}
		/*查询时间搜索*/
		if (!empty($this->para['addtime_from'])) {
			$_where['scope']['ltt']['add_time'] = strtotime($this->para['addtime_from']);
		}
		if (!empty($this->para['addtime_to'])) {
			$_where['scope']['mtt']['add_time'] = strtotime($this->para['addtime_to']);
		}
		if (isset($this->para['user_id']) && !empty($this->para['user_id'])) {
           $_where['user_id'] = $this->para['user_id'];
        }
        if (isset($this->para['name']) && !empty($this->para['name'])) {
           //通过名字查询user_id
           $name_arr =Helper::getShopUserId($this->para['name']);
           if(!empty($name_arr)){
                $_where['in']['user_id'] = $name_arr;
           }else{
              return $this->response('search_succ', [], 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'];
		}
		$PayLog = new PayLogModel();
		$total = $PayLog->getWidgetTotal($_where);
		$list = $PayLog->getWidgetPages($_where, $pageSize, $pageSize * ($currentPage - 1));
		if (!empty($list)) {
			foreach ($list as &$value) {
				$value['user_info'] = Helper::getUsersBase($value['sp_user_id']);
				$shop_info = $this->getCsShopinfo($value['user_id']);
				$value['shop_name'] = $shop_info['name'];
				$value['username'] = $shop_info['username'];
				$value['prov_id'] = $shop_info['prov_id'];
				$value['city_id'] = $shop_info['city_id'];
				$value['area_id'] = $shop_info['area_id'];
				$value['status_name'] = Helper::getPayLogLabel($value['status']);
				//获取精誉币数量
				$value['total_gold'] = Helper::getGoldSum($value['user_id']);
				$value['pay_way'] = '微信';
				$value['created'] = date("Y-m-d H:i:s", $value['created']);
				
			}
		}
		return $this->response('search_succ', $list, $total);
	}
	/**
     * [getBshopinfo 获取开票门店信息]
     * @name   接口名(所有菜品)
     * @desc   接口描述
     */
    private function getCsShopinfo($user_id = 0){
        $conn = Yii::$app->db;
        $command = $conn->createCommand('select prov_id,city_id,area_id,username from {{%users}} where user_id=:id');
        $command->bindValue(':id', $user_id);
        $result = $command->queryOne();
        if($result){
            $command = $conn->createCommand('select name from {{%users_shop_info}} where user_id=:id');
            $command->bindValue(':id', $user_id);
            $result_info = $command->queryOne();
        }
        $ret = [
            'prov_id' =>isset($result['prov_id'])?Helper::getRegion($result['prov_id']):'-',
            'city_id' =>isset($result['city_id'])?Helper::getRegion($result['city_id']):'-',
            'area_id' =>isset($result['area_id'])?Helper::getRegion($result['area_id']):'-',
            'username' =>isset($result['username'])?$result['username']:'-',
            'name' =>isset($result_info['name'])?$result_info['name']:'-',
        ];
        return $ret;
    }
}