<?php
/**
 * @link      http://www.u-bo.com
 * @copyright 南京友博网络科技有限公司 
 * @license   http://www.u-bo.com/license/
 */

namespace home\modules\receivable\models;

use Yii;
use qcbase\models\Auth;
use home\modules\contract\models\Contract;
use home\modules\receivable\models\BillingCategory;

/**
 * 开票记录表 ({%billing_record})
 *
 * @property integer $record_id  (ID)
 * @property integer $contract_no  (合同编号(关联表qc_contract))
 * @property string $invoice_no  (发票号码)
 * @property integer $invoice_time  (发票日期)
 * @property decimal $invoice_money  (发票金额)
 * @property string $invoice_name  (发票项目)
 * @property string $vbrk  (发票抬头)
 * @property string $drawer  (开票人)
 * @property integer $category_id  (开票类别id)
 * @property integer $create_time  (登记时间)
 * @property smallint $status  (状态  99逻辑删除)
 * @property integer $update_time  (更新时间)
 * @property integer $user_id  (创建人ID)
 * @property string $ip  (创建人IP)
 *
 * @author Strief http://blog.u-bo.com
 * @since 0.1
 */
class Billing extends \yii\db\ActiveRecord
{
    public $contract_name;  //合同名称
    public $customer_name;  //客户名称

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

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['contract_no', 'contract_name', 'invoice_no', 'invoice_name', 'invoice_time', 'invoice_money', 'vbrk'], 'required'],
            [['status', 'update_time', 'user_id', 'category_id'], 'integer'],
            [['invoice_money'], 'number', 'max' => 9999999999.99],
            [['invoice_no'], 'string', 'max' => 100],
            [['invoice_no'], 'unique'],
            [['invoice_name', 'vbrk'], 'string', 'max' => 255],
            [['ip'], 'string', 'max' => 15]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'record_id' => 'ID',
            'contract_no' => '合同名称',
            'invoice_no' => '发票号码',
            'invoice_time' => '发票日期',
            'invoice_money' => '发票金额(元)',
            'invoice_name' => '发票项目',
            'vbrk' => '发票抬头',
            'drawer' => '开票人',
            'category_id' => '开票类别',
            'create_time' => '登记时间',
            'status' => '状态',
            'update_time' => '更新时间',
            'user_id' => '创建人ID',
            'ip' => '创建人IP',
            'contract_name' => '合同名称',
            'customer_name' => '客户名称',
        ];
    }

    /**
     * 公共搜索所需信息
     *
     * 这里返回公共搜索的信息，我们希望所有的搜索走统一的配置
     * 返回值里的键名为keywords的数组为搜索里关键字搜索所支持的字段
     */
    public function search()
    {
        return [
            'keywords' => [
                'invoice_no' => '发票号码',
                'invoice_name' => '发票项目',
                'contract_no' => '合同编号',
                'contract_name' => '合同名称',
            ],
        ];
    }

    public static function getNo()
    {
        $prefix = 'FP';
        return $prefix.date('Ymd').mt_rand(1000, 9999);
    }

    /**
     * 关联获取合同信息
     */
    public function getContract()     
    {         
        return $this->hasOne(Contract::className(), ['contract_no' => 'contract_no']);
    }

    /**
     * 关联获取开票类别表信息
     */
    public function getCategory()
    {
        return $this->hasOne(BillingCategory::className(), ['cat_id' => 'category_id']);
    }

    /**
     * 插入更新前置操作
     */
    public function beforeSave($insert)
    {
        if (parent::beforeSave($insert)) {
            //判断是否是插入操作
            if ($this->isNewRecord) {
                $this->user_id =  Yii::$app->user->identity->user_id;
                $this->ip = Yii::$app->getRequest()->getUserIP();
                $this->create_time = time();
                $this->drawer =  Yii::$app->user->identity->realname;
            }
            $this->update_time = time();
            $this->invoice_time = strtotime($this->invoice_time);
            return true;
        } else {
            return false;
        }
    }

    public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes);
        \qcbase\models\ActionLog::insertLog('home','修改',json_encode($changedAttributes));
    }

    /**
     * 权限审核
     * @param  string  $url     操作URL
     * @param  integer $user_id 用户ID
     */
    public static function readAccess($url = null, $user_id = 0)
    {
        if (empty($url)) {
            return false;
        }
        empty($user_id) ? $user_id = \Yii::$app->user->id : $user_id;
        //非超级管理员，需要检测权限
        if (Yii::$app->session->get('isSuperAdmin')) {
            return true;
        }
        //检测是否具有某一特定权限
        if (Auth::checkAccess($url, $user_id)) {
            return true;
        }
        return false;
    }

    /**
    * 获取当前合同的所有开票记录
    */
    public static function getContractBilling($contract_no)
    {
        $list = static::find()
                    ->select('invoice_time, invoice_money')
                    ->where(['contract_no' => $contract_no, 'status' => 1])
                    ->asArray()
                    ->all();
        return $list;
    }

    /**
    * 获取当前合同的未开发票金额
    */
    public static function getContractMoney($contract_no)
    {
        $getMoney = static::find()
            ->where(['contract_no' => $contract_no, 'status' => 1])
            ->sum('invoice_money');
        $allMoney = Contract::find()
            ->select('money')
            ->where(['contract_no' => $contract_no, 'status' => 1])
            ->asArray()
            ->one();
        $surplusMoney = $allMoney['money'] - $getMoney;
        return $surplusMoney;
    }


}
