<?php

namespace common\models;

use common\util\Util;
use Yii;
use yii\db\Expression;

/**
 * This is the model class for table "fx_commission_info".
 *
 * @property integer $id
 * @property integer $fx_uid
 * @property string $total_money
 * @property integer $order_id
 * @property integer $status
 * @property integer $delete_flag
 * @property string $create_time
 * @property string $update_time
 * @property string $update_user
 */
class FxCommissionInfo extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'fx_commission_info';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['fx_uid', 'total_money', 'order_id'], 'required'],
            [['fx_uid', 'order_id', 'status', 'delete_flag'], 'integer'],
            [['total_money'], 'number'],
            [['create_time', 'update_time'], 'safe'],
            [['update_user'], 'string', 'max' => 50],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'fx_uid' => 'Fx Uid',
            'total_money' => 'Total Money',
            'order_id' => 'Order ID',
            'status' => 'Status',
            'delete_flag' => 'Delete Flag',
            'create_time' => 'Create Time',
            'update_time' => 'Update Time',
            'update_user' => 'Update User',
        ];
    }

    public function finishCommission()
    {
        $cnt = 0;
        $count = 0;
        //1.找出今天-完成日期大于3天的订单号,且佣金待结算
        $LogOrder = self::find()->select(['GROUP_CONCAT(a.order_id) as order_arr'])
            ->from('order_main as a')
            ->leftJoin('fx_commission_info as b', 'a.order_id=b.order_id')
            ->where(['and', ['=', 'order_status', 3], ['>', 'DATEDIFF(current_date,end_date)', 2], ['=', 'a.delete_flag', 0], ['=', 'b.`status`', 1]])
            ->asArray()
            ->all();
        $uptOrder = explode(',', $LogOrder[0]['order_arr']);
        if (empty($uptOrder['0']) == false) {
            //2.佣金表待结算变已结算
            $count = self::updateAll(['status' => 2], ['and', ['=', 'status', 1], ['in', 'order_id', $uptOrder]]);
            //3.不同用户的账户表分别更新
            //查出需要更新的分销账户及佣金金额
            $fx_user = self::find()->select(['fx_uid', 'SUM(total_money) as money'])
                ->from(self::tableName())
                ->where(['and', ['in', 'order_id', $uptOrder], ['=', 'delete_flag', 0]])
                ->groupBy('fx_uid')
                ->asArray()
                ->all();
            if (count($fx_user) != 0) {
                $fx_user_account = new FxUserAccount();
                foreach ($fx_user as $val) {
                    $available_commission = $val['money'];
                    $fx_uid = $val['fx_uid'];
                    $array = ['available_commission' => new Expression("available_commission +$available_commission"), 'total_commission' => new Expression("total_commission +$available_commission")];
                    $cnt += $fx_user_account::updateAll($array, ['and', ['=', 'fx_uid', $fx_uid]]);
                }
            }
            foreach ($uptOrder as $val) {
                Util::interfaceZzcx(['type' => 3, 'order_id' => $val], '/zzcx/interfaces/order/send-wx-msg', 1);
            }
            Util::addOrderLog(0, 0, implode('-', $uptOrder), '佣金结算', 7);

        }
        return ['order_list' => $LogOrder[0]['order_arr'], 'count' => $count, 'cnt' => $cnt];
    }

    /**
     * Function Description:佣金明细
     * Function Name: getInfoAdmin
     * @param $order_id
     *
     * @return array|\yii\db\ActiveRecord[]
     *
     * @author 娄梦宁
     */
    public function getInfoAdmin($order_id)
    {
        $result = self::find()
            ->from('order_info a')
            ->innerJoin('order_main c', 'a.order_id = c.order_id')
            ->leftJoin('prod_main b', 'a.prod_id=b.prod_id')
            ->select(['b.prod_name', 'a.unit_price prod_single_price', 'a.count prod_count', 'a.commission'  // update fuhc add b.commission on 2017-05-26
//                '(select TRUNCATE(total_money/c.prod_cnt,0)*a.count  from fx_commission_info where order_id =a.order_id ) as commission'
            ])
            ->where(['and', ['=', 'a.order_id', $order_id], ['!=', 'a.count', 0]])
            ->asArray()
            ->all();
        return $result;
    }

    /**
     * Des:根据订单ID获取佣金详细
     * Name: getInfoByOrderId
     * @param $oder_id
     * @return array
     * @author 倪宗锋
     */
    public function getInfoByOrderId($oder_id)
    {
        $orderInfo = self::find()
            ->from(static::tableName())
            ->where(['=', 'order_id', $oder_id])
            ->asArray()
            ->one();
        return $orderInfo;
    }

    /**
     * Des:修改单状态
     * Name: editStatus
     * @param $oder_id
     * @param $status
     * @return int
     * @author 倪宗锋
     */
    public function editStatus($oder_id, $status)
    {
        $flag = self::updateAll(['status' => $status], ['=', 'order_id', $oder_id]);
        return $flag;
    }
}
