<?php
/**
 *
 * ============================================================================
 * * 版权所有 蜘蛛出行 * *
 * 网站地址: http://www.zhizhuchuxing.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * Author By: 倪宗锋
 * PhpStorm LineProdService.php
 * Create By 2017/3/29 16:38 $
 */


namespace common\util\prod;


use common\models\BusTicket;
use common\models\OrderMain;
use common\models\ProdCategory;
use common\util\curl\CsCurl;
use common\util\Util;

class LineProdService
{
    /**
     * Des:获取主线路产品库存日历
     * Name: getLineSaleDate
     * @param $pro_cate_id
     * @param $if_back
     * @param $date
     * @return array
     * @author 倪宗锋
     */
    public static function getLineSaleDate($pro_cate_id, $if_back, $date = '')
    {
        if (Util::checkPattern('intVal', $pro_cate_id) == false) {
            return Util::returnArrEr('params error');
        }
        $prodCate = new ProdCategory();
        $prodInfo = $prodCate->getBusProdDetail($pro_cate_id);
        if ($if_back) {
            $end_area_id = $prodInfo['start_area_id'];//站点 起始站POI作为终点站POI
            $start_area_id = $prodInfo['end_area_id'];//站点 终点站POI作为起始站POI
            $return = CsCurl::getLineSaleDate('', $start_area_id, $end_area_id);//获取两个POI之间的班次库存

        } else {
            if (empty($prodInfo['sign'])) {
                return Util::returnArrEr('该产品已下架！');
            }
            $line_id = $prodInfo['sign'];//线路ID
            $return = CsCurl::getLineSaleDate($line_id);//获取线路的班次库存
        }
        //将比今天或者指定日期小的日期剔除
        if (empty($return['data']['list']['0']) == false) {
            if (empty($date)) {
                $date = date('Y-m-d');
            }
            foreach ($return['data']['list'] as $key => $val) {
                if (strtotime($val) < strtotime($date)) {
                    unset($return['data']['list'][$key]);
                } else {
                    break;
                }
            }
        }
        $return['data']['list'] = array_values($return['data']['list']);
        return $return;
    }

    /**
     * Des:获取主线路的按日期查询班次及库存
     * Name: getLineBusStock
     * @param $date
     * @param $pro_cate_id
     * @param $if_back
     * @return array
     * @author 倪宗锋
     */
    public static function getLineBusStock($date, $pro_cate_id, $if_back)
    {
        if (Util::checkPattern('intVal', $pro_cate_id) == false) {
            return Util::returnArrEr('params error！');
        }
        /**从cs获取主线路班次库存*/
        $getBusStock = static::getBusStockForLineFromCs($pro_cate_id, $date, $if_back);
        if ($getBusStock['flag'] == false) {
            return $getBusStock;
        }
        /**设置前端使用的价格库存*/
        $setReturn = static::setTicketReturn($getBusStock['data'], $date);
        return $setReturn;

    }

    /**
     * Des:从cs获取主线路班次库存
     * Name: getBusStockForLineFromCs
     * @param $pro_cate_id
     * @param $date
     * @param $if_back
     * @return array
     * @author 倪宗锋
     */
    public static function getBusStockForLineFromCs($pro_cate_id, $date, $if_back)
    {
        $prodCate = new ProdCategory();
        $prodInfo = $prodCate->getBusProdDetail($pro_cate_id);

        if ($if_back) {
            $end_area_id = $prodInfo['start_area_id'];//站点 起始站POI作为终点站POI
            $start_area_id = $prodInfo['end_area_id'];//站点 终点站POI作为起始站POI
            $return = CsCurl::getGoBusStockForArea($start_area_id, $end_area_id, $date);//获取两个POI之间的班次库存

        } else {
            if (empty($prodInfo['sign'])) {
                return Util::returnArrEr('该产品已下架！');
            }
            $line_id = $prodInfo['sign'];//线路ID
            $return = CsCurl::getGoBusStockForLine($line_id, $date);//获取线路的班次库存
        }
        /******************************增加售卖截止时间判断*****************************/
        $close_sale_time = $prodInfo['close_sale_time'];
        if ($close_sale_time == '') $close_sale_time = 24;
        $s_time = strtotime($date) + $close_sale_time * 60 * 60;
        $curr_h_i = date('H:i:s', $s_time);
        if ($curr_h_i == '00:00:00') $curr_h_i = '24:00:00';
        //1.判断是否存在订单了
        $orderMain = new OrderMain();
        $param = ["prod_cate_id" => $pro_cate_id, "start_date" => $date, "start_time" => $curr_h_i, "small24" => $close_sale_time < 0];
        $boolExist = $orderMain->existOrder($param);
        if (!$boolExist) {
            if ($s_time <= time()) {
                return Util::returnArrEr('该日的班次已截止售卖，请选择其它日期');
            }
        }
        /******************************华丽的分割线*****************************/
        return $return;
    }

