<?php
declare (strict_types = 1);

namespace app\apicom\controller;
use app\apicom\model\JWT;
use app\apicom\model\Money;
use app\apicom\model\Member as MemberModel;
use app\apicom\model\Bank as BankModel;
use think\facade\Db;
use think\request;
use util\RedisUtil;

class Member extends BaseController
{
    
    //用户中心首页数据接口 登录后获取的用户信息 未登录初始化 返回 data = 0
    public function index()
    {
        if(!$this->token || $this->userId == '') return ajaxmsg('未登录',500);
        $money = Money::getMoney($this->userId);
        $money['account']         = money_convert($money['account']);
        $money['freeze']          = money_convert($money['freeze']);
        $money['operate_account'] = money_convert($money['operate_account']);
        $money['bond_account']    = money_convert($money['bond_account']);
        $money['total']           = money_convert($money['total']);

        $data['money'] = $money;

        $msg_num   = Db::name('member_message')->where(['mid'=>$this->userId,'status'=>0])->count();
        $mobile    = Db::name('member')->alias('m')->field('id,mobile,agent_id,head_img,name')->where(['id'=>$this->userId,'status'=>1])->find();
        $agent_num = Db::name('member')->where(['agent_far'=>$this->userId,'status'=>1])->count();

        $other['msg_num']  = $msg_num;
        $other['mobile']   = substr_replace(strval($mobile['mobile']),'****',3,4);
        $other['agent_id'] = $mobile['agent_id'];
        $other['link_m']   = $agent_num;
        $other['name']     = $mobile['name'];
        $other['head_img'] = $mobile['head_img'] ? sysConfig('app_url').str_replace("'\'",'/',$mobile['head_img']) : '';

        $token = array(
            "uid"    => $mobile['id'],
            'doHost' => WS_SERVER_IP,
            'doTime' => time(),
            "mobile" => $mobile['mobile'],
        );
        $jwt = JWT::encode($token,LOCAL_TRADING_TOKEN);
        RedisUtil::cacheToken($jwt, $token);
        $other['token'] = $jwt;
        
        $data['infos']   = $other;
        return ajaxmsg('登陆信息',1,$data);
    }
    public function userInfo()
    {
        if(!$this->token || $this->userId == '') return ajaxmsg('未登录',500);
        $minfo = MemberModel::getMemberInfoByID($this->userId);
        unset($minfo['passwd']);
        unset($minfo['paywd']);
        $minfo['id_card']         = $minfo['id_card'] ?? '';
        $minfo['name']            = $minfo['name'] ?? '';
        $minfo['account']         = money_convert($minfo['account']);
        $minfo['freeze']          = money_convert($minfo['freeze']);
        $minfo['operate_account'] = money_convert($minfo['operate_account']);
        $minfo['bond_account']    = money_convert($minfo['bond_account']);
        $minfo['head_img']        = sysConfig('app_url').str_replace("\\",'/',$minfo['head_img']) ?? '';
        $token = array(
            "uid"    => $minfo['id'],
            'doHost' => WS_SERVER_IP,
            'doTime' => time(),
            "mobile" => $minfo['mobile'],
        );
        $jwt = JWT::encode($token,LOCAL_TRADING_TOKEN);
        RedisUtil::cacheToken($jwt, $token);
        $minfo['token'] = $jwt;
        return ajaxmsg('用户信息', 1, $minfo);
    }
    /**省市调用**/
    public  function getArea()
    {
        $reid = input('reid', '', ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $area = areaList($reid);
        return ajaxmsg('银行卡信息',1,$area);
    }
    /**
     * 用户银行卡操作
     */
    public function bankInfo(){

        if(!$this->token || $this->userId == '') return ajaxmsg('未登录',500);
        $bank = sysConfig('web_bank');
        if(!$bank) return false;
        $list = explode(PHP_EOL,$bank);
        $rate_val = array();
        foreach ($list as $k => $v){
            $arr = array(
                'id'   => $k,
                'name' => preg_replace('/\|img/', '',explode(':',$v)[1]),
            );
            array_push($rate_val, $arr);
        }
        $data['real'] = Db::name('member')->field('name,mobile,id_card')->where(['id'=>$this->userId])->find();
        $data['list'] = $rate_val;
        $data['bank'] = Db::name('member_bank')->where(['mid'=>$this->userId])->select();
        return ajaxmsg('银行卡信息',1,$data);
    }
    /**
     * 用户银行卡操作
     */
    public function bankInfoData()
    {
        if(!$this->token || $this->userId == '') return ajaxmsg('未登录',500);
        $id  = input('id', '', ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $res = BankModel::bankInfo($id) ?? [];
        return ajaxmsg('银行卡信息',1,$res);
    }
    /***
     *添加银行卡
     **/
    public function addBank()
    {
        if(!$this->token || $this->userId == '') return ajaxmsg('未登录',500);
        $data['mid']       = $this->userId;
        $data['id']        = input('id', '', ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $data['card']      = input('card', '');
        $data['id_card']   = input('id_card', '', ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $data['mobile']    = input('mobile', '', ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $data['real_name'] = input('real_name', '');
        $data['bank_name'] = input('bank_name', '');
        $name = Db::name('member')->where(['id'=>$this->userId])->update(['name'=>$data['real_name'],'id_card'=>$data['id_card'],'id_auth'=>1,'auth_time'=>time(),'create_ip' => getClientIp()]);
        // 检测是否满足实名赠送管理费活动
        if(sysConfig('give_open') == 1 && $name == 1) Money::setGiveFee($this->userId, 'give_realname', 0);
                
        if(!$name) return ajaxmsg('实名认证失败',0);
        $res = BankModel::saveData($data);
        return ajaxmsg($res['message'],$res['status']);
    }
    /*
     * 删除银行卡
     * id 要删除的银行卡id
     * mid 用户id
     */
    public function delBank()
    {
        if(!$this->token || $this->userId == '') return ajaxmsg('未登录',500);
        $id   = input('id' , '', ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $res  = BankModel::del_bank($id);
        if(!$res) return ajaxmsg('解绑失败，请联系客服',0);
        return ajaxmsg('解绑成功',1);
    }
    /*
     * 编辑银行卡
     * id 要编辑的银行卡id
     * mid 用户id
     */
    public function editBank()
    {
        if(!$this->token || $this->userId == '') return ajaxmsg('未登录',500);
        $id  = input('id' , '', ['trim', FILTER_SANITIZE_NUMBER_INT]);
        $BankModel = new BankModel;
        $res = $BankModel->bankInfo($id) ?? [];
        if(!$res) return ajaxmsg('编辑失败',0);
        if($res['mid'] != $this->userId) return ajaxmsg('您要编辑的银行卡不在您名下',0);
        //$name = Db::name('member')->where(['id'=>$this->userId])->value('name');
        //$data['name']     = $name;
        //$data['bank_id']  = $id;
        $data['bankinfo'] = $res;
        $bank = sysConfig('web_bank');
        if(!$bank) return false;
        $list = explode(PHP_EOL,$bank);
        $rate_val = array();
        foreach ($list as $k => $v){
            $arr = array(
                'id'   => $k,
                'name' => preg_replace('/\|img/', '',explode(':',$v)[1]),
            );
            array_push($rate_val, $arr);
        }
        $data['web_bank'] = $rate_val;
        return ajaxmsg('编辑信息',1,$data);
    }
    /*
     * 保存编辑数据
     */
    public function doEdit()
    {
        if(!$this->token || $this->userId == '') return ajaxmsg('未登录',500);
        $data = input();
        $result = $this->validate($data, 'BankCard.Complete');
        if($result !== true) return ajaxmsg($result,0);
        $table['id']        = $data['id'] ?? '';
        $table['mid']       = $this->userId ?? '';
        $table['bank']      = $data['bank'] ?? '';
        $table['branch']    = $data['branch'] ?? '';
        $table['card']      = $data['card'] ?? '';
        $table['province']  = $data['province'] ?? '';
        $table['city']      = $data['city'] ?? '';
        $table['real_name'] = $data['real_name'] ?? '';
        $table['create_ip'] = getClientIp() ?? '';
        $res  = BankModel::upEdit($table);
        return ajaxmsg($res['message'],$res['status']);
    }
    
}