<?php
// +----------------------------------------------------------------------
// | [ WE CAN DO IT MORE SIMPLE  ]
// +----------------------------------------------------------------------
// | Copyright (c) 2018-2020 rights reserved.
// +----------------------------------------------------------------------
// |
// +----------------------------------------------------------------------
// | Date: 2020-08-31 20:43
// +----------------------------------------------------------------------

namespace app\system\controller;


use app\BaseController;
use app\lib\OrderLib;
use app\model\api\PayTrade;
use library\utils\WxpayV2 as wxpayApi;
use app\model\api\User as UserModel;
use app\model\api\UserDetail as UserDetailModel;
use app\model\api\UserScoreDetail as UserScoreDetailModel;
use app\model\api\UserShowTemplate;
use library\services\UtilService;
use app\Request;
use think\facade\Db;

class Member extends BaseController
{
    /**
     * 会员列表
     * @param Request $request
     * @return mixed
     */
    public function list(Request $request)
    {
        $pageSize = 50;
        $post =  UtilService::getMore([
            ['page',1],
            ['pageSize',50],
            ['nickname',''],
            ['uid',''],
            ['parent_uid',''],
            ['mobile',''],
            ['status',''],
            ['time',[]],
        ],$request);
        $data = (new UserModel)->getDataList($post,"*",1);
        return app('json')->success([
            'list'      => $data["list"],
            'pageCount' => $data["totalCount"],
            'pageSize'  => $data["pageSize"],
            'page'      => $data["page"],
        ]);
    }

    /**
     * 编辑
     */
    public function save(Request $request){
        $post = UtilService::getMore([
            ['uid','0'],
            ['status',''],
            ['name',''],
            ['nickname',''],
        ],$request);
        $uid = (int)$post["uid"];
        if(empty($uid)){
            return app('json')->fail("参数错误");
        }
        unset($post["uid"]);
        $r=0;
        if(!in_array((string)$post["status"],['1','-1'])){
            return app('json')->success("状态错误");
        }
        //用户信息
        $save=[];
        $save["status"] = $post["status"];
        if(!empty($post["name"])){
            $save["name"] = $post["name"];
        }
        if(!empty($post["nickname"])){
            $save["nickname"] = $post["nickname"];
        }
        $r = (new UserModel)->where("uid",$uid)->update($save);
        return app('json')->success("数据保存成功");
    }

