<?php
namespace wstmart\common\model;
use think\Db;
class Ectwallet extends Base{
    protected $table = 'hyh_user_ectwallet';
     /**
      * 获取地址列表
      */
      public function listQuery($uId=0){
        $userId = ((int)$uId==0)?(int)session('WST_USER.userId'):$uId;
        $where = ['userId'=>(int)$userId,'dataFlag'=>1];
        $rs = $this->order('isDefault desc, eWalletId desc')->where($where)->select();
        return $rs;
      }

    /**
     * 新增
     */
    public function add($uId=0){
        $data = input('post.');
        unset($data['eWalletId']);
        $data['userId'] = ((int)$uId==0)?(int)session('WST_USER.userId'):$uId;
        $data['createTime'] = time();
        if($data['userId']==0)return WSTReturn('新增失败,请先登录');
        $result = $this->validate('EctWallet.add')->allowField(true)->save($data);
        if(false !== $result){
            if((int)input('post.isDefault')==1){
                $this->where("eWalletId != $this->eWalletId and userId=".$data['userId'])->setField('isDefault',0);
            }
            return WSTReturn('新增成功',1,['eWalletId'=>$this->eWalletId]);
        }else{
            return WSTReturn($this->getError(),-1);
        }
    }
    /**
     * [infoById 根据钱包地址id 获取钱包地址信息]
     * @param  [type] $eWalletId [钱包地址id]
     * @return [type]     [description]
     */
    public function infoById($eWalletId){
        $where['eWalletId'] = (int)($eWalletId);
        $data = Db::name('user_ectwallet')->where($where)->field('eWalletId,eAddress')->find();
        if(!empty($data))return $data;      
    }
    /**
     * 编辑
     */
    public function edit($uId=0){
        $userId = ((int)$uId==0)?(int)session('WST_USER.userId'):$uId;
        $id = (int)input('post.eWalletId/d');
        $data = input('post.');
        $result = $this->validate('EctWallet.edit')->allowField(true)->save($data,['eWalletId'=>$id,'userId'=>$userId]);
        //修改默认地址
        if((int)input('post.isDefault')==1)
          $this->where("eWalletId != $id and userId=".$userId)->setField('isDefault',0);
        if(false !== $result){
            return WSTReturn("编辑成功", 1);
        }else{
            return WSTReturn($this->getError(),-1);
        }
    }
    /**
     * 删除
     */
    public function del($uId=0){
        $userId = ((int)$uId==0)?(int)session('WST_USER.userId'):$uId;
        $id = input('post.eWalletId/d');
        $data = [];
        $data['dataFlag'] = -1;
        $result = $this->update($data,['eWalletId'=>$id,'userId'=>$userId]);
        if(false !== $result){
            return WSTReturn("删除成功", 1);
        }else{
            return WSTReturn($this->getError(),-1);
        }
    }
    /**
    * 设置为默认地址
    */
    public function setDefault($uId=0){
        $userId = ((int)$uId==0)?(int)session('WST_USER.userId'):$uId;
        $id = (int)input('post.eWalletId');
        $this->where(["eWalletId"=>['<>',$id],'userId'=>$userId] )->setField('isDefault',0);
        $rs = $this->where("eWalletId = $id and userId=".$userId)->setField('isDefault',1);
        if(false !== $rs){
            return WSTReturn("设置成功", 1);
        }else{
            return WSTReturn($this->getError(),-1);
        }
    }
    /**
     * 获取默认地址
     */
    public function getDefaultAddress($uId=0){
    	$userId = ((int)$uId==0)?(int)session('WST_USER.userId'):$uId;
    	$where = ['userId'=>$userId,'dataFlag'=>1,'isDefault'=>1];
        $rs = Db::name('user_ectwallet')->where($where)->field('eWalletId,eAddress')->find();
        if(empty($rs))return '';
         return $rs;
    }
    /**
     * 获取ect数目
     */
    public function getEctAddress($uId=0){
        $userId = ((int)($uId==0))?(int)session('WST_USER.userId'):$uId;
        $address = cache('USER_BLOCK_ADDRESS_'.$userId);
        if(!$address){      
            $where = ['userId'=>$userId];    
            $address= Db::name('block_user_ect_address')->where($where)->value('address');
            if($address){                
                cache('USER_BLOCK_ADDRESS_'.$userId,$address,0);
            }
        }
        return WSTReturn('',1,['userId'=>$userId,'address'=>$address]);
    }
    /**
     * 获取ect数目
     */
    public function getEctNum($uId=0){
        $userId = ((int)($uId==0))?(int)session('WST_USER.userId'):$uId;
        $where = ['userId'=>$userId];
        $num = Db::name('users')->where($where)->value('userECT');
        return $num;
    }   
    /**
     * 获取ect充值记录
     */
    public function getEctRechargeLog($uId=0){
        $userId = ((int)($uId==0))?(int)session('WST_USER.userId'):$uId;
        if($userId==0) return WSTReturn('请先登录','-999');
        $where = ['userId'=>$userId];
        $rs['list'] = Db::name('block_user_ect_recharge_log')->where($where)->order('id desc')->field('status,value,createTime')->paginate(10)->toArray();
        $rs['address'] = '';
        $cacheData = cache('USER_BLOCK_ADDRESS_'.$userId);
        if($cacheData){
            $rs['address'] = $cacheData;
        }else{
            $address= Db::name('block_user_ect_address')->where($where)->value('address');
            if($address){
                $rs['address'] = $address;
                cache('USER_BLOCK_ADDRESS_'.$userId,$address,0);
            }
        }
        return $rs;
    }
    /**
     * 获取ect提现记录
     */
    public function getUserEctCashLog($uId=0){
        $userId = ((int)($uId==0))?(int)session('WST_USER.userId'):$uId;
        if($userId==0) return WSTReturn('请先登录','-999');
        $where = ['userId'=>$userId];
        $rs['list'] = Db::name('user_ect_cash_log')->where($where)->order('id desc')->field('status,ectNum,toAccount,createTime')->paginate(10)->toArray();        
        return $rs;
    }
    
