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

namespace home\modules\receivable\models;

use Yii;
use yii\helpers\Url;
use qcbase\models\Auth;
use home\modules\contract\models\Contract;
use home\modules\customer\models\Customer;
use home\models\Announcement;

/**
 * 回款计划表 ({%receivable_plan})
 *
 * @property integer $plan_id  (ID)
 * @property integer $contract_no  (合同编号(关联表qc_contract))
 * @property string $plan_no  (计划编号)
 * @property integer $plan_time  (计划回款时间)
 * @property decimal $plan_money  (计划回款金额)
 * @property smallint $prompt  (0不提示   1提示)
 * @property string $registrant  (登记人)
 * @property string $remark  (备注)
 * @property smallint $status  (状态：0计划未完成   1计划已完成   99逻辑删除)
 * @property integer $create_time  (登记时间)
 * @property integer $update_time  (最后更新时间)
 * @property integer $user_id  (操作人员ID)
 * @property string $ip  (创建人IP)
 *
 * @author Strief http://blog.u-bo.com
 * @since 0.1
 */
class Plan extends \yii\db\ActiveRecord
{
    const STATUS_ENABLE = 1; //计划已完成
    const STATUS_DISABLE = 0; //计划未完成

    const PROMPT_ENABLE = 1; //提示
    const PROMPT_DISABLE = 0; //不提示

    public $contract_name;  //合同名称
    public $customer_name;  //客户名称
    public $project_name;  //项目名称

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

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['contract_no', 'contract_name', 'plan_no', 'plan_money', 'plan_time'], 'required'],
            [['prompt', 'status', 'update_time', 'user_id'], 'integer'],
            [['plan_money'], 'number', 'max' => 9999999999.99],
            [['plan_no'], 'string', 'max' => 20],
            [['plan_no'], 'unique'],
            [['registrant'], 'string', 'max' => 50],
            [['remark'], 'string', 'max' => 255],
            [['ip'], 'string', 'max' => 15]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'plan_id' => 'ID',
            'contract_no' => '合同名称',
            'plan_no' => '计划编号',
            'plan_time' => '计划回款时间',
            'plan_money' => '计划回款金额(元)',
            'prompt' => '是否提示',
            'registrant' => '登记人',
            'remark' => '备注',
            'status' => '状态',
            'create_time' => '登记时间',
            'update_time' => '最后更新时间',
            'user_id' => '操作人员ID',
            'ip' => '创建人IP',
            'contract_name' => '合同名称',
            'customer_name' => '客户名称',
            'project_name' => '项目名称',
        ];
    }

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

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

    /**
     * 返回计划状态列表 
     */
    public static function getStatusList()
    {
        return [
            self::STATUS_ENABLE => '已完成',
            self::STATUS_DISABLE => '未完成',
        ];
    }

    /**
     * 返回是否提示状态列表 
     */
    public static function getPromptList()
    {
        return [
            self::PROMPT_ENABLE => '提示',
            self::PROMPT_DISABLE => '不提示',
        ];
    }

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

    /**
     * 插入更新前置操作
     */
    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->registrant =  Yii::$app->user->identity->realname;
            }
            $this->update_time = time();
            $this->plan_time = strtotime($this->plan_time);
            return true;
        } else {
            return false;
        }
    }

    /**
     * 权限审核
     * @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 function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes);
        //\common\components\Tool::dump($this);
        //若该回款计划完成并且开启了消息提示则发送系统信息，否则无操作
        if ($this->prompt == self::PROMPT_ENABLE && $this->status == self::STATUS_ENABLE) {
            $contract = Contract::findOne(['contract_no' => $this->contract_no]);
            $content = '你登记的回款计划："' . (empty($contract) ? '':$contract->name) . '" 于' . date('Y-m-d H:m:s', time()) . '<font color="green">完成</font>了 <a href="'.Url::to(['/receivable/plan/detail', 'id' => $this->plan_id]).'">点击查看</a>';
            \home\models\Announcement::Send('回款计划通知', $content, $this->user_id, 2);
        }
    }*/

    /**
     * 回款计划通知(用于每天第一次登陆时调用)
     */
    public static function checkPrompt()
    {
        $user_id = Yii::$app->user->identity->user_id;
        if (!Announcement::equal($user_id, 2)) {
            $planList = static::find()
                ->select('plan_id,plan_no,plan_time')
                ->where([
                    'prompt' => self::PROMPT_ENABLE,
                    'status' => self::STATUS_DISABLE,
                    'user_id' => $user_id
                    ])
                ->orderBy(['plan_time' => SORT_DESC])
                ->indexBy('plan_id')
                ->asArray()
                ->all();
            //\common\components\Tool::dump($planList);
            foreach ($planList as $plan) {
                if ($plan['plan_time'] > time() && $plan['plan_time'] - time() <= 86399) {
                    $content = '你的编号为'.$plan['plan_no'].'的回款计划即将于' . date('Y-m-d', $plan['plan_time']) . '<font color="red">到期</font> <a target="_blank" href="'.Url::to(['/receivable/plan/detail', 'id' => $plan['plan_id']]).'">点击查看</a>';
                    \home\models\Announcement::Send('回款计划通知', $content, $user_id, 2);
                }
            }
        }
    }
}
