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


namespace common\util;

use common\models\BusTicket;
use common\models\CmsCategory;
use common\models\OrderMain;
use common\models\ProdCategory;
use common\models\ProdMain;
use common\util\curl\CsCurl;
use common\util\prod\LineProdService;
use yii\db\Exception;

class OrderUtil
{
    /**
     * Des:申请取消订单
     * Name: applyCancelOrder
     * @param $order_id int 订单ID
     * @param $is_check int 是否校验
     * @return array
     * @author 倪宗锋
     */
    public static function applyCancelOrder($order_id, $is_check = 1)
    {
        $return = Util::interfaceZzcx(['order_id' => $order_id, 'is_check' => $is_check], '/zzcx/interfaces/order/cancel-order');
        if ($return['flag']) {
            return Util::returnArrSu();
        }
        return Util::returnArrEr($return['msg']);

    }

    /**
     * Des:获取子线路产品的库存日历
     * Name: getBusSaleDate
     * @param $pro_cate_id
     * @param $if_back
     * @param $date
     * @return array
     * @author 倪宗锋
     */
    public static function getBusSaleDate($pro_cate_id, $if_back, $date = '')
    {
        $prod_main = new ProdMain();
        $bus_ticket = new BusTicket();
        if ($if_back == 1) {
            $ticket_info = $prod_main->getTicketId($pro_cate_id);
            $pro_cate_id = $bus_ticket->getBackTicketId($ticket_info[0]['bus_id']);
        }
        //读取产品对应的巴士票种id
        $ticket_info = $prod_main->getTicketId($pro_cate_id);
        $return = CsCurl::getBusSaleDate($ticket_info[0]['bus_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;
    }

    /**
     * Function Description:切换日期实时获取库存
     * Function Name: getBusStock
     * @param $date
     * @param $pro_cate_id
     * @param $if_back
     * @return array
     *
     * @author 娄梦宁
     */
    public static function getBusStock($date, $pro_cate_id, $if_back)
    {

        $prod_main = new ProdMain();
        $bus_ticket = new BusTicket();
        if ($if_back == 1) {
            $ticket_info = $prod_main->getTicketId($pro_cate_id);
            $pro_cate_id = $bus_ticket->getBackTicketId($ticket_info[0]['bus_id']);
        }
        //读取产品对应的巴士票种id
        $ticket_info = $prod_main->getTicketId($pro_cate_id);
        //去cs系统查实时库存信息
        $time = time();
        $siteConfig = Util::getSiteConfig();
        $send_data = [
            'auth_code' => Util::authCodeForCs($time),
            'user_key' => $siteConfig['adm_user_key'],
            'user' => $siteConfig['adm_user'],
            'user_id' => $siteConfig['adm_user_id'],
            'request_time' => $time,
            'action' => 'get_run_array',
            'run_date' => $date,
            'ticket_id' => $ticket_info[0]['bus_id']
        ];
        $curlInterface = new CurlInterface($send_data, 4);
        $curlInterface->setBaseUrl('');

        $ticket_arr_cs = $curlInterface->execute($siteConfig['adm_host1'] . '/api/nfx', 'POST');
        if ($ticket_arr_cs['code'] == 0 && $ticket_arr_cs['data']) {
            $result = [];
            foreach ($ticket_arr_cs['data'] as $val) {
                if (intval($val['count']) <= 0) {
                    $val['count'] = 0;
                }
                /** 将null字段的过滤掉 update on 2017-06-06 14:54**/
                if (empty($val['start_time'])) {
                    continue;
                }
                $stat_time = strtotime($date . ' ' . $val['start_time']);
                if ($stat_time <= time()) {
                    continue;
                }
                /**白哥说将已停运的过滤掉 update on 2017-06-01 10:23**/
                if ($val['run_status'] == 142) {
                    continue;
                }
                foreach ($ticket_info as $k => $v) {
                    $val['prod_name'] = $v['prod_name'];
                    $val['prod_id'] = $v['prod_id'];
                    $val['prod_price'] = $v['prod_price'];
                    $val['station_str'] = $prod_main->getStation($v['prod_id']);
                    if ($val['run_status'] != 137) {
                        $result[$val['start_time']][$k] = $val;
                    };
                }
            }
            if (count($result) == 0) {
                return Util::returnArrEr('该日的班次已截止售卖，请选择其它日期');
            }
            /******************************增加售卖截止时间判断*****************************/
            $prod_category = new ProdCategory();
            $prodInfo = $prod_category->getBusProdDetail($pro_cate_id);
            $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:00', $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('该日的班次已截止售卖，请选择其它日期');
                }
            }
            /******************************华丽的分割线*****************************/
            $result1 = ['prod_info' => $result, 'pro_cate_id' => $pro_cate_id];
            return Util::returnArrSu('', $result1);
        }
        return Util::returnArrEr('没有库存,请重选日期');
    }

    /**
     * Function Description:订单状态查询
     * Function Name: getOrderStatus
     * @param $order_id
     *
     * @return array
     *
     * @author 娄梦宁
     */
    public static function getOrderStatus($order_id)
    {
        $order_main = new OrderMain();
        $str_arr = explode('-', $order_id);
        $order_id = $str_arr[0];
        $result = $order_main->getOrderStatus($order_id);
        if ($result['order_status'] == 1) {
            return Util::returnArrSu('尚未支付', array('order_status' => 1));
        } elseif ($result['order_status'] == 2) {
            return Util::returnArrSu('支付已完成', array('order_status' => 2));
        } else {
            return Util::returnArrSu('订单已失效', array('order_status' => 0));
        }
    }

