<?php

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

namespace home\modules\statement\models;

use Yii;
use home\modules\contract\models\Contract;
use common\models\User;
use home\modules\receivable\models\Receivable;
use yii\web\ForbiddenHttpException;

/**
 * This is the model class for table "qc_statement_link_contract".
 * 
 * 进账单关联合同信息
 *
 * @property integer $id (ID)
 * @property integer $statement_id (进账单ID)
 * @property string $contract_no (关联合同编号)
 * @property decimal $money (关联金额)
 * @property string $remark (备注)
 * @property integer $create_time (关联时间)
 * @property integer $user_id (提交人)
 * @property string $ip (IP)
 * @property integer $rece_id (回款ID)
 *
 * @author HuLimin http://blog.u-bo.com
 * @since 0.1
 */
class StatementLinkContract extends \yii\db\ActiveRecord
{

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

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['statement_id', 'create_time', 'user_id', 'rece_id'], 'integer'],
            [['money'], 'number'],
            [['contract_no'], 'string', 'max' => 100],
            [['remark'], 'string', 'max' => 255],
            [['ip'], 'string', 'max' => 15]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'statement_id' => '进账单ID',
            'contract_no' => '关联合同编号',
            'money' => '关联金额(元)',
            'remark' => '备注',
            'create_time' => '关联时间',
            'user_id' => '提交人',
            'ip' => 'IP',
            'rece_id' => '回款ID'
        ];
    }

    /**
     * 保存前置操作，修改关联合同金额的时候总关联金额不得大于账单总额。有回款记录关联的修改记录，无回款记录则新建
     */
    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($this->money <= 0){
                throw new ForbiddenHttpException('关联金额必须大于0！');
                return false;
            }
            $statementInfo = StatementAccount::findOne($this->statement_id);
            //剩余金额
            $surplusMoney = max([$statementInfo->account_debit, $statementInfo->account_credit]) - $statementInfo->allocateAmount - $this->money;
            if(isset($this->oldAttributes['money'])){
                $surplusMoney+=$this->oldAttributes['money'];
            }
            if($surplusMoney < 0){
                throw new ForbiddenHttpException('未分配金额不足！');
                return false;
            }
            $reveInfo = Receivable::findOne($this->rece_id);
            if(empty($reveInfo)){
                if(self::createLink(['statement_id' => $this->statement_id, 'contract_no' => $this->contract_no, 'money' => $this->money]) == false){
                    return false;
                }
            } else {
                $reveInfo->rece_money = $this->money;
                $reveInfo->to_date = date('Y-m-d', $statementInfo->payment_time);
                $reveInfo->contract_name = $this->contract_no;
                if(!$reveInfo->save()){
                    $firstError = reset($reveInfo->getFirstErrors());
                    throw new ForbiddenHttpException($firstError);
                    return false;
                }
            }
            return true;
        }
    }

    /**
     * 删除前置操作，删除关联回款记录
     */
    public function beforeDelete()
    {
        if(parent::beforeDelete()){
            $receInfo = Receivable::findOne($this->rece_id);
            if($this->rece_id && !empty($receInfo)){
                $result = Receivable::deleteAll(['rece_id' => $this->rece_id]);
                return $result;
            }
            return true;
        }
    }

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

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

    /**
     * 创建关联
     * @param type $data
     * @return boolean
     */
    public static function createLink($data)
    {
        if(empty($data)){
            return false;
        }
        $model = new StatementLinkContract();
        $model->statement_id = $data['statement_id'];
        $model->contract_no = $data['contract_no'];
        $model->money = $data['money'];
        isset($data['remark']) && $model->remark = $data['remark'];
        $result = static::createReceivable($data);
        if($result !== false){
            $model->rece_id = $result;
            $model->save();
        } else {
            return false;
        }
        return true;
    }

    /**
     * 获取关联合同信息
     * @param type $map 查询条件
     * @param type $order 排序
     */
    public static function getLinkContracts($map = [], $order = ['create_time' => SORT_DESC])
    {
        if(empty($map)){
            return;
        }
        $query = static::find()
                ->where($map)
                ->orderBy($order)
                ->all();
        return $query;
    }

    /**
     * 创建回款记录
     * @param type $data 关联数据
     */
    public static function createReceivable($data)
    {
        if(empty($data) || !isset($data['statement_id'])){
            return false;
        }
        $statementInfo = StatementAccount::findOne($data['statement_id']);
        if(empty($statementInfo)){
            return false;
        }
        $model = new Receivable();
        $model->rece_no = Receivable::getNo();
        $model->contract_no = $data['contract_no'];
        $model->rece_money = $data['money'];
        $model->rece_bank = $statementInfo->remittance_bank;
        $model->contract_name = Contract::getContractItemByContractNo($data['contract_no'])->name;

        $model->rece_account = $statementInfo->remittance_no;
        $model->receiving_bank = $statementInfo->bank_id;
        $model->receiving_account = $statementInfo->account_no;
        $model->method_id = $statementInfo->type;
        $model->to_date = date('Y-m-d', $statementInfo->payment_time);
        isset($data['remark']) && $model->remark = $data['remark'];
        $model->save();
        if($model->rece_id){
            return $model->rece_id;
        }
    }

    /**
     * 删除合同关联
     * @param type $rece_id 回款记录ID
     */
    public static function deleteByReceId($rece_id = 0)
    {
        if(empty($rece_id)){
            return false;
        }
        $model = static::findOne(['rece_id' => $rece_id]);
        if(empty($model)){
            return false;
        }
        return $model->deleteAll(['rece_id' => $rece_id]);
    }

}
