<?php


namespace app\api\controller;


use app\common\controller\Common;
use think\facade\Db;
use think\facade\Request;

class Payorder extends Base
{
    //业主所有房间下的未缴费的水电物业等,只有业主才能看到记录
    public function payList() {
        //获取是业主身份的房间
        $vacancys = Db::name('house_user_bind')->alias('hub')
                ->leftJoin('house_vacancy hv','hv.vacancy_id = hub.vacancy_id')
                ->leftJoin('house_village hvi','hvi.village_id = hv.village_id')
                ->where(['hub.type'=>0,'hub.status'=>1,'hub.uid'=>$this->uid])
                ->field('hub.house_user_bind_id,hv.vacancy_id,hv.vacancy_code,hv.layout_id,hvi.village_name,hv.property_end_time')
                ->select()->toArray();

        if($vacancys) {


            $convertArr = $this->convertArr;
            $array_keys = array_keys($convertArr);
            foreach ($vacancys as $k =>$v) {
                $where['vacancy_id'] = $v['vacancy_id'];
                $where['is_pay'] = 0;
                $res = Common::getVacancyAddress($v['vacancy_code'],$v['layout_id']);
                $vacancys[$k]['vacancy_address'] = $res['vacancy_address'];
                foreach ($convertArr as $key=>$value) {
                    $where['type'] = $key;
                    //物业
                    if($key=='property') {
                        $property_end_time = $v['property_end_time'];
                        $dataInfo = Db::name('cost')->where($where)->where('cost_month','>',$property_end_time)->order('create_time','desc')->field('cost_id,pay_money,create_time')->select()->toArray();
                    } else {
                        $dataInfo = Db::name('cost')->where($where)->order('create_time','desc')->field('cost_id,pay_money,create_time')->select()->toArray();
                    }
//                    $dataInfo = Db::name('cost')->where($where)->order('create_time','desc')->field('cost_id,pay_money,create_time')->select()->toArray();
                    if(!$dataInfo) {
                        continue;
                    }
                    $total = 0;
                    $costIds=[];
                    foreach ($dataInfo as $ke =>$va) {
                        $total+=$va['pay_money'];
                        $costIds[]=$va['cost_id'];
                    }
                    //总金额
                    $rest['money'] =$total;
                    $rest['type'] = $key;
                    $rest['type_zh'] = $convertArr[$key];
                    $rest['create_time'] = $dataInfo[0]['create_time']; //最近的账单生成的时间
                    $rest['cost_ids'] = $costIds;
                    $vacancys[$k]['pay_list'][] = Common::changeField($rest);
                }
                //获取自定义的
                unset($where['type']);
                $dataInfo = Db::name('cost')->where($where)->whereNotIn('type',$array_keys)->order('create_time','desc')->field('cost_id,pay_money,create_time')->select()->toArray();
                if(!$dataInfo) {
                    continue;
                }
                $total = 0;
                $costIds=[];
                foreach ($dataInfo as $ke =>$va) {
                    $total+=$va['pay_money'];
                    $costIds[]=$va['cost_id'];
                }
                $rest_other['money'] = $total;
                $rest_other['type'] = "other";
                $rest_other['type_zh'] = "自定义";
                $rest_other['create_time'] = $dataInfo[0]['create_time']; //最近的账单生成的时间
                $rest_other['cost_ids'] = $costIds;
                $vacancys[$k]['pay_list'][] = Common::changeField($rest_other);


            }
            //删除没有收费的房间
            foreach ($vacancys as $ke => $va) {
                if(empty($va['pay_list']) || !isset($va['pay_list'])) {
                    unset($vacancys[$ke]);
                }
            }
            $vacancys = array_values($vacancys);

        } else {
            $vacancys = [];
        }
        return  $this->returnJson($vacancys);
    }

