<?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "prod_main".
 *
 * @property integer $prod_id
 * @property integer $prod_cate_id
 * @property string $prod_name
 * @property string $prod_price
 * @property string $create_user
 * @property string $create_time
 * @property string $update_time
 * @property integer $delete_flag
 * @property string $update_user
 * @property string $bus_id
 */
class ProdMain extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'prod_main';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['prod_cate_id', 'prod_price'], 'required'],
            [['prod_cate_id', 'delete_flag'], 'integer'],
            [['prod_price', 'commission'], 'number'],
            [['create_time', 'update_time'], 'safe'],
            [['prod_name'], 'string', 'max' => 100],
            [['create_user', 'update_user'], 'string', 'max' => 50],
            [['bus_id'], 'string', 'max' => 255],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'prod_id' => 'Prod ID',
            'prod_cate_id' => 'Prod Cate ID',
            'prod_name' => 'Prod Name',
            'prod_price' => 'Prod Price',
            'create_user' => 'Create User',
            'create_time' => 'Create Time',
            'update_time' => 'Update Time',
            'delete_flag' => 'Delete Flag',
            'update_user' => 'Update User',
            'bus_id' => 'Bus ID',
        ];
    }

    /**
     * Function Description:产品详情获取子产品数组
     * Function Name: getProdArr
     * @param $pro_cate_id
     *
     * @return array|null|\yii\db\ActiveRecord
     *
     * @author 娄梦宁
     */
    public function getProdArr($pro_cate_id)
    {
        $result = self::find()->select(['prod_name', 'prod_price', 'prod_id', 'bus_id', '(select 100) as prod_count', 'commission'])
            ->from(self::tableName())
            ->where(['and', ['=', 'prod_cate_id', $pro_cate_id], ['=', 'delete_flag', 0]])
            ->asArray()
            ->all();
        if (empty($result['0'])) {
            return [];
        } else {
            foreach ($result as &$v) {
                $v['prod_price'] = $this->dealFloat($v['prod_price']);
            }
        }
        return $result;
    }

    /**
     * Des:获取订单总价格
     * Name: getTotalMoney
     * @param $params array  多为数组  产品ID和数量
     * @return array
     * @author 倪宗锋
     */
    public function getTotalMoney($params)
    {
        $prod_id = [];
        $sqlCase = '';
        foreach ($params as $val) {
            $sqlCase .= " WHEN {$val['prod_id']} THEN prod_price*{$val['prod_count']} ";
            $prod_id[] = $val['prod_id'];
        }
        $prodId = implode(',', $prod_id);

        $sql = '' . "SELECT
        SUM(CASE prod_id
        {$sqlCase}
        ELSE 0
        END)
        from prod_main
        where prod_id in ({$prodId})
    ";
        $result = Yii::$app->db->createCommand($sql)->queryScalar();
        return $result;
    }

    /**
     * Function Description:获取票种id
     * Function Name: getTicketId
     * @param $pro_cate_id
     *
     * @return array|null|\yii\db\ActiveRecord
     *
     * @author 娄梦宁
     */
    public function getTicketId($pro_cate_id)
    {
        $where = ['and'];
        $where[] = ['=', 'prod_cate_id', $pro_cate_id];
        $where[] = ['=', 'delete_flag', 0];
        $result = self::find()->select(['bus_id', 'prod_price', 'prod_id', 'prod_name'])
            ->from(self::tableName())
            ->where($where)
            ->orderBy('prod_id')
            ->asArray()
            ->all();
        return $result;
    }

    /**
     * Function Description:查询起始站点
     * Function Name: getStation
     * @param $prod_id
     *
     * @return mixed
     *
     * @author 娄梦宁
     */
    public function getStation($prod_id)
    {
        $result = self::find()->select(["concat(start_res_name,' - ',end_res_name) as station_str"])
            ->from(self::tableName() . ' as a')
            ->leftJoin('bus_ticket as b', 'a.bus_id=b.ticket_id')
            ->where(['a.prod_id' => $prod_id])
            ->asArray()
            ->one();
        return $result['station_str'];
    }

    /**
     * Function Description:子产品表添加（只能添加非巴士产品）
     * Function Name: addProdMain
     * @param $param
     *
     * @return bool
     *
     * @author 娄梦宁
     */
    public function addProdMain($param)
    {
        $transaction = Yii::$app->db->beginTransaction();
        if ($param['category_id'] != 1) {
            foreach ($param['price_type'] as $val) {
                $values = [
                    'prod_cate_id' => $param['prod_cate_id'],
                    'prod_name' => $val['price_type_name'],
                    'prod_price' => $val['price_type_price'],
                    'create_time' => date('Y-m-d H:i:s'),
                ];
                $prod_main = clone $this;
                $prod_main->attributes = $values;
                $res = $prod_main->insert();
                if (!$res) {
                    $transaction->rollBack();
                    return false;
                }
            }
        }
        $transaction->commit();
        return true;
    }

    /*
     * 修改子产品表
     */
    public function uptCmsProd($prod_arr, $pro_cate_id)
    {
        if ($prod_arr['prod_id'] == 0) {
            $value = [
                'prod_name' => $prod_arr['price_type_name'],
                'prod_price' => $prod_arr['price_type_price'],
                'prod_cate_id' => $pro_cate_id,
                'create_time' => date('Y-m-d H:i:s')
            ];
            $this->attributes = $value;
            $res = $this->insert();
            if (!$res) {
                return false;
            }
        } else {
            $count = self::updateAll(['prod_name' => $prod_arr['price_type_name'], 'prod_price' => $prod_arr['price_type_price']], ['=', 'prod_id', $prod_arr['prod_id']]);
            if ($count === false) {
                return false;
            }
        }
        return true;
    }

    /*
     * 获取产品的子产品数组
     */
    public function getIdArr($pro_cate_id)
    {
        $arr = self::find()->select('prod_id')->from(self::tableName())->where(['prod_cate_id' => $pro_cate_id])->indexBy('prod_id')->asArray()->all();
        return $arr;
    }

    public function delCount($prod_id)
    {
        $count = self::updateAll(['delete_flag' => 1], ['=', 'prod_id', $prod_id]);
        return $count;
    }


    /*
    * Des:设置产品佣金 (根据prod_cate_id)
    * Name: setProdCommissionByCateId
    * @param $param
    * @return int
    * @author 付泓程
    */
    public function setProdCommissionByCateId($param)
    {
        $commission = $param['commission'];
        $prod_cate_id = $param['prod_cate_id'];
        $count = $this->updateAll(['commission' => $commission], ['and', ['=', 'prod_cate_id', $prod_cate_id], ['=', 'delete_flag', '0']]);
        return $count;
    }

    /*
    * Des:设置产品佣金 (根据prod_id)
    * Name: setProdCommissionByProdId
    * @param $param
    * @return int
    * @author 付泓程
    */
    public function setProdCommissionByProdId($param)
    {
        $commission = $param['commission'];
        $prod_id = $param['prod_id'];
        $count = $this->updateAll(['commission' => $commission], ['and', ['=', 'prod_id', $prod_id], ['=', 'delete_flag', '0']]);
        return $count;
    }

    /**
     * Function Description:处理价格
     * Function Name: dealFloat
     * @param $float
     *
     * @return float
     *
     * @author LUOCJ
     */
    public function dealFloat($float)
    {
        $int = floor($float);
        if ($float - $int == 0) {
            $float = $int;
        }
        return $float;
    }
}