    /**
     * 会员收益明细列表
     * @param Request $request
     * @return mixed
     */
    public function moneyDetail (Request $request)
    {
        $pageSize = 50;
        $post     = UtilService::getMore(
            [
                ['page', '1'],
                ['uid', '0'],
                ['mobile', ''],
                ['time', []],
                ['type', ''],
                ['code', ''],
            ], $request
        );
        $where    = [];
        if (!empty($post['uid'])){
            $where[]=["d.uid","=",$post['uid']];
        }
        if (!empty($post['mobile'])) {
            $m  = Db::name("user")->where("mobile",$post['mobile'])->find();
            if(!empty($m)) {
                $where[]=["d.uid","=",$m['uid']];
            }
        }
        $startTime = "";
        $endTime = "";
        if(!empty($post['time'][0]) && !empty($post['time'][1])) {
           $startTime =  strtotime($post['time'][0]);
           $endTime = strtotime($post['time'][1]);
           $where[]=["d.time","between","{$startTime},{$endTime}"];
        }
        if (!empty($post['type']) && in_array(strval($post['type']), ["1","-1"])) {
            $where[]=["d.type","=",$post['type']];
        }
        if(!empty($post['code']) && $post['code']!="all"){
            $where[]=["d.code","=",$post['code']];
        }
        $data = (new UserDetailModel)
                ->alias("d")
                ->field("d.*,u.mobile")
                ->leftJoin("user u", "u.uid = d.uid")
                ->where($where)
                ->page((int)$post["page"], $pageSize)
                ->order("d.id","desc")
                ->select()
                ->toArray();
        $pageCount = (new UserDetailModel)->alias("d")->where($where)->count();
        foreach($where as $k=>$v){
            if($v[0]=="d.type"){
                array_splice($where,$k,1);
            }
        }
        //收入
        $inWhere = $where;
        $inWhere[]=["d.type","=",1];
        $inTotal   = (new UserDetailModel)->alias("d")->where($inWhere)->sum("d.into");
        //支出
        $outWhere = $where;
        $outWhere[]=["d.type","=",-1];
        $outTotal  = (new UserDetailModel)->alias("d")->where($outWhere)->sum("d.into");     
        $result = UtilService::getParam(
            [
                'id',
                'uid',
                'mobile',
                'title',
                'content',
                'type',
                'into',
                'money',
                ['time', 'time', 'date("Y-m-d H:i:s",$1)'],
            ], $data);
        return app('json')->success([
            'list'      => $result,
            'pageCount' => $pageCount,
            'pageSize'  => $pageSize,
            'page'      => $post['page'],
            'inTotal'   => empty($inTotal) ? 0 : floatval($inTotal),
            'outTotal'  => empty($outTotal)? 0 : floatval($outTotal),
        ]);
    }
    /**
     * 收益增/减
     * @param Request $request
     */
    public function moneyDetailSave(Request $request)
    {
        $post = UtilService::getMore([
            ['uid', '', 'empty', '参数错误'],
            ['type', '1'],
            ['into', '0', 'gt|0', '输入值错误'],
            ['othen', ''],
        ], $request);
        $userData = (new UserModel)->where("uid",$post["uid"])->find();
        if(empty($userData)){
            return app('json')->fail('用户不存在，请输入正确的用户uid');
        }
        if(!in_array((string)$post["type"],["1","-1"])){
            return app('json')->fail('请选择增减');
        }
        $post["into"] = bcadd("0",$post["into"],2);
        if(!is_numeric($post["into"]) || $post["into"]<=0){
            return app('json')->fail('请输入正确的金额');
        }
        if ($post['type'] == 1)
            $bool = (new UserDetailModel)->adminAddMoney($userData['uid'], $post['into'],  $request->adminInfo['id'],$post['othen']);

        if ($post['type'] == -1){
            if($userData["money"]-$post['into']<0){
                return app('json')->fail('余额不足');
            }
            $bool = (new UserDetailModel)->adminCutMoney($userData['uid'], $post['into'],  $request->adminInfo['id'],$post['othen']);
        }

        if ($bool)
            return app('json')->success('操作成功');
        else
            return app('json')->fail('操作失败');
    }
    
