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

namespace home\modules\reimbursement\models;

use Yii;
use yii\helpers\Url;
use yii\db\ActiveRecord;
use yii\db\Query;
use common\models\User;
use home\modules\reimbursement\models\Reimbursement;
use home\modules\reimbursement\models\Application;
use common\components\Tool;
use home\models\Announcement;

/**
 * 报销审批表 ({%reimbursement_verify})
 *
 * @property integer $verify_id  ()
 * @property string $link_type  (关联类型)
 * @property integer $link_id  (关联ID)
 * @property integer $verify_user_id  (审核人 关联表qc_user)
 * @property string $remark  (审批记录)
 * @property smallint $status  (审核状态   0待审核   1通过   2否决)
 * @property integer $verify_time  (审核日期)
 *
 * @author Strief http://blog.u-bo.com
 * @since 0.1
 */
class Verify extends ActiveRecord
{

    const STATUS_WAIT = 0; //审核状态:待审核
    const STATUS_ENABLE = 1; //审核状态:通过
    const STATUS_DISABLE = 2; ///审核状态:否决

    /**
    * @inheritdoc
    */
    public static function tableName()
    {
        return '{{%reimbursement_verify}}';
    }
    
    /**
    * @inheritdoc
    */
    public function rules()
    {
        return [
            [['link_type'], 'required'],
            [['link_id', 'verify_user_id', 'status', 'verify_time'], 'integer'],
            [['link_type'], 'string', 'max' => 20],
            [['remark'], 'string', 'max' => 255]
        ];
    }

    /**
    * @inheritdoc
    */
    public function attributeLabels()
    {
        return [
            'verify_id' => 'ID',
            'link_type' => '关联类型',
            'link_id' => '关联ID',
            'verify_user_id' => '审核人',
            'remark' => '审批记录',
            'status' => '审核状态',
            'verify_time' => '审核日期',
        ];
    }

    /**
     * 获取数据
     * 
     * @param  array $map   查询条件
     * @param  array $order 排序方式
     * @param  char  $field 查询字段，默认所有
     */
    public static function getList($map = [], $order = ['verify_time' => SORT_DESC], $field = "*", $column = '')
    {
        $query = static::find()
            ->select($field)
            ->where($map)
            ->with('user')
            ->orderBy($order);
        if (!empty($column)) {
            $query->indexBy($column);
        }
        $List = $query
            ->all();
        return $List;
    }

    /**
     * 关联获取用户信息
     */
    public function getUser()
    {         
        $fields = User::getSafeFields();
        return $this->hasOne(User::className(), ['user_id' => 'verify_user_id'])->select($fields);
    }

    /**
     * 插入更新前置操作
     */
    public function beforeSave($insert)
    {
        if (parent::beforeSave($insert)) {
            //判断是否是插入操作
            if (!isset($this->verify_id)) {
                $this->verify_user_id = Yii::$app->user->id;
            }
            $this->verify_time = time();
            return true;
        } else {
            return false;
        }
    }

    /**
     * 插入更新后置操作
     * 
     */
    public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes);
        //检查审核状态并更新
        self::checkIsverify($this->link_type, $this->link_id, $this->status);
        
        \qcbase\models\ActionLog::insertLog('home','修改',json_encode($changedAttributes));
    }

    /**
     * 检查并更新审核状态
     * 
     * @param char    $type      审核类型(报销或费用申请)
     * @param integer $id        当前审核的ID
     * @param integer $curStatus 当前审核的状态
     */
    public static function checkIsverify($type, $id, $curStatus)
    {
        if($type == 'reim') {
            $list = Reimbursement::findOne(['reim_id' => $id]);
            $model = '{{%reimbursement}}';
            $pk = 'reim_id';
            $text = '报销';
            $url = '/reimbursement/reimbursement/detail';
        } elseif ($type == 'appli') {
            $list = Application::findOne(['appli_id' => $id]);
            $model = '{{%reimbursement_application}}';
            $pk = 'appli_id';
            $text = '申请单';
            $url = '/reimbursement/application/detail';
        }

        //审核消息通知
        if ($curStatus == self::STATUS_ENABLE) {
            $content = Yii::$app->user->identity->realname.'于'.date('Y-m-d H:m:s', time()).'审核<font color="green">通过</font>了你的'.$text.'请求';
        } elseif ($curStatus == self::STATUS_DISABLE) {
            $content = Yii::$app->user->identity->realname.'于'.date('Y-m-d H:m:s', time()).'审核<font color="red">否决</font>了你的'.$text.'请求';
        } else {
            $content = '';
        }

        //检查是否所有的审核人均通过审核
        $verify_ids = explode(',', $list->verify_ids);
        $isverify = 1;
        $status = [0 => 0];
        
        //取出所有审核人对当前审核项的审核状态，如果没有则为待审核状态
        foreach ($verify_ids as $key => $value) {
            //查找出每个审核人最近一次的审核信息
            $verify = static::find()->where(['link_type' => $type, 'link_id' => $id, 'verify_user_id' => $value])->orderBy(['verify_time' => SORT_DESC])->one();
            if (isset($verify)) {
                $status[$key] = $verify->status;
            } else {
                $status[$key] = 0;
            }
        }

        //若有一个否决，则该审核不通过
        if (in_array(self::STATUS_DISABLE, $status)) {
            $list->isverify = self::STATUS_DISABLE;
            $content .= ',该请求审核<font color="red">没有通过</font>';
        } elseif (in_array(self::STATUS_WAIT, $status)) {
            $list->isverify = self::STATUS_WAIT;
        } else {
            $list->isverify = self::STATUS_ENABLE;
            $content .= ',该请求已经全部审核<font color="green">通过</font>';
        }
        $content .= ' <a target="_blank" href="'.Url::to([$url, 'id' => $list->$pk]).'">点击查看</a>';
        Announcement::Send('审核通知', $content, $list->user_id, 3);
        
        $command = Yii::$app->db->createCommand();
        $command->update($model, ['isverify' => $list->isverify], $pk.' = :id', [':id' => $id])->execute();
    }

    /**
     * 审核否决情况下重新提交申请请求后删除原有审核记录
     * 
     * @param  char    $type 审核类型(报销或费用申请)
     * @param  integer $id   当前报销或费用申请的ID
     */
    public static function deleteVerify($type, $id)
    {
        $lists = self::getList(['link_type' => $type, 'link_id' => $id]);
        foreach ($lists as $list) {
            $list->delete();
        }
    }
}
