<?php

namespace common\models;

use common\helpers\user\Info;
use Yii;

/**
 * This is the model class for table "{{%RECHARGE}}".
 *
 * @property string $ID
 * @property string $SN 单号
 * @property string $USER_ID 会员ID
 * @property string $ID_CARD 身份证号
 * @property int $RECHARGE_PERIOD_NUM 充值期数
 * @property int $RECHARGE_YEAR 充值年份
 * @property int $RECHARGE_MONTH 充值月份
 * @property string $AMOUNT 充值金额
 * @property string $REAL_NAME 会员姓名
 * @property string $OPEN_BANK 开户行
 * @property string $BANK_ADDRESS 开户支行
 * @property string $BANK_NO 银行账号
 * @property int $BANK_PROVINCE 银行省份
 * @property int $BANK_CITY 银行城市
 * @property int $BANK_COUNTY 银行地区
 * @property string $BANK_PROVE 打款凭证
 * @property string $P_MONTH 表分区标识
 * @property int $AUDIT_STATUS 审核状态
 * @property string $REMARK 审核备注
 * @property string $AUDIT_ADMIN 审核管理员
 * @property int $CREATED_AT 创建时间
 * @property int $AUDITED_AT 审核时间
 */
class Recharge extends \common\components\ActiveRecord {
    const TYPE_MANUAL = 0;      // 手动充值
    const TYPE_AUTO = 1;        // 自动充值
    const TYPE_ADMIN = 2;       // 后台管理员


    const STATUS_APPLIED = 0;       // 已申请
    const STATUS_PROVED = 1;       // 已上传凭证
    const STATUS_AUDITED = 2;       // 已审核
    const STATUS_REFUSED = 3;       // 已拒绝

    const STATUS_NAME = [
        self::STATUS_APPLIED => '待审核',
        self::STATUS_PROVED => '已上传凭证',
        self::STATUS_AUDITED => '已审核',
        self::STATUS_REFUSED => '已拒绝',
    ];

    /**
     * @inheritdoc
     */
    public static function tableName() {
        return '{{%RECHARGE}}';
    }

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['USER_ID', 'P_MONTH', 'CREATED_AT'], 'required'],
            [['RECHARGE_PERIOD_NUM', 'RECHARGE_YEAR', 'RECHARGE_MONTH', 'AUDIT_STATUS', 'CREATED_AT', 'AUDITED_AT', 'BANK_PROVINCE', 'BANK_CITY', 'BANK_COUNTY'], 'integer'],
            [['AMOUNT'], 'number'],
            [['ID', 'SN', 'USER_ID', 'OPEN_BANK', 'BANK_NO', 'AUDIT_ADMIN'], 'string', 'max' => 32],
            [['ID_CARD'], 'string', 'max' => 20],
            [['REAL_NAME', 'BANK_ADDRESS'], 'string', 'max' => 255],
            [['REMARK'], 'string', 'max' => 4000],
            [['ID'], 'unique'],
            [['SN'], 'unique'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'ID' => 'ID',
            'SN' => '单号',
            'USER_ID' => '会员ID',
            'ID_CARD' => '身份证号',
            'RECHARGE_PERIOD_NUM' => '充值期数',
            'RECHARGE_YEAR' => '充值年份',
            'RECHARGE_MONTH' => '充值月份',
            'AMOUNT' => '充值金额',
            'REAL_NAME' => '会员姓名',
            'OPEN_BANK' => '汇款银行',
            'BANK_ADDRESS' => '开户支行',
            'BANK_NO' => '汇款账号',
            'BANK_PROVINCE' => '银行省份',
            'BANK_CITY' => '银行城市',
            'BANK_COUNTY' => '银行地区',
            'BANK_PROVE' => '打款凭证',
            'P_MONTH' => '表分区标识',
            'AUDIT_STATUS' => '审核状态',
            'REMARK' => '备注',
            'AUDIT_ADMIN' => '审核管理员',
            'CREATED_AT' => '创建时间',
            'AUDITED_AT' => '审核时间',
        ];
    }

    /**
     * 获取充值相关期数，目前按照直接取当月第一期来实现
     * @param $nowTime
     * @return array
     */
    public static function getPeriod($nowTime) {
        $period = Period::instance();
        $year = $period->getNowYear();
        $month = $period->getNowMonth();
        $yearMonth = $period->getNowYearMonth();
        $thisMonth = Period::getPeriodNumRangeFromMonth($year, $month);
        $period->setPeriodNum($thisMonth['min']);
        $endTime = $period->getNowPeriodEnd();
        return ['nowPeriodNum' => $thisMonth['min'], 'nowYear' => $year, 'nowMonth' => $month, 'yearMonth'=>$yearMonth, 'endTime' => $endTime];
    }

    /**
     * 会员本月是否充值
     * @param $uid
     * @return bool
     */
    public static function hasThisMonthRecharge($uid) {
        $period = Period::instance();
        $idCard = Info::getIdCardByUserId($uid);
        if ($idCard) {
            if (static::find()->where('ID_CARD=:ID_CARD AND RECHARGE_YEAR=:RECHARGE_YEAR AND RECHARGE_MONTH=:RECHARGE_MONTH', [':ID_CARD' => $idCard, ':RECHARGE_YEAR' => $period->getNowYear(), ':RECHARGE_MONTH' => $period->getNowMonth()])->exists()) {
                return true;
            }
        } else {
            if (static::find()->where('USER_ID=:USER_ID AND RECHARGE_YEAR=:RECHARGE_YEAR AND RECHARGE_MONTH=:RECHARGE_MONTH', [':USER_ID' => $uid, ':RECHARGE_YEAR' => $period->getNowYear(), ':RECHARGE_MONTH' => $period->getNowMonth()])->exists()) {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断充值状态
     * @param $sn
     * @param $nowStatus
     * @param $toStatus
     * @return string
     */
    public static function chkAuditStatus($sn, $nowStatus, $toStatus) {
        $statusName = self::STATUS_NAME;
        $msg = '充值单' . $sn . '当前状态为【' . $statusName[$nowStatus] . '】，无法设置为【' . $statusName[$toStatus] . '】';
        switch ($toStatus) {
            //已审核
            case Recharge::STATUS_AUDITED:
                if (($nowStatus == Recharge::STATUS_APPLIED) || ($nowStatus == Recharge::STATUS_PROVED)) {
                    $msg = '';
                }
                break;
            //审核拒绝
            case Recharge::STATUS_REFUSED:
                if (($nowStatus == Recharge::STATUS_APPLIED) || ($nowStatus == Recharge::STATUS_PROVED)) {
                    $msg = '';
                }
                break;
            default:
        }
        return $msg;
    }

    /**
     * 按充值状态返回总和
     * @param $userId
     * @param int $type
     * @return mixed
     */
    public static function getRechargeTotal($userId, $type = self::STATUS_AUDITED) {
        $total = self::find()->where('USER_ID=:USER_ID AND AUDIT_STATUS=:AUDIT_STATUS', [':USER_ID' => $userId, ':AUDIT_STATUS' => $type])->sum('AMOUNT');
        return $total ? $total : '0.00';
    }

    /**
     * 按充值状态返回所有会员总和
     * @param int $type
     * @return mixed
     */
    public static function getAllRechargeTotal($type = self::STATUS_AUDITED) {
        $total = self::find()->where('AUDIT_STATUS=:AUDIT_STATUS', [':AUDIT_STATUS' => $type])->sum('AMOUNT');
        return $total ? $total : '0.00';
    }

}