    /**
     * 钻石收益明细列表
     * @param Request $request
     * @return mixed
     */
    public function scoreDetail (Request $request)
    {
        $pageSize = 50;
        $post     = UtilService::getMore(
            [
                ['page', '1'],
                ['uid', '0'],
                ['mobile', ''],
                ['type', ''],
                ['code', ''],
                ['time', []],
            ], $request
        );
        $where    = [];
        if (!empty($post['uid'])){
            $where[]=["d.uid","=",$post['uid']];
        }else if (!empty($post['mobile'])) {
            $m  = Db::name("user")->where("mobile",$post['mobile'])->find();
            if(!empty($m)) {
                $where[]=["d.uid","=",$m['uid']];
            }
        }
        $startTime = "";
        $endTime = "";
        if(!empty($post['time'][0]) && !empty($post['time'][1])) {
           $startTime =  strtotime($post['time'][0]);
           $endTime = strtotime($post['time'][1]);
           $where[]=["d.time","between","{$startTime},{$endTime}"];
        }
        if (!empty($post['type']) && in_array(strval($post['type']), ["1","-1"])) {
            $where[]=["d.type","=",$post['type']];
        }
        if (!empty($post['code'])) {
            $where[]=["d.code","=",$post['code']];
        }
        $data = (new UserScoreDetailModel)
                ->alias("d")
                ->field("d.*,u.mobile")
                ->leftJoin("user u", "u.uid = d.uid")
                ->where($where)
                ->page((int)$post["page"], $pageSize)
                ->order("d.id","desc")
                ->select()
                ->toArray();
        $pageCount = (new UserScoreDetailModel)->alias("d")->where($where)->count();
        foreach($where as $k=>$v){
            if($v[0]=="d.type"){
                array_splice($where,$k,1);
            }
        }
        //收入
        $inWhere = $where;
        $inWhere[]=["d.type","=",1];
        $inTotal   = (new UserScoreDetailModel)->alias("d")->where($inWhere)->sum("d.v");
        //支出
        $outWhere = $where;
        $outWhere[]=["d.type","=",-1];
        $outTotal  = (new UserScoreDetailModel)->alias("d")->where($outWhere)->sum("d.v");
        $result = UtilService::getParam(
            [
                'id',
                'uid',
                'mobile',
                'title',
                'content',
                'type',
                ['into','v'],
                'money',
                ['time', 'time', 'date("Y-m-d H:i:s",$1)'],
            ], $data);

        return app('json')->success([
            'list'      => $result,
            'pageCount' => $pageCount,
            'pageSize'  => $pageSize,
            'page'      => $post['page'],
            'inTotal'   => empty($inTotal) ? 0 : floatval($inTotal),
            'outTotal'  => empty($outTotal)? 0 : floatval($outTotal),
        ]);
    }
    /**
     * 积分增/减
     * @param Request $request
     */
    public function scoreDetailSave(Request $request)
    {
        $post = UtilService::getMore([
            ['uid', '', 'empty', '参数错误'],
            ['type', '1'],
            ['into', '0', 'gt|0', '输入值错误'],
            ['othen', ''],
        ], $request);
        $userData = (new UserModel)->where("uid",$post["uid"])->find();
        if(empty($userData)){
            return app('json')->fail('用户不存在，请输入正确的用户uid');
        }
        if ($post['type'] == 1)
            $bool = (new UserScoreDetailModel)->adminAddMoney($userData['uid'], intval($post['into']),  $request->adminInfo['id'],$post['othen']);

        if ($post['type'] == -1){
            if($userData["score"]-$post['into']<0){
                return app('json')->fail('剩余积分不足');
            }
            $bool = (new UserScoreDetailModel)->adminCutMoney($userData['uid'], intval($post['into']),  $request->adminInfo['id'],$post['othen']);
        }
            

        if ($bool)
            return app('json')->success('操作成功');
        else
            return app('json')->fail('操作失败');
    }
    