    //查看已缴费的列表
    public function getPayList() {
        //获取是业主身份的房间
        $vacancys = Db::name('house_user_bind')->alias('hub')
            ->leftJoin('house_vacancy hv','hv.vacancy_id = hub.vacancy_id')
            ->leftJoin('house_village hvi','hvi.village_id=hv.village_id')
            ->where(['hub.type'=>0,'hub.status'=>1,'hub.uid'=>$this->uid])
            ->field('hub.house_user_bind_id,hv.vacancy_id,hv.vacancy_code,hv.layout_id,hvi.village_name')
            ->select()->toArray();
        if($vacancys) {
            $convertArr = $this->convertArr;
            $array_keys = array_keys($convertArr);
            $unit = $this->myUnit;
            foreach ($vacancys as $k =>$v) {
                $where['vacancy_id'] = $v['vacancy_id'];
                $where['is_pay'] = 1;
                $res = Common::getVacancyAddress($v['vacancy_code'],$v['layout_id']);
                $vacancys[$k]['vacancy_address'] = $res['vacancy_address'];
                foreach ($convertArr as $key=>$value) {
                    $where['type'] = $key;
                    //总金额
                    $data= Db::name('cost')->where($where)->sum('pay_money');
                    //如果金额是0就跳过
                    if($data ==0) {
                        continue;
                    }
                    $rest['total_money'] = $data;
                    if($key == "property" || $key =="park"){
                        $count = Db::name('cost')->where($where)->count();
                        $total_num = $count."个月";
                    } else if($key == "water" || $key=="electric" || $key == "gas") {
                        $num =  Db::name('cost')->where($where)->sum('area');
                        $total_num  = $num.$unit[$key];
                    }
                    $rest['total_num'] = $total_num;
                    $rest['name'] = $key;
                    $rest['name_zh'] = $value;
                    //获取最近的支付订单时间
                    $time = Db::name('cost')->where($where)->order('pay_time','desc')->value('pay_time');
                    $rest['pay_time'] = $time;
                    $all[] = $rest;
                }
                //获取自定义的
                unset($where['type']);
                $count = Db::name('cost')->where($where)->whereNotIn('type',$array_keys)->sum('pay_money');
                //获取最近一次支付时间
                $time = Db::name('cost')->where($where)->whereNotIn('type',['property','water','gas','electric','park'])->order('pay_time','desc')->value('pay_time');
                $other['pay_time'] = $time;
                $other['name'] = "other";
                $other['name_zh'] = "自定义";
                $other['total_num'] = $count;
                if($other['total_num'] !=0){
                    $all[] = $other;
                }
                $vacancys[$k]['pay_list'] = Common::changeField($all,'pay_time');
                //如果当前房间没有已缴费记录,则去掉
                if(empty($all)) {
                    unset($vacancys[$k]);
                }
            }
        } else {
            $vacancys = [];
        }
        return  $this->returnJson($vacancys,'pay_time');
    }


    //某个房间下的某个收费项的以缴费缴费列表
    public function vacancyPayedList(){
        $vacancy_id = Request::param('vacancy_id');
        $type = Request::param('type'); //property|water|electric|gas|park|other,除了other,其他都能对应表中的type
        $page = Request::param('page',1);

        $convertArr = $this->convertArr;
        if(in_array($type,array_keys($convertArr))){
            $where[] = ['type','=',$type];
        } else {
            $where[] = ['type','not in',array_keys($convertArr)];

        }
        $where[] = ['vacancy_id','=',$vacancy_id];
        $where[] = ['is_pay','=',1];
        //先查询是否合法
        $is_exit = Db::name('house_user_bind')->where(['uid'=>$this->uid,'vacancy_id'=>$vacancy_id,'type'=>0])->find();
        if(!$is_exit) {
            return $this->returnJson([],'查询错误!',400);
        }

        $data = Db::name('cost')->where($where)->page($page,config('app.limit'))->order('cost_month','desc')->field('cost_id,cost_month,pay_money,type')->select()->toArray();
        $total =  Db::name('cost')->where($where)->count();
        $res['total'] = $total;
        $res['data'] = $data;
        return $this->returnJson($res);
    }

    //某个房间下的某个收费项的未缴费缴费列表
    //具体房间未缴费列表
    public function  vacancyPayList() {
        $vacancy_id = Request::param('vacancy_id');
        $type = Request::param('type'); //property|water|electric|gas|park|other,除了other,其他都能对应表中的type
        $page = Request::param('page',1);

        $convertArr = $this->convertArr;
        if(in_array($type,array_keys($convertArr))){
            $where[] = ['type','=',$type];
        } else {
            $where[] = ['type','not in',array_keys($convertArr)];
        }
        $where[] = ['vacancy_id','=',$vacancy_id];
        $where[] = ['is_pay','=',0];

        //查询该房间的服务结束时间
        $property_end_time = Db::name('house_vacancy')->where(['vacancy_id'=>$vacancy_id])->value('property_end_time');
        if($property_end_time){
            $where[] = ['cost_month','>',$property_end_time];
        } else {
            //展示空数据
            return $this->returnJson();
        }
        //先查询是否合法
        $is_exit = Db::name('house_user_bind')->where(['uid'=>$this->uid,'vacancy_id'=>$vacancy_id,'type'=>0])->find();
        if(!$is_exit) {
            return $this->returnJson([],'查询错误!',400);
        }

        $data = Db::name('cost')->where($where)->page($page,config('app.limit'))->order('cost_month','asc')->field('cost_id,cost_month,pay_money,type')->select()->toArray();
        $total =  Db::name('cost')->where($where)->count();
        $res['total'] = $total;
        $res['data'] = $data;
        return $this->returnJson($res);
    }

