<?php

namespace common\models;

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

/**
 * This is the model class for table "order_main".
 *
 * @property integer $order_id
 * @property string $order_name
 * @property string $spider_order_id
 * @property string $total_money
 * @property integer $category_id
 * @property integer $prod_cate_id
 * @property integer $prod_source
 * @property integer $prod_cnt
 * @property integer $sh_uid
 * @property integer $fx_uid
 * @property string $start_time
 * @property string $end_time
 * @property string $start_date
 * @property string $end_date
 * @property integer $order_status
 * @property string $update_time
 * @property string $create_time
 * @property integer $delete_flag
 * @property integer $system
 * @property string $start_area
 * @property string $end_area
 * @property integer $main_user_id
 */
class OrderMain extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'order_main';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['total_money','original_price'], 'number'],
            [['category_id', 'prod_cate_id', 'prod_source', 'prod_cnt', 'sh_uid', 'fx_uid', 'order_status', 'delete_flag', 'system', 'main_user_id'], 'integer'],
            [['start_time', 'end_time', 'start_date', 'end_date', 'update_time', 'create_time'], 'safe'],
            [['order_name', 'spider_order_id', 'start_area', 'end_area'], 'string', 'max' => 255],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'order_id' => 'Order ID',
            'order_name' => 'Order Name',
            'spider_order_id' => 'Spider Order ID',
            'total_money' => 'Total Money',
            'category_id' => 'Category ID',
            'prod_cate_id' => 'Prod Cate ID',
            'prod_source' => 'Prod Source',
            'prod_cnt' => 'Prod Cnt',
            'sh_uid' => 'Sh Uid',
            'fx_uid' => 'Fx Uid',
            'start_time' => 'Start Time',
            'end_time' => 'End Time',
            'start_date' => 'Start Date',
            'end_date' => 'End Date',
            'order_status' => 'Order Status',
            'update_time' => 'Update Time',
            'create_time' => 'Create Time',
            'delete_flag' => 'Delete Flag',
            'system' => 'System',
            'start_area' => 'Start Area',
            'end_area' => 'End Area',
            'main_user_id' => 'Main User ID',
            'original_price' => 'original_price'
        ];
    }

    /**
     * Function Description:插入主订单
     * Function Name: insertOrder
     * @param $param_arr
     *
     * @return bool
     *
     * @author 娄梦宁
     */
    public function insertOrder($param_arr)
    {
        $values = [
            'total_money' => $param_arr['total_money'],
            'prod_cate_id' => (int)$param_arr['pro_cate_id'],
            'prod_cnt' => $param_arr['prod_cnt'],
            'fx_uid' => $param_arr['fx_uid'],
            'start_date' => $param_arr['start_date'],
            'start_time' => $param_arr['start_time'],
            'sh_uid' => $param_arr['sh_uid'],
            'order_status' => 1,
            'create_time' => date('Y-m-d H:i:s'),
            'end_date' => date('Y-m-d', $param_arr['end_date']),
            'category_id' => $param_arr['category_id']
        ];
        $this->attributes = $values;
        $res = $this->insert();
        if (!$res) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * Function Description:查询订单是否支付
     * Function Name: getOrderStatus
     * @param $order_id
     *
     * @return array|null|\yii\db\ActiveRecord
     *
     * @author 娄梦宁
     */
    public function getOrderStatus($order_id)
    {
        $result = self::find()->select(['order_status'])
            ->from(self::tableName())
            ->where(['and', ['=', 'order_id', $order_id], ['=', 'delete_flag', 0]])
            ->asArray()
            ->one();
        return $result;
    }

    /**
     * Des:获取订单详情
     * Name: getOrderInfo
     * @param $order_id
     * @return array|null|\yii\db\ActiveRecord
     * @author 倪宗锋
     */
    public function getOrderInfo($order_id)
    {
        $result = self::find()
            ->from(self::tableName())
            ->where(['and', ['=', 'order_id', $order_id], ['=', 'delete_flag', 0]])
            ->asArray()
            ->one();
        return $result;
    }

    /**
     * Function Description:分销订单列表
     * Function Name: FxOrderList
     * @param $params array
     * @param $fx_uid
     * @return array|\yii\db\ActiveRecord[]
     *
     * @author 娄梦宁
     */
    public function FxOrderList($fx_uid, $params)
    {
        $where = ['and', ['=', 'a.fx_uid', $fx_uid], ['=', 'a.delete_flag', 0]];
        if (!empty($params['is_refund'])) {
            $where[] = ['in', 'b.status', explode(',', $params['is_refund'])];
        }
        if (!empty($params['status'])) {
            $where[] = ['in', 'a.order_status', explode(',', $params['status'])];
        }
        $offset = ($params['current_page'] - 1) * $params['page_size'];
        $select = [
            'a.order_id',//订单ID
            'a.order_status',//订单状态
            'a.create_time',//创建时间
            'a.total_money as order_total_money',//订单金额
            'a.category_id',//订单类型ID
            'a.order_name as pro_cate_name',//产品名称
            'a.start_date',//出游时间
            'prod_str' => new Expression("(SELECT GROUP_CONCAT(CONCAT(y.prod_name,',,',x.count) SEPARATOR '||') from order_info x LEFT JOIN prod_main y on x.prod_id = y.prod_id WHERE x.order_id = a.order_id and x.count != 0)"),
            'b.status',//佣金状态
            'commission_total_money' => new Expression("ifnull(b.total_money,0)"),//佣金金额
            "if(b.`status`=1,'待结算',if(b.`status`=2,'已结算','已取消')) as status_desc",//佣金结算状态
            'c.room_name',//房型名称
            'a.prod_cnt',//产品数量
            'a.end_date',//结束日期
            'c.total_details',//房型名称
        ];
        $result = self::find()->select($select)
            ->from(self::tableName() . ' as a')
            ->leftJoin('fx_commission_info b', 'a.order_id=b.order_id')
            ->leftJoin('order_hotel_extra c', 'c.main_order_id = a.order_id')
            ->where($where)
            ->orderBy('a.create_time DESC')
            ->limit($params['page_size'])
            ->offset($offset)
            ->asArray()
            ->all();
        return $result;
    }

    /**
     * Function Description:获取已完成订单
     * Function Name: getFinishOrder
     * @param $date
     *
     * @return array|null|\yii\db\ActiveRecord
     *
     * @author 娄梦宁
     */
    public function getFinishOrder($date)
    {
        $result = self::find()->select(['GROUP_CONCAT(order_id) as order_arr'])
            ->from(self::tableName())
            ->where(['and', ['=', 'order_status', 2], ['<', 'end_date', $date], ['=', 'delete_flag', 0]])
            ->asArray()
            ->one();
        return $result;
    }

    /**
     * Function Description:已完成订单状态变更
     * Function Name: uptFinishOrder
     * @param $order_arr
     *
     * @return int
     *
     * @author 娄梦宁
     */
    public function uptFinishOrder($order_arr)
    {
        $values = [
            'order_status' => 3
        ];
        $count = self::updateAll($values, ['in', 'order_id', $order_arr]);
        return $count;
    }

    /**
     * Des:修改订单信息
     * Name: upOrder
     * @param $value
     * @param $orderIds
     * @return int
     * @author 倪宗锋
     */
    public function upOrder($value, $orderIds)
    {
        $count = self::updateAll($value, ['in', 'order_id', $orderIds]);
        return $count;
    }

    /**
     * Function Description:取消超时订单
     * Function Name: cancelOuttimeOrder
     *
     * @return bool
     *
     * @author 娄梦宁
     */
    public function cancelOuttimeOrder()
    {
        $values = [
            'order_status' => 5
        ];
        $time = date('Y-m-d H:i:s', strtotime('-15 minute'));
        $count = self::updateAll($values, ['and', ['=', 'order_status', 1], ['<', 'create_time', $time]]);
        return $count;
    }

    /**
     * Des:管理后台 订单列表 获取订单列表信息
     * Name: getOrderListAdm
     * @param $param
     * @param int $type
     * @return array|mixed
     * @author 倪宗锋
     */
    public function getOrderListAdm($param, $type = 1)
    {
        //where条件
        $where = ['and', ['!=', 'a.order_status', 1], ['!=', 'a.order_status', 5], ['=', 'a.delete_flag', 0]];
        if ($param['order_id'] != '') {
            $where[] = ['like', 'a.order_id', $param['order_id']];
        }
        if ($param['category_id'] != '') {
            $where[] = ['=', 'a.category_id', $param['category_id']];
        }
        if ($param['create_time_start'] != '') {
            $where[] = ['>=', 'a.create_time', $param['create_time_start']];
        }
        if ($param['create_time_end'] != '') {
            $where[] = ['<', 'a.create_time', date('Y-m-d', strtotime("{$param['create_time_end']} +1 day"))];
        }

        if ($param['start_date_start'] != '') {
            $where[] = ['>=', 'a.start_date', $param['start_date_start']];
        }
        if ($param['start_date_end'] != '') {
            $where[] = ['<', 'a.start_date', date('Y-m-d', strtotime("{$param['start_date_end']} +1 day"))];
        }
        if ($param['order_status'] != '') {
            $where[] = ['=', 'a.order_status', $param['order_status']];
        }
        if ($param['fx_uid'] != '') {
            $where[] = ['=', 'a.fx_uid', $param['fx_uid']];
        }
        if ($param['pay_type'] != '') {
            $where[] = ['=', 'd.pay_type', $param['pay_type']];
        }
        if (empty($param['user_area']) == false) {
            $where[] = ['=', 'g.user_area', $param['user_area']];
        }
        //果运营主体非1或空，则读取自身对应的订单数据，如果运营主体为空，或者运营主体是1则读取订单运营主体是0或1的订单
        $cookies = $_COOKIE;
        if (empty($cookies['user_main_corp']) == false && $cookies['user_main_corp'] != 1 && in_array(YII_ENV,['pro','dev'])) {
            $where[] = ['=', 'e.main_corp_id', $cookies['user_main_corp']];
        }
        //运营负责人
        if (empty($param['main_search']) == false) {
            $where[] = ['=', 'a.main_user_id', $param['main_search']];
        }
        //联系人 和手机号
        if (empty($param['contacts_name']) == false) {
            $where[] = ['like', 'f.contacts_name', $param['contacts_name']];
        }
        if (empty($param['contacts_phone']) == false) {
            $where[] = ['like', 'f.contacts_phone', $param['contacts_phone']];
        }
        if ($type == 1) {//获取count
            $select = ["count(1) cnt"];
            $result = self::find()->select($select)
                ->from(self::tableName() . ' a')
                ->innerJoin('base_category c', ' a.category_id = c.category_id')
                ->innerJoin('pay_main d', ' a.order_id = d.order_id')
                ->leftJoin(MainCorpUser::tableName() . ' e', 'a.main_user_id=e.id')
                ->leftJoin(OrderContacts::tableName() . ' f', 'a.order_id=f.order_id and f.contacts_type=1')
                ->leftJoin(FxUser::tableName() . ' g', 'a.fx_uid=g.uid')
                ->where($where)
                ->asArray()
                ->one();
            return $result['cnt'];
        } else if ($type == 3) {
            $select = ["count(1) cnt", "sum(total_money) total_money"];
            $where[] = ['in', 'a.order_status', [2, 3]];
            $result = self::find()->select($select)
                ->from(self::tableName() . ' a')
                ->innerJoin('base_category c', ' a.category_id = c.category_id')
                ->innerJoin('pay_main d', ' a.order_id = d.order_id')
                ->leftJoin(MainCorpUser::tableName() . ' e', 'a.main_user_id=e.id')
                ->leftJoin(OrderContacts::tableName() . ' f', 'a.order_id=f.order_id and f.contacts_type=1')
                ->leftJoin(FxUser::tableName() . ' g', 'a.fx_uid=g.uid')
                ->where($where)
                ->asArray()
                ->one();
            return $result;
        } else {//获取列表
            //查询字段
            $select = [
                'a.order_id',//订单ID
                "a.create_time as create_order_time",//下单时间
                "c.category_name as order_type_des",//订单类型
                "a.order_name as book_product",//产品品类名称
                "(
                SELECT GROUP_CONCAT(CONCAT(x.prod_name,'X',x.count)  SEPARATOR ' ')
                from order_info x
                WHERE x.order_id = a.order_id
                GROUP BY x.order_id
                ) as prod_des
            ",//具体产品及数量
                "CONCAT(a.start_date,' ',IFNULL(a.start_time,'')) as start_time",//出发时间
                "(SELECT contacts_name from order_contacts where a.order_id = order_id and contacts_type=1 ) as contacts_name",
                "(SELECT contacts_phone from order_contacts where a.order_id = order_id and contacts_type=1) as contacts_phone",
                "(SELECT contacts_ID from order_contacts where a.order_id = order_id and contacts_type=1) as contacts_ID",
                new Expression("CASE a.order_status
                    WHEN 1 THEN '待支付'
                    WHEN 2 THEN '已支付'
                    WHEN 3 THEN '已完成'
                    WHEN 4 THEN '已退款'
                    WHEN 5 THEN '已取消'
                    ELSE ''
                    END
                    as order_status_des
                ")
                ,//订单状态名称
                "a.order_status as order_status_id",//订单状态标识ID
                "if(d.pay_type=1,'微信',if(d.pay_type=2,'支付宝','预付款')) as pay_type_des",//支付类型名称
                'order_come' => new Expression("(SELECT CONCAT(nickname,'<br/>',phone) from fx_user where a.fx_uid = uid)"),//订单来源（分销商）
                "if(a.order_status in (1,2),
                 if(a.start_date >= '" . date('Y-m-d') . "',0,1), 1)
                  as if_can_cancel",//是否可以取消订单
                'a.total_money',
                'a.start_area',
                'a.end_area',
                'a.prod_cnt',
                'a.category_id',
                'a.end_time',
                'system' => new Expression("if(a.system=1,'分销',if(a.system=2,'微信','官网'))"),
                'user_area_name' => new Expression("(select area_name from fx_user_area where area_id = g.user_area)"),
                'a.remark',
                "commission_amount" => new Expression("(SELECT SUM(total_money) from fx_commission_info WHERE order_id = a.order_id)")
            ];
            $offset = ($param['current_page'] - 1) * $param['page_size'];
            $result = self::find()->select($select)
                ->from(self::tableName() . ' a')
                ->innerJoin('base_category c', ' a.category_id = c.category_id')
                ->innerJoin('pay_main d', ' a.order_id = d.order_id')
                ->leftJoin(MainCorpUser::tableName() . ' e', 'a.main_user_id=e.id')
                ->leftJoin(OrderContacts::tableName() . ' f', 'a.order_id=f.order_id and f.contacts_type=1')
                ->leftJoin(FxUser::tableName() . ' g', 'a.fx_uid=g.uid')
                ->where($where)
                ->orderBy('a.create_time DESC')
                ->offset($offset)
                ->limit($param['page_size'])
                ->asArray()
                ->all();
            return $result;
        }
    }

    /*
     * 订单列表
     */
    public function AdminCommissionList($param)
    {
        //where条件
        $where = ['and', ['!=', 'a.order_status', 1], ['!=', 'a.order_status', 5], ['=', 'a.delete_flag', 0], ['=', 'a.fx_uid', $param['fx_uid']]];
        if ($param['order_id'] != '') {
            $where[] = ['like', 'a.order_id', $param['order_id']];
        }
        if ($param['order_type_id'] != '') {
            $where[] = ['=', 'a.category_id', $param['order_type_id']];
        }
        if ($param['create_order_start_date'] != '') {
            $where[] = ['>=', 'a.create_time', $param['create_order_start_date']];
        }
        if ($param['create_order_end_date'] != '') {
            $where[] = ['<', 'a.create_time', date('y-m-d', strtotime("{$param['create_order_end_date']} +1 day"))];
        }
        if ($param['order_status_id'] != '') {
            $where[] = ['=', 'a.order_status', $param['order_status_id']];
        }
        if ($param['settlement_start_date'] != '') {
            $where[] = ['>=', 'a.end_date', date('Y-m-d', strtotime("{$param['settlement_start_date']} -3 day"))];
        }
        if ($param['settlement_end_date'] != '') {
            $where[] = ['<', 'a.end_date', date('Y-m-d', strtotime("{$param['settlement_end_date']} -2 day"))];
        }
        $select = [
            'a.order_id',
            'a.category_id as order_type_id',
            new Expression("CASE a.category_id
                    WHEN 1 THEN '车票'
                    WHEN 2 THEN '门票'
                    WHEN 3 THEN '酒店'
                    ELSE ''
                    END
                    as order_type_des
                ")
            ,
            'a.create_time as create_order_date',
            'a.total_money as order_price',
            'a.order_status as order_status_id',
            new Expression("CASE a.order_status
                    WHEN 2 THEN '已支付'
                    WHEN 3 THEN '已完成'
                    WHEN 4 THEN '已退款'
                    ELSE ''
                    END
                    as order_status_des
            ")
            ,
            'date_add(a.end_date,INTERVAL 3 DAY) as settlement_order_date',
            'b.total_money as all_commission_money'
        ];
        $offset = ($param['current_page'] - 1) * $param['page_size'];
        $result = self::find()->select($select)
            ->from(self::tableName() . ' as a')
            ->leftJoin('fx_commission_info as b', 'a.order_id=b.order_id')
            ->where($where)
            ->orderBy('a.create_time DESC')
            ->offset($offset)
            ->limit($param['page_size'])
            ->asArray()
            ->all();
        $count = self::find()->select('count(1) as count')->from(self::tableName() . ' as a')->where($where)->asArray()->one();
        $count = $count['count'];
        return ['list' => $result, 'count' => $count];
    }

    /**
     * Des:获取订单退款信息
     * Name: getOrderRefund
     * @param $order_id
     * @return array
     * @author 倪宗锋
     */
    public function getOrderRefund($order_id)
    {
        $select = [
            'IFNULL(a.spider_order_id,a.order_id) as order_id',
            'b.pro_cate_name',
            'a.spider_order_id',
            'a.start_date',
            'a.start_time',
            'a.category_id'
        ];
        $result = self::find()
            ->select($select)
            ->from(OrderMain::tableName() . ' a')
            ->innerJoin(ProdCategory::tableName() . ' b', 'a.prod_cate_id = b.pro_cate_id')
            ->where(['=', 'a.order_id', $order_id])
            ->asArray()
            ->one();
        return $result;
    }

    /**
     * Des:判断某个产品是否存在订单
     * Name: existOrder
     * @param $param
     * @return bool
     * @author 付泓程
     */
    public function existOrder($param)
    {
        $prod_cate_id = $param['prod_cate_id'];
        $start_date = $param['start_date'];
        $run_time = $param['start_time'];
        $small24 = $param['small24']; //是否小于0 -即提前X天。
        $select = ['count(order_id) as count'];
//        $sql = "select count(order_id) as count from order_main where prod_cate_id = {$prod_cate_id} and start_date={$start_date} and order_status = 3 and delete_flag=0";
        $where = ['and', ['=', 'a.prod_cate_id', $prod_cate_id], ['=', 'a.start_date', $start_date], ['=', 'a.order_status', 2], ['=', 'a.delete_flag', 0]];
        if (!$small24) {
            $where[] = ['>=', 'a.start_time', $run_time];
        }
        $result = self::find()
            ->select($select)
            ->from(OrderMain::tableName() . ' a')
            ->where($where)
            ->asArray()
            ->one();
        $count = $result['count'];
        if ($count > 0) {
            return true;
        }
        return false;
    }

    /**
     * des 获取订单支付详细信息
     * @param $orderId
     * @return array
     */
    public function getOrderPayInfo($orderId)
    {
        $select = [
            'a.order_id',
            'b.pro_cate_name',
            new Expression("concat(a.start_date,' ',a.start_time) as 'run_time'"),
            'a.category_id',
            new Expression("(select category_name from base_category WHERE category_id = a.category_id) as category_name"),
            'a.prod_cnt',
            'a.create_time',
            'a.order_status',
            'a.total_money',
            'c.contacts_name',
            'c.contacts_phone'
        ];
        $result = self::find()
            ->select($select)
            ->from(OrderMain::tableName() . ' a')
            ->innerJoin(ProdCategory::tableName() . ' b', 'a.prod_cate_id = b.pro_cate_id')
            ->innerJoin(OrderContacts::tableName() . ' c', 'a.order_id = c.order_id and c.contacts_type=1 ')
            ->where(['=', 'a.order_id', $orderId])
            ->asArray()
            ->one();
        return $result;
    }

    /**
     * Des:订单初始化运营负责人
     * Name: bindMainCorp
     * @param $fx_uid
     * @param $main_user_id
     * @return int
     * @author 倪宗锋
     */
    public function bindMainCorp($fx_uid, $main_user_id)
    {
        $count = self::updateAll(['main_user_id' => $main_user_id], ['=', 'fx_uid', $fx_uid]);
        return $count;
    }

    /**
     * Des:获取酒店订单数据
     * Name: getHotelOrderInfo
     * @param $order_id
     * @return array
     * @author 倪宗锋
     */
    public function getHotelOrderInfo($order_id)
    {
        $select = [
            'a.order_id',
            'c.hotel_id',
            'c.room_id',
            'a.prod_cnt',
            'a.start_date',
            'a.end_date',
            'a.total_money',
            'b.contacts_name',
            'b.contacts_phone',
            'c.total_details',
            'a.system'
        ];
        $where = ['=','a.order_id', $order_id];
        $getInfo = self::find()->select($select)
            ->from(self::tableName().' a')
            ->innerJoin(OrderContacts::tableName().' b','a.order_id = b.order_id and b.contacts_type=1')
            ->innerJoin('order_hotel_extra c','a.order_id = c.main_order_id')
            ->where($where)
            ->asArray()
            ->one();
        return $getInfo;
    }
}