    /**
     * 获取ect变更记录
     */
    public function getEctLog($uId=0){
        $userId = ((int)($uId==0))?(int)session('WST_USER.userId'):$uId;
        $where = ['userId'=>$userId];
        $rs = Db::name('user_ect_log')->where($where)->order('createTime desc')->paginate(10)->toArray();
        return $rs;
    }
    /**
     * 提现
     */
    public function withdraw($uId=0){
        //return WSTReturn('系统调试中,请稍候重试',-1);
        $userId = ((int)($uId==0))?(int)session('WST_USER.userId'):$uId; 
        if($userId==0)return WSTReturn('请先登录','-999');
        //获取提现ect数量
        $ectNum = abs((float)input('post.ectNum'));
        //获取支付密码
        $payPwd = input('post.payPwd');
        //获取钱包地址
        $eAddress = trim(input('post.eAddress'));
        $where = ['userId'=>$userId,'eAddress'=>$eAddress];
        $exist = $this->where($where)->find();
        if(empty($exist))return WSTReturn('地址不正确',-1);
        if($payPwd=='')return WSTReturn('密码不能为空');
        $user = model('users')->get($userId);
        //获取用户ECT数量
        $userECT = (float)$user->userECT;
        if($ectNum<500)return WSTReturn('ECT数量最低提取500',-1); 
        //与用户ect数量作比较
        if($userECT<$ectNum)return WSTReturn('ECT数量不足',-1); 
        //与数据库支付密码作比较
        if(md5($payPwd.$user->loginSecret) !=$user->payPwd)return WSTReturn('支付密码错误',-1);
        $fp = fopen("cash.lock", "r");
        if(flock($fp,LOCK_EX | LOCK_NB)) {//if(flock($fp,LOCK_EX))阻塞(等待)模式
            // if(Db::table('rd_user_give_coin')->where(['user_id'=>$user->hyhlm_id])->find() || Db::table('rd_user_give_car_coin')->where(['user_id'=>$user->hyhlm_id])->find()){  
            //     flock($fp,LOCK_UN);
            //     fclose($fp);
            //     return WSTReturn('系统调试中,请稍候重试',-1); 
            // }
            // if($user->userType == 0){
            //     flock($fp,LOCK_UN);
            //     fclose($fp);
            //     return WSTReturn('系统调试中,请稍候重试',-1); 
            // }
            $dataSrc = 4;
            $remark ="提现";
            $ectType = 2;      
            $update =array('userECT'=>['exp','userECT-'.$ectNum]);
            Db::startTrans();
            try {
                $rs = ectLog($userId,$ectNum,$dataSrc,$remark,$update,$ectType);
                $cash_id = $this->ectCashLog($userId,$ectNum,$eAddress,'');
                if($rs && $cash_id){
                    flock($fp,LOCK_UN);
                    fclose($fp);
                    Db::commit();
                    return WSTReturn('提现成功,预计审核次日到账(节假日顺延),请耐心等待!',-1);
                   // return WSTReturn('提现成功',1,['id'=>$cash_id]);
                }else{                    
                    Db::rollback();errLog($e);
                    flock($fp,LOCK_UN);
                    fclose($fp);
                    return WSTReturn('提现失败,请重试!',-1);
                }
            } catch (Exception $e) {
                Db::rollback();errLog($e);
                return WSTReturn('提现失败,请重试',-1);
            }
        }else{
            fclose($fp);
            return WSTReturn('系统繁忙,请稍后再试');              
        }
    }
    function ectCashLog($userId,$ectNum,$toAccount,$remark=''){
        $data['userId']         = $userId;
        $data['ectNum']         = $ectNum;
        $data['toAccount']      = $toAccount;
        $data['dataRemarks']    = $remark;
        $data['createTime']     = time(); 
        // $disabled_ids = [888,1843,15,892,1359,2150];
        // if(in_array($userId,$disabled_ids)){
        //     $data['status']    = 2;
        // }
        return Db::name('user_ect_cash_log')->insertGetid($data);
    }
}