    //查看具体的订单详情
    public function getDetailPay(){
        $cost_id = Request::param('cost_id');
        $data = Db::name('cost')->where(['cost_id'=>$cost_id])->find();
        $typeArr = $this->convertArr;
        $myunit = $this->myUnit;
        $priceUnit = $this->priceUnit;
        $vacancyInfo = Db::name('house_vacancy')->where(['vacancy_id'=>$data['vacancy_id']])->field('vacancy_code,layout_id')->find();
        $vacancyAddress = Common::getVacancyAddress($vacancyInfo['vacancy_code'],$vacancyInfo['layout_id']);
        $data['vacancy_address'] = $vacancyAddress['vacancy_address'];
        $data['type_zh'] = isset($typeArr[$data['type']]) ? $typeArr[$data['type']] : "自定义";
        if($data['is_pay']==1) {
            $orderInfo = Db::name('pay_order')->where(['order_id'=>$data['order_id']])->field('order_num,pay_type')->find();
            if($orderInfo) {
                $data['pay_type'] = $orderInfo['pay_type'];
                $data['order_num'] = $orderInfo['order_num'];
            } else {
                $data['pay_type'] = "暂无";
                $data['order_num'] = "暂无";
            }
        } else {
            $data['pay_type'] = "暂无";
            $data['order_num'] = "暂无";
        }
        if(in_array($data['type'],['water','electric','gas','property'])) {
            $data['area'] = $data['area'].$myunit[$data['type']];
            $data['price'] = $data['price'].$priceUnit[$data['type']];
        } else{
            $data['area'] = "无";
            $data['price'] = "暂无";
        }
        return $this->returnJson(Common::changeField($data,['pay_time','create_time']));
    }



    //生成订单
    public function createOrder(){
        $vacancy_id = Request::param('vacancy_id');
        $bind_id = Request::param('bind_id');
        $cost_ids = Request::param('cost_ids');

        //验证物业费订单是否是连续的
        $where['type'] = 'property';
        $where['is_pay'] = 0;
        $where['vacancy_id'] = $vacancy_id;

        //获取房间的物业服务时间,
        $property_end_time = Db::name('house_vacancy')->where(['vacancy_id'=>$vacancy_id])->value('property_end_time');
        if($property_end_time) {
            $whereOne[] = ['cost_month','>',$property_end_time];
        } else {
            $whereOne = [];
        }
        $property_cost_ids =  Db::name('cost')->where($where)->where($whereOne)->whereIn('cost_id',$cost_ids)->column('cost_id'); //上传的未缴物业费的连续cost_id
        //如果物业费选择了,则判断
        if($property_cost_ids) {
            $limit = count($property_cost_ids);
            $cost_property_ids = Db::name('cost')->where($where)->where($whereOne)->limit($limit)->column('cost_id');
            if($cost_property_ids != $property_cost_ids) {
                return $this->returnJson([],'物业费缴费必须连续!',400);
            }
        }
        $total_money = Request::param('total_money',0);
        //判断金额是否一致
        unset($where['type']);
        $total = Db::name('cost')->where($where)->whereIn('cost_id',$cost_ids)->sum('pay_money');
        if($total != $total_money) {
            return $this->returnJson([],'支付金额不正确!',400);
        }
        $data['uid'] = $this->uid;
        if(count($cost_ids)>1){
            $data['order_type'] = "多订单收费";
        } else {
            $type =Db::name('cost')->whereIn('cost_id',$cost_ids)->value('type');
            $data['order_type'] = $type;
        }
        $data['order_name'] = "社区收费";
        $data['order_num'] = createOrderNum();
        $data['vacancy_id'] = $vacancy_id;
        $res =  $this->getProperty($data['vacancy_id']);
        if($res['code'] !=200){
            return $this->returnJson([],$res['data'],400);
        }
        $data['property_id'] =$res['data']['property_id'];
        $data['village_id'] =$res['data']['village_id'];
        $data['bind_id'] = $bind_id;
        $data['money'] = $total;
        $data['create_time'] = time();
        $data['cost_ids'] = json_encode($cost_ids);
        $data['money'] = $total;
        $order_id = Db::name('pay_order')->insertGetId($data);
        if($order_id) {
            unset($res);
            $res['order_id'] = $order_id;
            //cost表中关联order_id
            Db::name('cost')->whereIn('cost_id',$cost_ids)->save(['order_id'=>$order_id]);
            return $this->returnJson($res);
        } else{
            return  $this->returnJson([],'添加失败!',400);
        }

    }

