<?php

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

namespace home\modules\statement\models;

use Yii;
use common\models\User;
use home\modules\receivable\models\Bank;
use home\modules\customer\models\Customer;
use home\modules\contract\models\Contract;
use home\modules\statement\models\StatementLinkContract;

/**
 * This is the model class for table "qc_statement_account".
 *
 * 财务对账单
 *
 * @property integer $statement_id  (账单ID)
 * @property integer $bank_id  (收款银行ID)
 * @property string $bank_name  (收款银行名称)
 * @property string $account_no  (银行账号)
 * @property string $remittance_user  (对方户名)
 * @property string $remittance_bank  (对方银行)
 * @property string $remittance_no  (对方账号)
 * @property decimal $account_debit  (借方金额)
 * @property decimal $account_credit  (贷方金额)
 * @property string $serial_number  (银行流水号)
 * @property smallint $type  (账单类型 1电子账单 2现金账单)
 * @property integer $payment_time  (付款日期)
 * @property integer $create_time  (创建时间)
 * @property integer $update_time  (更新时间)
 * @property integer $user_id  (创建人id)
 * @property string $ip  (创建人ip)
 * @property string $remark  (备注摘要)
 *
 * @author HuLimin http://blog.u-bo.com
 * @since 0.1
 */
class StatementAccount extends \yii\db\ActiveRecord
{

    const TYPE_ELECTRONIC = 1; //电子账单
    const TYPE_CASH = 2; //现金账单

    public function init()
    {
        parent::init();
        $this->type = 2; //默认现金
        $this->payment_time = date('Y-m-d'); //默认当前时间
    }

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

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['type', 'payment_time'], 'required'],
            [['bank_id', 'type', 'create_time', 'update_time', 'user_id'], 'integer'],
            [['account_debit', 'account_credit'], 'number'],
            [['account_debit', 'account_credit'], 'default', 'value' => 0],
            [['update_time'], 'default', 'value' => time()],
            [['payment_time'], 'date', 'format' => 'php:Y-m-d'],
            [['bank_name', 'account_no', 'remittance_user', 'remittance_bank', 'remittance_no', 'serial_number', 'remark'], 'trim'],
            [['bank_name', 'account_no', 'remittance_user', 'remittance_bank', 'remittance_no', 'serial_number'], 'string', 'max' => 100],
            [['serial_number'], 'unique'],
            [['ip', 'payment_time'], 'string', 'max' => 15],
            [['remark'], 'string', 'max' => 255]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'statement_id' => '账单ID',
            'bank_id' => '收款银行',
            'bank_name' => '收款银行名称',
            'account_no' => '银行账号',
            'remittance_user' => '对方户名',
            'remittance_bank' => '对方银行',
            'remittance_no' => '对方账号',
            'account_debit' => '借方金额(元)',
            'account_credit' => '贷方金额(元)',
            'serial_number' => '银行流水号',
            'type' => '账单类型', //1电子账单 2现金账单
            'payment_time' => '付款日期',
            'create_time' => '创建时间',
            'update_time' => '更新时间',
            'user_id' => '创建人id',
            'ip' => '创建人ip',
            'remark' => '摘要'
        ];
    }

    /**
     * 公共搜索所需信息
     *
     * 这里返回公共搜索的信息，我们希望所有的搜索走统一的配置
     * 返回值里的键名为keywords的数组为搜索里关键字搜索所支持的字段
     */
    public function search()
    {
        return [
            'keywords' => [
                'remark' => '摘要'
            ],
        ];
    }

    public function beforeSave($insert)
    {
        if(parent::beforeSave($insert)){
            if($insert){
                $this->user_id = Yii::$app->user->identity->user_id;
                $this->ip = Yii::$app->getRequest()->getUserIP();
                $this->create_time = time();
            }
            if(!is_int($this->payment_time)){
                $this->payment_time = empty($this->payment_time) ? time() : strtotime($this->payment_time);
            }
            $this->bank_name = !empty($this->bank_id) ? Bank::findOne($this->bank_id)['name'] : '';
            return true;
        }
    }

    /**
     * 返回类型列表
     */
    public static function getTypeList()
    {
        return [
            self::TYPE_CASH => '现金账单',
            self::TYPE_ELECTRONIC => '电子账单'
        ];
    }

    /**
     * 获取创建人的姓名
     */
    public function getUser()
    {
        $fields = User::getSafeFields();
        return $this->hasOne(User::className(), ['user_id' => 'user_id'])->select($fields);
    }

    /**
     * 获取关联客户信息
     */
    public function getStatementLink()
    {
        return $this->hasOne(StatementLink::className(), ['statement_id' => 'statement_id']);
    }

    /**
     * 获取关联客户信息
     */
    public function getCustomer()
    {
        return $this->hasOne(Customer::className(), ['customer_no' => 'link_id'])
                        ->via('statementLink');
    }

    /**
     * 获取关联客户信息
     */
    public function getCustomerContract()
    {
        return $this->hasMany(Contract::className(), ['customer_no' => 'link_id'])
                        ->orderBy(['signing_time' => SORT_DESC])
                        ->via('statementLink');
    }

    /**
     * 获取关联合同 
     * @param type $statement_id 进账ID
     */
    public static function getContracts($statement_id)
    {
        if(!empty($statement_id)){
            $linkCustomer = StatementLink::findOne(['statement_id' => $statement_id, 'link_type' => 'customer']);
            $linkContracts = StatementLinkContract::find()
                    ->where(['statement_id' => $statement_id])
                    ->select('contract_no')
                    ->column();
            $contracts = Contract::find()->where(['customer_no' => $linkCustomer->link_id]);
            if(!empty($linkContracts)){
                $contracts = $contracts->andWhere(['not in', 'contract_no', $linkContracts]);
            }
            $contracts = $contracts->orderBy(['signing_time' => SORT_DESC])->all();
            if(!empty($contracts)){
                return $contracts;
            }
        }
        return;
    }

    /**
     * 获取关联合同No
     */
    public function getStatementLinkContract()
    {
        return $this->hasMany(StatementLinkContract::className(), ['statement_id' => 'statement_id']);
    }

    /**
     * 获取一条关联合同
     * @param type $contract_no 合同编号
     */
    public function getLinkContractItem($contract_no)
    {
        return $this->hasOne(StatementLinkContract::className(), ['statement_id' => 'statement_id', 'contract_no' => $contract_no]);
    }

    /**
     * 关联获取已分配数量
     */
    public function getAllocateAmount()
    {
        return $this->hasMany(StatementLinkContract::className(), ['statement_id' => 'statement_id'])->sum('money');
    }

    /**
     * 关联获取已分配总额
     */
    public static function getTotalAmount()
    {
        $allocateAmount = StatementLinkContract::find()->sum('money'); //已经分配金额
        $totalAdebit = static::find()->sum('account_debit'); //借方总金额
        $totalCredit = static::find()->sum('account_credit'); //贷方总金额
        return $totalAdebit + $totalCredit - $allocateAmount;
    }

}
