<?php

namespace common\models;

use Yii;
use yii\db\Exception;
use yii\db\Expression;

/**
 * This is the model class for table "bus_ticket".
 *
 * @property integer $ticket_id
 * @property integer $start_area_id
 * @property string $start_area_name
 * @property integer $end_area_id
 * @property string $end_area_name
 * @property integer $start_res_id
 * @property string $start_res_name
 * @property integer $end_res_id
 * @property string $end_res_name
 * @property integer $line_id
 * @property integer $line_type
 * @property string $prod_price
 * @property string $line_name
 */
class BusTicket extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'bus_ticket';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['ticket_id'], 'required'],
            [['ticket_id', 'start_area_id', 'end_area_id', 'start_res_id', 'end_res_id', 'line_id', 'line_type'], 'integer'],
            [['prod_price', 'start_res_longitude', 'start_res_latitude', 'end_res_longitude', 'end_res_latitude'], 'number'],
            [['start_area_name', 'end_area_name', 'start_res_name', 'end_res_name'], 'string', 'max' => 50],
            [['line_name'], 'string', 'max' => 255],
            [['ticket_id'], 'unique'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'ticket_id' => 'Ticket ID',
            'start_area_id' => 'Start Area ID',
            'start_area_name' => 'Start Area Name',
            'end_area_id' => 'End Area ID',
            'end_area_name' => 'End Area Name',
            'start_res_id' => 'Start Res ID',
            'start_res_name' => 'Start Res Name',
            'end_res_id' => 'End Res ID',
            'end_res_name' => 'End Res Name',
            'line_id' => 'Line ID',
            'line_type' => 'Line Type',
            'prod_price' => 'Prod Price',
            'line_name' => 'Line Name',
            'start_LONGITUDE' => 'start_LONGITUDE',
            'start_LATITUDE' => 'start_LATITUDE',
            'end_LONGITUDE' => 'end_LONGITUDE',
            'end_LATITUDE' => 'end_LATITUDE'
        ];
    }

    public function insertBus($ticket_arr)
    {
        foreach ($ticket_arr as $val) {
            $this->isNewRecord = true;
            $this->setAttributes($val);
            $this->save();
        }
    }

    /**
     * Function Description:新增可售票种的操作
     * Function Name: istBusTicket
     * @param $ticket_arr
     *
     * @return bool
     *
     * @author 娄梦宁
     */
    public function istBusTicket($ticket_arr)
    {
        $prod_category_1 = new ProdCategory();
        $prod_main_1 = new ProdMain();

        foreach ($ticket_arr as $val) {
            $transaction = Yii::$app->db->beginTransaction();
            try {
                //***************************************插入bus_ticket表**************************************************
                $this->isNewRecord = true;
                $this->setAttributes($val);
                $res = $this->save();
                if ($res === false) {
                    $transaction->rollBack();
                    continue;
                }
                //***************************************插入prod_category表**************************************************
                $tmp_pro_name = $val['line_name'] . "({$val['start_res_name']}-{$val['end_res_name']})";
                $value = [
                    'category_id' => '1',
                    'pro_cate_name' => $tmp_pro_name,
                    'bus_ticket_id' => $val['ticket_id'],
                    'bus_line_type' => $val['line_type'],
                    'create_time' => date('Y-m-d H:i:s'),
                    'show_price' => $val['prod_price'],
                    'commission' => 5,
                ];
                $prod_category = clone $prod_category_1;
                $prod_category->attributes = $value;
                $prod_res = $prod_category->insert();
                if ($prod_res === false) {
                    $transaction->rollBack();
                    continue;
                }
                //***************************************插入prod_main表**************************************************
                $value_adult = [
                    'prod_cate_id' => $prod_category->pro_cate_id,
                    'prod_price' => $val['prod_price'],
                    'bus_id' => $val['ticket_id'],
                    'prod_name' => '成人票',
                    'create_time' => date('Y-m-d H:i:s')
                ];
                $prod_main = clone $prod_main_1;
                $prod_main->attributes = $value_adult;
                $prod_main_res = $prod_main->insert();
                if ($prod_main_res === false) {
                    $transaction->rollBack();
                    continue;
                }
                $value_child = [
                    'prod_cate_id' => $prod_category->pro_cate_id,
                    'prod_price' => $val['prod_price'],
                    'bus_id' => $val['ticket_id'],
                    'prod_name' => '儿童票',
                    'create_time' => date('Y-m-d H:i:s')
                ];
                $prod_main_2 = clone $prod_main_1;
                $prod_main_2->attributes = $value_child;
                $prod_main_res_2 = $prod_main_2->insert();
                if ($prod_main_res_2 === false) {
                    $transaction->rollBack();
                    continue;
                }
                $transaction->commit();
            } catch (Exception $e) {
                $transaction->rollBack();
            }
        }

        return true;
    }

    /**
     * Function Description:cs系统取消的票种处理
     * Function Name: delBusTicket
     * @param $ticket_arr
     *
     * @return bool
     *
     * @author 娄梦宁
     */
    public function delBusTicket($ticket_arr)
    {

        $prod_category = new ProdCategory();
        $prod_main = new ProdMain();
        foreach ($ticket_arr as $val) {
            $transaction = Yii::$app->db->beginTransaction();
            //物理删除bus_ticket表
            $this->deleteAll(['ticket_id' => $val['ticket_id']]);
            //***************************************改变prod_category表状态位**************************************************
            $count = $prod_category::updateAll(['delete_flag' => 1], ['=', 'bus_ticket_id', $val['ticket_id']]);
            if (!$count) {
                $transaction->rollBack();
                continue;
            }
            //***************************************改变prod_main表状态位**************************************************
            $count = $prod_main::updateAll(['delete_flag' => 1], ['=', 'bus_id', $val['ticket_id']]);
            if (!$count) {
                $transaction->rollBack();
                continue;
            }
            $transaction->commit();
        }

        return true;
    }


    /**
     * Des:激活已售卖的产品
     * Name: assocBusTicket
     * @param $ticket_arr
     * @return bool
     * @throws \yii\db\Exception
     * @author 倪宗锋
     */
    public function assocBusTicket($ticket_arr)
    {
        $transaction = Yii::$app->db->beginTransaction();
        $prod_category = new ProdCategory();
        foreach ($ticket_arr as $val) {
            //***************************************修改bus_ticket表现有记录**************************************************
            self::updateAll($val, ['=', 'ticket_id', $val['ticket_id']]);
            //***************************************改变prod_category表状态位**************************************************
            $prod_category::updateAll(['delete_flag' => 0], ['=', 'bus_ticket_id', $val['ticket_id']]);//不论是否成功
        }
        $transaction->commit();
        return true;

    }

    /**
     * Function Description:查返程票种id对应的产品id
     * Function Name: getBackTicketId
     * @param $ticket_id
     *
     * @return mixed
     *
     * @author 娄梦宁
     */
    public function getBackTicketId($ticket_id)
    {
        $result = self::find()->select(['c.pro_cate_id'])
            ->from(self::tableName() . ' as a')
            ->innerJoin('bus_ticket b', 'a.end_res_name=b.start_res_name and a.start_res_name=b.end_res_name')
            ->innerJoin('prod_category c', 'a.ticket_id=c.bus_ticket_id')
            ->where(['b.ticket_id' => $ticket_id])
            ->orderBy('a.ticket_id desc,c.pro_cate_id desc')
            ->asArray()
            ->one();
        return $result['pro_cate_id'];
    }


    /*
     * 获取当前数据库所存票种信息
     */
    public function getBusArr()
    {
        $result = self::find()
            ->from(self::tableName())
            ->indexBy('ticket_id')
            ->asArray()
            ->all();
        return $result;
    }

    /**
     * Des:
     * Name: getTicketAndLineByIDs
     * @param $ticketIds array
     * @return array
     * @author 倪宗锋
     */
    public function getTicketAndLineByIDs($ticketIds)
    {
        $where = [
            'and',
            ['in', 'ticket_id', $ticketIds],
            ['=', 'b.delete_flag', 0]
        ];
        $result = self::find()->select(['a.start_res_name', 'a.start_res_id', new Expression("GROUP_CONCAT(CONCAT(ticket_id,'|',a.end_res_id,'|',a.end_res_name,'|',b.pro_cate_id) separator '||') FxTicket")])
            ->from(self::tableName() . ' as a')
            ->innerJoin(ProdCategory::tableName() . ' b', 'a.ticket_id = b.bus_ticket_id')
            ->where($where)
            ->groupBy('a.start_res_id')
            ->indexBy('start_res_id')
            ->asArray()
            ->all();
        if (empty($result)) {
            return [];
        }
        foreach ($result as $key => $val) {//拼接成以起始站为中心的数组
            $result[$key]['end_station_list'] = [];
            $ticketArr = explode('||', $val['FxTicket']);
            foreach ($ticketArr as $val1) {
                $theArr = explode('|', $val1);
                if (count($theArr) == 4) {
                    $theArr1['ticket_id'] = $theArr[0];
                    $theArr1['end_res_id'] = $theArr[1];
                    $theArr1['end_res_name'] = $theArr[2];
                    $theArr1['pro_cate_id'] = $theArr[3];
                    $result[$key]['end_station_list'][$theArr[0]] = $theArr1;
                }
            }
            unset($result[$key]['FxTicket']);
        }
        return $result;
    }
}