    /**
     * 获取会员数据
     * @param Request $request
     * @return mixed
     */
    public function getItem(Request $request)
    {
        $post   = UtilService::getMore([
            ['uid', 1],
        ]);
        $data = (new UserModel)
                ->alias("u")
                ->field("u.uid,u.mobile,u.nickname,u.avatar,u.status,u.regtime,u.lasttime,u.parent_uid.p.nickname as parent_nickname")
                ->leftJoin("user p","p.uid = u.parent_uid")
                ->where("u.uid",$post["uid"])
                ->find()
                ->toArray();
        if(!empty($data)){
            $data["regtime"] = date("Y-m-d H:i:s",$data["regtime"]);
            $data["lasttime"] = date("Y-m-d H:i:s",$data["lasttime"]);
        }
        return app('json')->success(empty($data) ? [] : $data);
    }
    public function shopSave(Request $request){
        $post = UtilService::getMore([
            ['id','','empty','参数错误'],
            ['name','','empty','请输入名称'],
            ['tel','','empty','请输入联系电话'],
            ['lx_name','','empty','请输入联系人'],
            ['address','','empty','请输入门店地址'],
            ['longitude',''],
            ['latitude',''],
            ['is_show',''],
        ],$request);
        $id = (int)$post["id"];
        if(empty($id)){
            return app('json')->fail("参数错误");
        }
        unset($post["id"]);
        $shopSave=[
            "name"      => $post["name"],
            "tel"       => $post["tel"],
            "address"   => $post["address"],
            "lx_name"   => $post["lx_name"],
            "longitude" => $post["longitude"],
            "latitude"  => $post["latitude"],
            "is_show"   => $post["is_show"]==1?1:0,
        ];
        if(empty($shopSave["name"])){
            return app('json')->fail("请输入门店名称");
        }
        if(empty($shopSave["tel"])){
            return app('json')->fail("请输入门店联系电话");
        }
        if(empty($shopSave["address"])){
            return app('json')->fail("请输入门店地址");
        }
        if(empty($shopSave["lx_name"])){
            return app('json')->fail("请输入门店联系人");
        }
        (new UserShopModel)->where("id",$id)->update($shopSave);
        return app('json')->success("数据保存成功");
        
    }
    public function shopList(Request $request){
        $pageSize = 50;
        $post     = UtilService::getMore(
            [
                ['page', '1'],
                ['uid', ''],
                ['is_show', ''],
                ['mobile', ''],
                ['name', ''],
                ['pageSize', ''],
            ], $request);
        $where    = [];
        if(!empty($post["pageSize"]) && $post["pageSize"]>50){
            $pageSize = (int)$post["pageSize"];
        }
        //用户
        if (!empty($post['uid'])){
            $where[]=["t.uid","=",$post['uid']];
        }else if (!empty($post['mobile'])) {
            $m  = Db::name("user")->where("mobile",$post['mobile'])->find();
            if(!empty($m)) {
                $where[]=["t.uid","=",$m['uid']];
            }
        }
        if(is_numeric($post['is_show']) && in_array((string)$post['is_show'],['0','1'])) {
            $where[]=["t.is_show","=",(int)$post['is_show']];
        }
         if(!empty($post['name'])){
            $where[]=["t.name","like","%{$post['name']}%"];
        }
        $data = (new UserShopModel)
                ->alias("t")
                ->field("t.*,u.nickname as nickname")
                ->leftJoin("user u" , "u.uid = t.uid")
                ->where($where)
                ->page((int)$post["page"], $pageSize)
                ->order("t.id","desc")
                ->select()
                ->toArray();
        $pageCount = (new UserShopModel)->alias("t")->where($where)->count();
        $result = UtilService::getParam(
            [
                'id',
                'uid',
                'nickname',
                'name',
                'area',
                'address',
                'tel',
                'lx_name',
                'longitude',
                "latitude",
                'is_show',
                ['time', 'time', function($item){
                    return empty($item) ? "--" : date("Y-m-d H:i:s",$item);
                }],
            ], $data);
        return app('json')->success([
            'list'      => $result,
            'pageCount' => $pageCount,
            'pageSize'  => $pageSize,
            'page'      => $post['page'],
        ]);
        
    }
    
    
    /**
     * 支付任务列表
     * @param \app\model\api\Request $request
     */
    public function payTradeList(Request $request){
        $pageSize = 50;
        $post     = UtilService::getMore(
            [
                ['page', '1'],
                ['uid', ''],
                ['status', ''],
                ['mobile', ''],
                ['type', ''],
                ['pay_no', ''],
                ['order_id', ''],
                ['time', []],
            ], $request);
        $where    = [];
        //用户
        if (!empty($post['uid'])){
            $where[]=["t.uid","=",$post['uid']];
        }else if (!empty($post['mobile'])) {
            $m  = Db::name("user")->where("mobile",$post['mobile'])->find();
            if(!empty($m)) {
                $where[]=["t.uid","=",$m['uid']];
            }
        }
        if(is_numeric($post['status']) && in_array((string)$post['status'],['0','1'])) {
            $where[]=["t.status","=",(int)$post['status']];
        }
        if(!empty($post['pay_type']) && in_array($post['pay_type'],['wxpay','system'])) {
            $where[]=["t.pay_type","=",$post['pay_type']];
        }
        if(!empty($post['type']) && in_array($post['type'],['pro','temp','activity'])) {
            $where[]=["t.type","=",$post['type']];
        }
        if(!empty($post['pay_no'])){
            $where[]=["t.pay_no","=",$post['pay_no']];
        }
        if(!empty($post['order_id'])){
            $where[]=["t.order_id","=",$post['order_id']];
        }
        
        $startTime = "";
        $endTime = "";
        if(!empty($post['time'][0]) && !empty($post['time'][1])) {
           $startTime =  strtotime($post['time'][0]);
           $endTime = strtotime($post['time'][1]);
           $where[]=["t.time","between","{$startTime},{$endTime}"];
        }
        $data = (new PayTrade)
                ->alias("t")
                ->field("t.*,u.nickname as nickname,a.username as admin_name")
                ->leftJoin("user u" , "u.uid = t.uid")
                ->leftJoin("admin a", "a.id  = t.admin_id")
                ->where($where)
                ->page((int)$post["page"], $pageSize)
                ->order("t.id","desc")
                ->select()
                ->toArray();
        $pageCount = (new PayTrade)->alias("t")->where($where)->count();
        $result = UtilService::getParam(
            [
                'id',
                'uid',
                'nickname',
                "admin_id",
                "admin_name",
                'pay_no',
                'out_trade_no',
                'pay_no',
                'order_id',
                'pay_type',
                'type',
                'money',
                'content',
                "d_json",
                'status',
                'mono',
                ['time', 'time', function($item){
                    return empty($item) ? "--" : date("Y-m-d H:i:s",$item);
                }],
                ['pay_time' , 'pay_time', function($item){
                    return empty($item) ? "--" : date("Y-m-d H:i:s",$item);
                }],
                ['pay_json', 'pay_json', function($item){
                    if(empty($item)){
                        return "";
                    }
                    $payData = json_decode($item,true);
                    return $payData;
                }],
            ], $data);
        return app('json')->success([
            'list'      => $result,
            'pageCount' => $pageCount,
            'pageSize'  => $pageSize,
            'page'      => $post['page'],
        ]);
    }
    /**
     * 搜索交易数据
     * @param Request $request
     */
    public function searchPayTrade(Request $request){
        $post     = UtilService::getMore(
            [
                ['id', '','empty',''],
            ], $request);
        $data = (new PayTrade)->where("id",$post["id"])->find();
        if(empty($data)){
            return app("json")->fail("数据不存在");
        }
        if($data["status"]==1 && !empty($data["pay_json"])){
            return app("json")->success("交易支付成功", json_decode($data["pay_json"],true));
        }
        $out_trade_no = $data["out_trade_no"];
        //微信支付
        if($data["pay_type"]=="wxpay"){
            $wxpay = new wxpayApi();
            $resAr = $wxpay->searchOrderQuery($out_trade_no);
            if(empty($resAr) || !is_array($resAr)){
                return app("json")->fail("查询失败");
            }
            if(empty($resAr["trade_state"])){
                return app("json")->fail("查询状态错误");
            }
            if($resAr["trade_state"]=="NOTPAY"){
                return app("json")->fail("未支付");
            }
            if($resAr["trade_state"]=="REFUND"){
                return app("json")->fail("转入退款");
            }
            if($resAr["trade_state"]=="CLOSED"){
                return app("json")->fail("已关闭");
            }
            if($resAr["trade_state"]=="REVOKED"){
                return app("json")->fail("已撤销（付款码支付）");
            }
            if($resAr["trade_state"]=="USERPAYING"){
                return app("json")->fail("用户支付中（付款码支付）");
            }
            if($resAr["trade_state"]=="PAYERROR"){
                return app("json")->fail("支付失败(其他原因，如银行返回失败)");
            }
            if($resAr["trade_state"]=="ACCEPT"){
                return app("json")->fail("已接收，等待扣款");
            }
            if($resAr["trade_state"]=="SUCCESS"){
                if(empty($resAr["payMoney"])){
                    return app("json")->fail("交易支付成功，但是查询不到金额信息");
                }
                $payDataInfo = [
                    'totalMoney' =>empty($resAr["total_fee"])      ? "未返回" : $resAr["total_fee"]/100,
                    'payMoney'   =>empty($resAr["cash_fee"])       ? "未返回" : $resAr["cash_fee"]/100,
                    'payTradeNo' =>empty($resAr["transaction_id"]) ? "未返回" : $resAr["transaction_id"],
                    'outTradeNo' =>empty($resAr["out_trade_no"])   ? "未返回" : $resAr["out_trade_no"],
                    "tradeStatus"=>empty($resAr["trade_state"])    ? "未返回" : $resAr["trade_state"],
                    "payTime"    =>empty($resAr["time_end"])       ? "未返回" : $resAr["time_end"],
                    "attach"     =>empty($resAr["attach"])         ? "未返回" : $resAr["attach"],
                ];
                //重新调用支付处理
                if(!empty($data["o_id"]) && $data["status"]==0){
                    $pay_json = json_encode($payDataInfo);
                    (new OrderLib)->orderPay($payDataInfo["outTradeNo"], $pay_json);
                }
                return app("json")->success("交易支付成功",$payDataInfo);
            }
            return app("json")->fail("支付状态未知");
        }
        return app("json")->fail("查询失败");
    }
    
    
    /**
     * 用户模板列表
     * @param Request $request
     */
    public function showTemplateList(Request $request){
        $post = UtilService::getMore([
            ['page', 1],
            ['pageSize', 50],
            ['uid', ''],
            ['mobile', ''],
        ], $request);
        $post["pageSize"] = $post["pageSize"]>50 ? 50 : (int)$post["pageSize"];
        $post["page"]     = $post["page"]<=0 ? 1 : (int)$post["page"];
        $where=[];
        //用户
        if (!empty($post['uid'])){
            $where[]=["ut.uid","=",$post['uid']];
        }else if (!empty($post['mobile'])) {
            $m  = Db::name("user")->where("mobile",$post['mobile'])->find();
            if(!empty($m)) {
                $where[]=["ut.uid","=",$m['uid']];
            }
        }
        $totalCount = (new UserShowTemplate)->alias("ut")->where($where)->count();
        $data=null;
        if($totalCount>0){
            $data = (new UserShowTemplate)
                ->field("ut.id,ut.uid,ut.start_time,t.id as show_template_id,t.title,t.price,t.old_price,t.status,t.imgs,t.is_hot,t.is_recommend,t.code,look_count,t.real_sales,t.unreal_sales,ut.is_default,u1.mobile,u1.nickname")
                ->alias("ut")
                ->join("show_template t", "t.id = ut.show_template_id","left")
                ->leftJoin("user u1","u1.uid = ut.uid")
                ->where($where)
                ->order("ut.id", "desc")
                ->page($post["page"], $post["pageSize"])
                ->select();
            foreach($data as $k=>$v){
                $data[$k]["is_use"]      = 1;//是否已经购买或者可以使用
                $data[$k]["imgs"]        = getImageAr($v["imgs"]);
                $data[$k]["img"]         = empty($data[$k]["imgs"]) ? "" : $data[$k]["imgs"][0];
                $data[$k]["sales_count"] = $data[$k]["real_sales"] + $data[$k]["unreal_sales"];
                unset($data[$k]["real_sales"]);
                unset($data[$k]["unreal_sales"]);
                $data[$k]["start_time"]  = date("Y-m-d H:i:s",$v["start_time"]);
                
            }
        }
        $data = empty($data)?[]:$data;
        return app('json')->success(["list" => $data, "pageSize" => $post["pageSize"],"page"=>$post["page"],"pageCount"=>$totalCount]);
    }

    
    
}
