<?php

namespace common\models;

use admin\util\AdminUtil;
use fx\util\FxUtil;
use Yii;
use yii\base\Exception;
use yii\db\Expression;

/**
 * This is the model class for table "fx_commission_apply".
 *
 * @property integer $id
 * @property integer $fx_uid
 * @property string $apply_money
 * @property integer $status
 * @property string $remit_time
 * @property string $auth_time
 * @property string $auth_memo
 * @property integer $auth_uid
 * @property integer $remit_uid
 * @property integer $delete_flag
 * @property string $create_time
 * @property string $update_time
 * @property string $update_user
 */
class FxCommissionApply extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'fx_commission_apply';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['fx_uid'], 'required'],
            [['fx_uid', 'status', 'auth_uid', 'remit_uid', 'delete_flag'], 'integer'],
            [['apply_money'], 'number'],
            [['create_time', 'update_time'], 'safe'],
            [['remit_time', 'auth_time', 'update_user'], 'string', 'max' => 50],
            [['auth_memo'], 'string', 'max' => 255],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'fx_uid' => 'Fx Uid',
            'apply_money' => 'Apply Money',
            'status' => 'Status',
            'remit_time' => 'Remit Time',
            'auth_time' => 'Auth Time',
            'auth_memo' => 'Auth Memo',
            'auth_uid' => 'Auth Uid',
            'remit_uid' => 'Remit Uid',
            'delete_flag' => 'Delete Flag',
            'create_time' => 'Create Time',
            'update_time' => 'Update Time',
            'update_user' => 'Update User',
        ];
    }

    /**
     * Function Description:提现明细
     * Function Name: getCommissionApplyList
     *
     * @return array|\yii\db\ActiveRecord[]
     *
     * @author 娄梦宁
     */
    public function getCommissionApplyList(){
        $fx_uid=FxUtil::$uid;
        $result=self::find()->select(['apply_money','status','date_format(create_time,"%m-%d %H:%i:%s") as create_date',"if(`status`=1,'未审核','已审核') as status_desc"])
            ->from(self::tableName())
            ->where(['and',['=','fx_uid',$fx_uid],['=','delete_flag',0]])
            ->asArray()
            ->all();
        return $result;
    }

    /**
     * Function Description:提交提现申请，申请表记录
     * Function Name: InsertApplyCommission
     * @param $apply_commission
     *
     * @return bool
     *
     * @author 娄梦宁
     */
    public function InsertApplyCommission($apply_commission){
        $values=[
            'status'=>1,
            'apply_money'=>$apply_commission,
            'fx_uid'=>FxUtil::$uid,
            'create_time'=>date('Y-m-d H:i:s'),
        ];
        $transaction=Yii::$app->db->beginTransaction();
        try{
            $this->attributes=$values;
            $res=$this->insert();
            if(!$res){
                throw new Exception('添加出错');
            }
            $transaction->commit();
            return true;
        }catch (Exception $e){
            $transaction->rollBack();
            return false;
        }
    }

    /**
     * Function Description:后台提现列表
     * Function Name: ApplyList
     * @param $param
     *
     * @return array
     *
     * @author 娄梦宁
     */
    public function ApplyList($param){
        $where=['and',['=','a.delete_flag',0]];
        if ($param['apply_user_name'] != '') {
            $where[] = ['like', 'b.nickname', $param['apply_user_name']];
        }
        if ($param['apply_user_phone'] != '') {
            $where[] = ['like', 'b.phone', $param['apply_user_phone']];
        }
        if ($param['start_time'] != '') {
            $where[] = ['>=', 'a.create_time', $param['start_time']];
        }
        if ($param['end_time'] != '') {
            $where[] = ['<', 'a.create_time', date('Y-m-d',strtotime("{$param['end_time']} +1 day"))];
        }
        if ($param['apply_status'] != '') {
            $where[] = ['=', 'a.status', $param['apply_status']];
        }
        $select=[
            'b.nickname as apply_user_name',
            'b.phone as apply_user_phone',
            'a.apply_money',
            'b.openid open_id',
            'b.wx_openid',
            '(select "微信") as apply_style_des',
            'a.status as apply_status_id',
            new Expression("CASE a.status
                    WHEN 1 THEN '待处理'
                    WHEN 2 THEN '已审核'
                    ELSE ''
                    END
                    as apply_status_des
                "),
            'a.create_time apply_create_time',
            'a.id as apply_id'
        ];
        $offset = ($param['current_page'] - 1) * $param['page_size'];
        $result=self::find()->select($select)
            ->from(self::tableName().' as a')
            ->leftJoin('fx_user as b','a.fx_uid=b.uid')
            ->where($where)
            ->orderBy('a.create_time desc')
            ->offset($offset)
            ->limit($param['page_size'])
            ->asArray()
            ->all();
        $count=self::find()->select('count(1) as count')->from(self::tableName().' as a')->leftJoin('fx_user as b','a.fx_uid=b.uid')->where($where)->asArray()->one();
        $count=$count['count'] ;
        return ['list'=>$result,'count'=>$count];
    }

    /*
     * 提现通过，状态变更
     */
    public function applyChange($apply_id){
        $count = self::updateAll(['status'=>2,'update_user'=>AdminUtil::$uid,'auth_time'=>date('Y-m-d H:i:s')], ['and', ['=', 'status', 1], ['=', 'id', $apply_id]]);
        return $count;
    }
}