    /**
     * Des:设置获取班次返回值
     * Name: setTicketReturn
     * @param $data
     * @return array
     * @author 倪宗锋
     */
    public static function setTicketReturn($data, $date)
    {
        /**获取所有去重后的票种ID*/
        $ticketIds = static::getTicketByCSTicket($data);
        if (empty($ticketIds['ticket'])) {
            return Util::returnArrEr('当前日期票已售完，请选择其他日期！');
        }
        /**获取票种对应的站点数组*/
        $bus_ticket = new BusTicket();
        $ticketArr = $bus_ticket->getTicketAndLineByIDs($ticketIds['ticket']);
        foreach ($ticketIds['runBusArr'] as $key => $val) {
            $ticketIds['runBusArr'][$key]['start_station_list'] = static::getBusArrBYTicketList($val['ticket_list'], $ticketArr, $date);
            unset($ticketIds['runBusArr'][$key]['ticket_list']);
            if (count($ticketIds['runBusArr'][$key]['start_station_list']) <= 0) {//如果没有可选站点则 删除该班次
                unset($ticketIds['runBusArr'][$key]);
                continue;
            }
        }
        ksort($ticketIds['runBusArr']);
        if (empty($ticketIds['runBusArr'])) {
            return Util::returnArrEr('没有库存,请重选日期');
        }
        return Util::returnArrSu('', ['station_list' => array_values($ticketIds['runBusArr'])]);
    }

    /**
     * Des:凭借前端班次数组
     * Name: getBusArrBYTicketList
     * @param $ticketList
     * @param $ticketArr
     * @return array
     * @author 倪宗锋
     */
    public static function getBusArrBYTicketList($ticketList, $ticketArr, $date)
    {
        $theArr = [];
        foreach ($ticketList as $key => $val) {
            /**判断时间*/
            $stat_time = strtotime($date . ' ' . $val['start_time'] . ':00');
            if ($stat_time <= time()) {
                continue;
            }
            foreach ($ticketArr as $tkey => $tVal) {
                if (isset($tVal['end_station_list'][$key])) {
                    $sArr = [];
                    if (empty($theArr[$tkey])) {
                        $theArr[$tkey]['start_res_id'] = $tVal['start_res_id'];
                        $theArr[$tkey]['start_res_name'] = $tVal['start_res_name'];
                        if (isset($val['prod_num'])) {
                            $theArr[$tkey]['start_res_time'] = $val['start_time'];
                        } else {//兼容之前的版本
                            $theArr[$tkey]['start_res_time'] = '00:00:00';
                        }
                        $theArr[$tkey]['end_station_list'] = [];
                    }
                    $sArr['station_id'] = $tVal['end_station_list'][$key]['end_res_id'];
                    $sArr['station_name'] = $tVal['end_station_list'][$key]['end_res_name'];
                    $sArr['pro_cate_id'] = $tVal['end_station_list'][$key]['pro_cate_id'];
                    if (isset($val['prod_num'])) {
                        $sArr['count'] = $val['prod_num'];
                        $sArr['end_res_time'] = $val['end_time'];
                    } else {//兼容之前的版本
                        $sArr['count'] = $val;
                        $sArr['end_res_time'] = '00:00';
                    }
                    $theArr[$tkey]['end_station_list'][] = $sArr;
                }
            }
        }
        return array_values($theArr);
    }

    /**
     * Des:获取TICKET字符串
     * Name: getTicketByCSTicket
     * @param $busArr
     * @return array
     * @author 倪宗锋
     */
    public static function getTicketByCSTicket($busArr)
    {
        $ticketArr = [];
        $runBusArr = [];
        foreach ($busArr as $val) {
            if (count($val['ticket_list']) == 0) {
                continue;
            }
            $cnt = 0;
            foreach ($val['ticket_list'] as $key => $tiVal) {
                if ($tiVal > 0) {
                    $cnt++;
                    $ticketArr[$key] = $key;//去重保存
                }
            }
            if ($cnt) {//没有库存的不保存
                $runBusArr[$val['run_time']] = $val;
            }
        }
        return ['ticket' => array_values($ticketArr), 'runBusArr' => $runBusArr];
    }
}