<?php

namespace backend\models;

use common\helpers\Utils;
use Yii;

/**
 * This is the model class for table "crm_remit_log".
 *
 * @property integer $id
 * @property integer $remit_no
 * @property string $memo
 * @property integer $admin_id
 * @property string $admin_name
 * @property string $admin_ip
 * @property integer $create_time
 */
class RemitLog extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'crm_remit_log';
    }

    /**
     * @return \yii\db\Connection the database connection used by this AR class.
     */
    public static function getDb()
    {
        return Yii::$app->get('dbXcrm');
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['remit_no', 'create_time'], 'required'],
            [['remit_no', 'admin_id', 'create_time'], 'integer'],
            [['memo'], 'string', 'max' => 255],
            [['admin_name', 'admin_ip'], 'string', 'max' => 32],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'remit_no' => '打款单号',
            'memo' => '备注',
            'admin_id' => '审核人id',
            'admin_name' => '审核人名字',
            'admin_ip' => '审核人ip',
            'create_time' => '创建时间',
        ];
    }

    /**
     * @param array $remitOrder
     * @param array $logData
     * @return mixed
     */
    public static function addLog($remitOrder, $logData = [])
    {
        $model = new static();
        $model->remit_no = $remitOrder['remit_no'];
        isset($logData['admin_id']) && $model->admin_id = trim($logData['admin_id']);
        isset($logData['admin_name']) && $model->admin_name = trim($logData['admin_name']);
        $model->admin_ip = isset($logData['admin_ip']) ? trim($logData['admin_ip']) : Utils::getClientIp();
        isset($logData['memo']) && $model->memo = trim($logData['memo']);
        $model->create_time = time();
        return $model->save();
    }
    
    /**
     * 列表数据
     * @param array $post
     * @return array
     */
    public function getList($post)
    {
        $result = ['code' => 0, 'data' => [], 'message' => ''];
        
        $remit_no = isset($post['remit_no']) ? $post['remit_no'] : '';
        if (!$remit_no) {
            $result['message'] = '参数错误';
            return $result;
        }

        $query = static::find();
        $list = $query->alias('rl')
            ->select('rl.*')
            ->innerJoin(RemitOrder::tableName() . ' ro', 'rl.remit_no = ro.remit_no')
            ->where(['rl.remit_no' => $remit_no])
            ->orderBy(['rl.id' => SORT_ASC])
            ->all();
        
        $result['code'] = 1;
        $result['data'] = $list;

        return $result;
    }
}