    /**
     * Function Description:车详情
     * Function Name: getDetail
     * @param $pro_cate_id
     *
     * @return array
     *
     * @author 娄梦宁
     */
    public static function getDetail($pro_cate_id)
    {
        //参数校验
        if (Util::checkPattern('intVal', $pro_cate_id) == false) {
            return Util::returnArrEr('参数错误');
        }
        $prod_category = new ProdCategory();
        $prod_main = new ProdMain();
        $prod_detail = $prod_category->getBusProdDetail($pro_cate_id);
        if ($prod_detail['sign'] != '') {
            $getRunDate = LineProdService::getLineSaleDate($pro_cate_id, 0);
        } else {
            $getRunDate = OrderUtil::getBusSaleDate($pro_cate_id, 0);
        }
        //子产品列表
        $prod_arr = $prod_main->getProdArr($pro_cate_id);
        $prod_detail['prod_arr'] = $prod_arr;
        $prod_detail['run_date'] = $getRunDate['data']['list'];
        return Util::returnArrSu('', $prod_detail);
    }

    /**
     * Function Description:首页列表数据获取
     * Function Name: getAllProd
     * @param $where
     * @param $point
     * @return array
     *
     * @author 娄梦宁
     */
    public static function getAllProd($where, $point)
    {
        $cms_category = new CmsCategory();
        $prod_category = new ProdCategory();
        $result = [];
        $getHotProdArr = $prod_category->GetHotProd($where);
        //热销产品
        if (count($getHotProdArr)) {
            $result[0] = [
                'prod_arr' => $getHotProdArr,
                'cms_category_id' => 1,
                'category_name' => '购买过',
                'recom_arr' => []
            ];
        }
        //推荐产品
        $getRecommendArr = $prod_category->GetRecommendProd($where);
        if (count($getRecommendArr)) {
            $result[1] = [
                'prod_arr' => $getRecommendArr,
                'cms_category_id' => 2,
                'category_name' => '热销',
                'recom_arr' => []
            ];
        }
        //自定义产品类型
        $category_arr = $cms_category->getCategoryArr();
        foreach ($category_arr as $key => $val) {
            $category_id = $val['cms_category_id'];
            $prodArr = $prod_category->GetListProd($category_id, $where);
            if (count($prodArr)) {
                $category_arr[$key]['prod_arr'] = $prodArr;
                $siteConfig = Util::getSiteConfig();
                if (in_array($category_id, $siteConfig['show_recom'])) {//获取LBS定位推荐产品
                    $category_arr[$key]['recom_arr'] = $prod_category->getLBSListByCmsCate($point, $category_id);
                } else {
                    $category_arr[$key]['recom_arr'] = [];
                }
            } else {
                unset($category_arr[$key]);
            }
        }
        $arr = array_merge($result, $category_arr);
        $data = ['prod_list' => $arr];
        return Util::returnArrSu('', $data);
    }


    /**
     * Des:前往蜘蛛出行确认支付
     * Name: payOrder
     * @param $orderId
     * @param $param_arr
     * @return array
     * @author 倪宗锋
     */
    public static function payOrderNotify($orderId, $param_arr)
    {
        $siteConfig = Util::getSiteConfig();
        $pay = FxAmount::pay($param_arr['fx_uid'], $param_arr['total_money']);
        if ($pay['flag'] == false) {
            return $pay;
        }
        //将数据进行加密
        $time = time();
        $data = [
            'out_trade_no' => $orderId,
            'time' => $time,
            'buyer_pay_amount' => $param_arr['total_money'],
        ];
        $code = Util::authCode(http_build_query($data), "ENCODE");
        $pay_params = [
            'system' => 1,
            'code' => $code,
            'time' => $time,
        ];
        //调用支付确认接口
        $curl = new CurlInterface($pay_params, 3);
        $payResult = $curl->execute($siteConfig['notify_url'], 'POST');
        if ($payResult['return_code'] != 'SUCCESS') {
            return Util::returnArrEr('预下单失败!' . $payResult['return_msg']);
        }
        return Util::returnArrSu();
    }


    /**
     * Des:下单
     * Name: makeOrder
     * @param $params
     * @return array
     * @author 倪宗锋
     */
    public static function makeOrder($params)
    {
        /***前往蜘蛛出行下单***/
        $siteConfig = Util::getSiteConfig();
        $curl = new CurlInterface($params, 4);
        $makeOrder = $curl->execute($siteConfig['zzcx_host'] . '/zzcx/order/order/make-order', 'POST');
        if ($makeOrder['flag'] != true) {//下单成功
            return Util::returnArrEr($makeOrder['msg']);
        }
        $return = $makeOrder['data'];//返回值
        //如果是余额支付 需扣除当前分销账户的余额 并调用支付完成通知接口告知支付已完成
        if ($params['pay_type'] == 3) {//余额支付
            $orderId = $return['order_id'];
            $payOrder = [
                'fx_uid' => $params['fx_uid'],
                'total_money' => $return['total_money'],
            ];
            $payFlag = static::payOrderNotify($orderId, $payOrder);
            if ($payFlag['flag'] == false) {
                return Util::returnArrEr($payFlag['msg']);
            }
        }
        /****设置返回值****/
        $return['qr_code'] = $siteConfig['host_name'] . '/fx/?r=weChat/we-chat/q-code&qCode=' . urlencode($return['pay_url']) . '&_math=441';
        $return['pay_type'] = $params['pay_type'];
        return Util::returnArrSu('', $return);

    }
}