    //根据房间id获取当前的物业id和小区id
    public function getProperty($vacancy_id) {
        $data = Db::name('house_vacancy')->alias('hv')->leftJoin('house_village hvi','hvi.village_id = hv.village_id')->where(['hv.vacancy_id'=>$vacancy_id])->field('hvi.village_id,hvi.property_id')->find();
        if($data){
            return ['code'=>200,'data'=>$data];
        } else {
            return ['code'=>400,'data'=>'数据错误!'];
        }
    }

    //生成支付参数
    public function createPaySign() {
        $order_id = Request::param('order_id');
        $total_money = Request::param('total_money');
        $vacancy_id = Request::param('vacancy_id');
        $pay_type = Request::param('pay_type','alipay'); //weixin|alipay
        if(empty($order_id)) {
            return $this->returnJson([],'订单未找到!',400);
        }
        if($this->checkOrder($order_id,$total_money,$vacancy_id)){
            $orderInfo = Db::name('pay_order')->where(['order_id'=>$order_id])->find();
            //支付宝支付
            if($pay_type =='alipay') {
                $param['out_trade_no'] = $orderInfo['order_num'];
                $param['subject'] = $orderInfo['order_name'];
                $param['total_amount'] = floatval($orderInfo['money']);
                $res= $this->getAliPaySign($param);
                Db::name('pay_order')->where(['order_id'=>$order_id])->save(['pay_type'=>"支付宝"]);
            //微信支付
            } else {
                $param['order_id'] = $orderInfo['order_id'];
                $param['total_money'] = $orderInfo['money'];
                $param['order_name'] = $orderInfo['order_name'];
                $param['order_num'] = $orderInfo['order_num'];
                $res= $this->getWeiXinPaySign($param);
                //更改订单的支付方式
                Db::name('pay_order')->where(['order_id'=>$order_id])->save(['pay_type'=>"微信"]);
            }
            return $this->returnJson($res);
        } else {
            return $this->returnJson([],'非法的订单信息!',400);
        }
    }
    //获取支付宝支付参数
    public function getAliPaySign($param) {
        require_once "../extend/aliPay/AopClient.php";
        require_once "../extend/aliPay/request/AlipayTradeAppPayRequest.php";
        $aop = new \AopClient();
//        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
//        $aop->apiVersion = '1.0';
//        $aop->postCharset = 'utf-8';
//        $aop->format = 'json';
        $aop->appId = config('app.pay_alipay_appid');
        $aop->rsaPrivateKey = config('app.pay_alipay_merchant_private_key');
        $aop->alipayrsaPublicKey = config('app.pay_alipay_public_key');
        $aop->signType = config('app.pay_alipay_sign_type');
        $request = new \AlipayTradeAppPayRequest();
        $request->setNotifyUrl(config('app.notifyurl'));
        $request->setBizContent(json_encode($param));
        $response = $aop->sdkExecute($request);
        return $response;
    }


    //获取微信支付参数
    public function getWeiXinPaySign($param) {
        require_once "../extend/weixin/Weixin.php";
        $configArr = config('app.weixinPay');
        $weixin = new \Weixin($param,$configArr);
        return $weixin->pay();
    }

    //检查订单是否合法
    public function checkOrder($order_id,$total_money,$vacancy_id) {
        $where['order_id'] = $order_id;
        $where['uid'] = $this->uid;
        $where['vacancy_id'] = $vacancy_id;
        $money = Db::name('pay_order')->where($where)->value('money');
        if($money != $total_money) {
            return false;
        }
        return true;
    }







}