<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Order_finance extends CI_Controller {

    /*!
     * 基本流程
     * * 获取拼团类别: PVT?
     * * 获取拼团总人数, 价格人等
     * * 分别计算每次拼团成本
     * * * 写入report_tour
     * * 所有产品总成本
     * * * 写入report_order
     * END
     */
    /*!
     * GCI_groupType
     * 1 - PVT
     * 2 - combine
     */

    public function __construct(){
        parent::__construct();
        $this->load->helper('array');
        $this->load->model('OrderFinance_model');
        mb_regex_encoding("UTF-8");
        bcscale(4);
    }

    public function index()
    {

    }

    // 重新生成账单
    // HT批量按钮调用
    // 仅读取成本信息计算
    public function single_order_report($coli_sn=0, $debug=false, $force_action=false )
    {
        $debug = boolval($debug);
        $force_action = boolval($force_action);
        $order_info = $this->OrderFinance_model->get_order_info($coli_sn);
        if (empty($order_info)) {
            return;
        }
        $report_order_exists = $this->OrderFinance_model->get_report_order($order_info->ordernumber);
        if ( ! empty($report_order_exists) && $debug===false && $force_action===false) {
            return $this->output->set_content_type('application/json')->set_output(json_encode($report_order_exists));
        }
        return $this->generate_report($order_info, $debug);
    }

    // 重新生成账单
    // HT单团财务表页面调用, 先刷新一次成本
    public function single_order_report_refresh($coli_sn=0, $debug=false, $force_action=false)
    {
        ignore_user_abort(true);
        $debug = boolval($debug);
        $force_action = boolval($force_action);
        // 刷新成本
        $controller_name = "TulanduoApi";
        require_once($controller_name . '.php');
        $vendor_class = new $controller_name();
        $ret = $vendor_class->insert_HT_order_operation($coli_sn, null, false);
        $this->single_order_report($coli_sn, $debug, $force_action);
    }

    /*!
     * 单团财务表计算
     * @date   2018-07-18
     * @param  integer     $coli_sn 订单主表key
     * 基本流程:
     * * 获取拼团类别: PVT, 拼团
     * * 获取拼团总人数, 价格人等
     * * 分别计算每次拼团成本
     * * * 写入report_tour
     * * * 其他产品项目, report_train, report_hotel等
     * * 所有产品总成本
     * * * [此处不做]写入核算管理CK_GroupInfo
     * * * 写入单团财务表report_order
     * END
     */
    public function generate_report($order_info=array(), $debug=false)
    {
        $coli_sn = $order_info->COLI_SN;
        /** 单团财务表 */
        $report_order = array();
        $report_order['OrderYJLR'] = 0; //预计利润
        $report_order['money'] = 0; // 总收入, 实收金额
        $report_order['profitmoney'] = 0;   // 利润
        $report_order['adultnumber'] = 0;
        $report_order['childnumber'] = 0;
        $report_order['babynumber'] = 0;
        $report_order['qtCost'] = 0;
        $report_order['qtMoney'] = 0;
        $report_order['orderstats'] = 1;
        $report_order['ordernumber'] = $order_info->ordernumber;
        $report_order['TuanName'] = mb_convert_encoding(substr($order_info->TuanName, 0, 50), 'UTF-8');
        $report_order['operater'] = $order_info->operater;
        $report_order['Agenter'] = mb_substr($order_info->Agenter,0,10);
        $report_order['ChinaName'] = $order_info->ChinaName;
        $report_order['country'] = $order_info->country;
        $report_order['reservedate'] = $order_info->reservedate;
        $report_order['guesttype'] = ($order_info->guesttype===null) ? 1 : $order_info->guesttype;
        $report_order['RO_GRI_SN'] = $report_order['RO_CGI_SN'] = $order_info->GRI_SN;
        $report_order['basemoney'] = $order_info->otherCost;    // 总成本=SUM(COLD_TotalCOst)+COLI_OtherCost
        // $report_order['OrderPrice'] = $order_info->OrderPrice;  // 总报价
        /** 订单支付信息 */
        $order_payment = $this->OrderFinance_model->get_order_payment($coli_sn);
        $report_order['paymodenew'] = 0;
        $report_order['money'] = $order_payment->SSmoney;
        $report_order['RO_PayDescribe'] = $order_payment->payTypeDesc;
        $report_order['paydate'] = $order_payment->patDate;
        $report_order['OrderPrice'] = $report_order['money'];
        if (strval($order_info->operater) === '435') {
            $report_order['money'] = $order_info->OrderPrice;
        }
        /** 订单人数 */
        $person_num = $this->OrderFinance_model->get_order_person_num($coli_sn);
        $report_order['adultnumber'] = $person_num->adult_num;
        $report_order['childnumber'] = $person_num->child_num;
        $ret = new stdClass();
        $ret->pvt = array();
        /** 图兰朵产品: 取拼团实际成本 */
        $ret->combine_cost = array();
        $ret->report_tour = array();
        $combineNo_arr = $this->OrderFinance_model->get_order_combineNo($coli_sn); // 拼团,PVT按顺序处理
        $group_type_arr = array_unique(array_map(function($ele){return $ele->GCI_groupType;}, $combineNo_arr));
        $processed_code = array(); // 已处理的产品编号
        foreach ($combineNo_arr as $kc => $vc) {
            if (empty($vc->GCI_combineNo)) {
                continue;
            }
            if ($vc->GCI_groupType == 1) {
                // 除去只能PVT的. 避免预定接送*1+tour*1, tour拼团只有一个订单, 被视为整团pvt,漏算接送成本
                $processed_code = array_diff($processed_code, $this->forbidden_combine());
                $pvt_cost = $this->pvt_basic($vc->GCI_combineNo, $coli_sn, $processed_code);
                if ($pvt_cost !== null) {
                    $ret->pvt[] = $pvt_cost;
                }
                if (isset($pvt_cost->processed_code) && $order_info->pag_cnt > 1) { // 单个产品可能重复,既拼又PVT
                    $processed_code = array_merge($processed_code, $pvt_cost->processed_code); // 多地pvt时需要区分
                }
            } else if ($vc->GCI_groupType == 2) {
                // 这里不排除产品编号是否已处理, 因为重复的情况比较多. 如T180917-BHJ180716001M
                $tmp_cost = $this->combine_basic($vc->GCI_combineNo, $coli_sn);
                if ($order_info->pag_cnt > 1) { // 单个产品可能重复,既拼又PVT
                    $processed_code = array_merge($processed_code, $tmp_cost->combine_pags);
                }
                $ret->combine_cost[] = $tmp_cost;
                $tmp_cost = null;
            }
        }
        /** 保存图兰朵包价线路产品的成本到report_tour */
        $processed_cold_sn = array();
        // pvt
        $report_tour_pvt = array();
        if ( ! empty($ret->pvt)) {
            foreach ($ret->pvt as $kpvt => $cpvt) {
                $processed_cold_sn = array_merge($processed_cold_sn,$cpvt->cold_sn);
                $report_tour_pvt = array();
                $report_tour_pvt['ordernumber'] = $cpvt->coli_id;
                $report_tour_pvt['tourCode']    = mb_substr($cpvt->PAG_Code, 0, 50);
                $report_tour_pvt['tourname']    = mb_convert_encoding(substr($cpvt->pag_name, 0, 200), 'UTF-8');
                $report_tour_pvt['tourtime']    = $cpvt->startdate;
                $report_tour_pvt['tourRSd']     = $cpvt->adult_num;
                $report_tour_pvt['tourRSx']     = $cpvt->child_num;
                $report_tour_pvt['tourCostRsd'] = $cpvt->person_cost;
                $report_tour_pvt['tourCostRSx'] = $cpvt->person_cost;
                $report_tour_pvt['tourcost']    = $cpvt->cost_sum;
                $report_tour_pvt['tourPrice']   = $this->OrderFinance_model->convert_to_RMB($cpvt->totalPrice);
                $report_tour_pvt['tourProfit']  = ($report_tour_pvt['tourPrice']>0) ? bcsub($report_tour_pvt['tourPrice'], $report_tour_pvt['tourcost']) : 0;
                $report_tour_pvt['tourProvide'] = mb_substr($cpvt->vendor_name, 0, 50);
                $report_tour_pvt['tourBZ']      = mb_substr($cpvt->comment, 0, 150);
                $report_tour_pvt['orderstats']  = 1;
                $report_tour_pvt['RPT_COLD_SN'] = $cpvt->cold_sn[0];
                // 成本详情
                $report_tour_pvt['RPT_Car']         = $cpvt->cost_category['touristCarOperations'];
                $report_tour_pvt['RPT_Meal']        = $cpvt->cost_category['restraurantOperations'];
                $report_tour_pvt['RPT_Ticket']      = $cpvt->cost_category['sceneryOperations'];
                $report_tour_pvt['RPT_Service']     = $cpvt->cost_category['guiderOperations'];
                $report_tour_pvt['RPT_MealGrants']  = $cpvt->cost_category['guide_meal'];
                $report_tour_pvt['RPT_Water']       = $cpvt->cost_category['water'];
                $report_tour_pvt['RPT_Other']       = $cpvt->cost_category['otherCosts'];
                $report_tour_pvt['RPT_Total']       = $cpvt->cost_sum;
                $report_tour_pvt['RPT_PersonGrade'] = $cpvt->person_grade;
                $report_tour_pvt['this_coldsn'] = implode(',', $cpvt->cold_sn);
                $ret->report_tour[] = $report_tour_pvt;
                // 计算订单总成本
                $report_order['basemoney'] = bcadd($report_order['basemoney'], $report_tour_pvt['tourcost']);
            }
        }
        // 拼团
        if ( ! empty($ret->combine_cost)) {
            foreach ($ret->combine_cost as $kcc => $cost) {
                $cost_c = array();
                $cost_c['ordernumber'] = $cost->coli_id;
                $cost_c['tourCode']    = mb_substr(implode(',', array_unique(array_map(function($ele){ return $ele->real_code; }, $cost->order_cost))), 0, 50);
                $cost_c['tourname']    = mb_convert_encoding( substr($cost->pag_name, 0, 200), 'UTF-8') ;
                $cost_c['tourtime']    = $cost->startdate;
                $cost_c['tourRSd']     = $cost->order_cost[0]->adult_num;
                $cost_c['tourRSx']     = $cost->order_cost[0]->child_num;
                $cost_c['tourCostRsd'] = $cost->person_cost;
                $cost_c['tourCostRSx'] = $cost->person_cost;
                $cost_c['tourcost']    = $cost->order_cost[0]->order_cost_sum;
                $cost_c['RPT_COLD_SN'] = $cost->order_cost[0]->COLD_SN;
                $cost_c_price = 0;
                foreach ($cost->order_cost as $koc => $coc) {
                    if ($coc->PAG_code === $coc->real_code) {
                        $cost_c_price = bcadd($cost_c_price, $coc->totalPrice);
                    }
                    $processed_cold_sn[] = $coc->COLD_SN;
                }
                $cost_c['tourPrice']   = $this->OrderFinance_model->convert_to_RMB($cost_c_price);
                $cost_c['tourProfit']  = ($cost_c['tourPrice']>0) ? bcsub($cost_c['tourPrice'], $cost_c['tourcost']) : 0;
                $cost_c['tourProvide'] = mb_substr($cost->vendor_name, 0, 50);
                $cost_c['tourBZ']      = mb_substr($cost->comment, 0, 150);
                $cost_c['orderstats']  = 1;
                // 成本详情
                $cost_c['RPT_Car']         = $cost->cost_category['touristCarOperations'];
                $cost_c['RPT_Meal']        = $cost->cost_category['restraurantOperations'];
                $cost_c['RPT_Ticket']      = $cost->cost_category['sceneryOperations'];
                $cost_c['RPT_Service']     = $cost->cost_category['guiderOperations'];
                $cost_c['RPT_MealGrants']  = $cost->cost_category['guide_meal'];
                $cost_c['RPT_Water']       = $cost->cost_category['water'];
                $cost_c['RPT_Other']       = $cost->cost_category['otherCosts'];
                $cost_c['RPT_Total']       = $cost->cost_sum;
                $cost_c['RPT_PersonGrade'] = $cost->person_num;
                $cost_c['this_coldsn'] = implode(',', array_map(function ($ele){return $ele->COLD_SN;}, $cost->order_cost));
                $ret->report_tour[] = $cost_c;
                // 计算订单总成本
                $report_order['basemoney'] = bcadd($report_order['basemoney'], $cost_c['tourcost']);
            }
        }
        $ret->processed_cold_sn = array_unique($processed_cold_sn);
        if ($debug !== false) {
            $ret->report_order = $report_order;
            return $this->output->set_content_type('application/json')->set_output(json_encode($ret));
        }
        /** 开始写入数据库 */
        /** 图兰朵供应商 */
        if ( ! empty($ret->report_tour)) {
            $this->OrderFinance_model->insert_report_tour_tulanduo($ret->report_tour);
        }
        /**
         * 非图兰朵供应商的包价线路产品
         * 是图兰朵供应商, 但已取消且未退款
         */
        $other_tour = $this->OrderFinance_model->get_order_detail($coli_sn, 'D', false);
        if ( ! empty($other_tour) || empty($ret->processed_cold_sn)) {
            $ret->others = $this->OrderFinance_model->insert_report_tour_others($coli_sn);
            foreach ($ret->others as $kro => $vro) {
                $report_order['basemoney'] = bcadd($report_order['basemoney'], $vro->tourcost);
            }
        }
        /** 火车票预定 */
        $train_detail = $this->OrderFinance_model->get_order_detail($coli_sn, '2');
        if( ! empty($train_detail)) {
            $ret->train = $this->OrderFinance_model->insert_report_train($coli_sn);
            foreach ($ret->train as $krt => $vrt) {
                $report_order['basemoney'] = bcadd($report_order['basemoney'], $vrt->TotalCost);
            }
        }
        /** 酒店预订 */
        $hotel_detail = $this->OrderFinance_model->get_order_detail($coli_sn, 'A');
        if ( ! empty($hotel_detail)) {
            $ret->hotel = $this->OrderFinance_model->insert_report_hotel($coli_sn);
            foreach ($ret->hotel as $krh => $vrh) {
                $report_order['basemoney'] = bcadd($report_order['basemoney'], $vrh->roomcost);
            }
        }
        // 订单利润
        $report_order['profitmoney'] = $report_order['OrderYJLR'] = bcsub($report_order['money'], $report_order['basemoney']);
        $report_order['builddate'] = date('Y-m-d H:i:s');
        $report_order['xh'] = $this->OrderFinance_model->get_report_order_xh(); //序号
        $ret->report_order = $this->OrderFinance_model->insert_report_order($report_order, $coli_sn, $report_order['RO_GRI_SN']);

        $this->output->set_content_type('application/json')->set_output(json_encode($ret));
        return;
    }

    /*!
     * 拼团计算
     * @example 180426360,180516007U
     * @date   2018-07-18
     * @param  string     $combineNo
     */
    public function combine_basic($combineNo="", $coli_sn=0, $debug=false)
    {
        $ret = new stdClass();
        $all_orders = $this->OrderFinance_model->get_all_combine_order($combineNo);
        if (empty($all_orders)) {
            return null;
        }
        if ($coli_sn !== NULL) {
            $ret->coli_sn = $coli_sn;
            $payment_currency = "USD";
            $currency_rate = 1;
            $order_payment = $this->OrderFinance_model->get_order_payment($coli_sn, TRUE);
            foreach ($order_payment as $kp => $vp) {
                if ($vp->GAI_SQJE > 0) {
                    $payment_currency = trim($vp->GAI_SQJECurrency);
                    $currency_rate = bcdiv($vp->GAI_SSJE, $vp->GAI_SQJE);
                    break;
                }
            }
        }
        $all_pags = array_map(function($ele){
            return false === stripos($ele->PAG_Title,'pvt') ? mb_strtoupper($ele->PAG_Code) : null;
        }, $all_orders);
        $all_pag = array_unique($all_pags);
        $combine_pag_arr = array();
        $pvt_code = $this->forbidden_combine();
        if (count($all_pag) > 1) {
            // 多个产品, 找出拼团产品号
            // 先处理拆分拼团的产品, 补全产品号
            $allowed_spread = $this->spread_code();
            $extra_code_cold = array();
            $all_orders_arr = json_decode(json_encode($all_orders), true);  // 避免foreach object 改变自身
            foreach ($all_orders_arr as $ka => $va) {
                $extra_arr = array();
                if (isset($allowed_spread[$va['PAG_Code']])) {
                    foreach ($allowed_spread[$va['PAG_Code']] as $ks => $vs) {
                        $tmp_extra = new stdClass();
                        $tmp_extra = (object) $va;
                        $tmp_extra->real_code = $tmp_extra->PAG_Code;
                        $tmp_extra->real_pag_sn = $tmp_extra->COLD_ServiceSN;
                        $tmp_extra->PAG_Code = $vs;
                        $tmp_extra->COLD_ServiceSN = null;
                        $extra_arr[] = $tmp_extra;
                    }
                }
                $extra_code_cold = array_merge($extra_code_cold, $extra_arr);
            }
            // 不直接merge,避免覆盖key
            foreach ($extra_code_cold as $ke => $ve) {
                $all_orders[] = $ve;
            }
            // 重新计算重复次数
            /**
             * 忽略PVT的重复:名称中含PVT
             */
            $all_pags = array_filter(array_map(function($ele){
                return false===stripos($ele->PAG_Title,'pvt') ? mb_strtoupper($ele->PAG_Code) : null;
            }, $all_orders));
            // 重复的产品号; 可混拼的产品
            $repeat_code = array();
            $code_count = array_count_values($all_pags);
            foreach ($all_pag as $kp => $vp) {
                if (in_array($vp, $pvt_code)) {
                    continue;
                }
                $tmp = null;
                $tmp = $this->get_allowed_combine(mb_strtoupper($vp));
                $this_allowed = ($tmp === null) ? null : array_diff($tmp, $all_pag); // diff((31,41), (31,41,47)) ==> ()
                // $this_allowed = ($tmp === null) ? null : array_diff($all_pag, $tmp); // diff((31,41), (31,41,47)) ==> ()
                if (empty($this_allowed) && $tmp !== null) {
                    $combine_pag_arr[] = $tmp;  // push (31,41)
                }
                // 重复的产品即为拼团
                if(isset($code_count[$vp]) && $code_count[$vp] > 1) {
                    $repeat_code[] = $vp;
                }
            }
            if ( ! empty($repeat_code)) {
                $combine_pag_arr[] = $repeat_code;
            }
        } else {
            // 单个产品
            $combine_pag_arr[] = ($all_pag);
        }
        // 预定多产品, 但是只有部分发了计划
        // 预定多产品, 拼团只有一个订单, 相当于整团PVT
        if (empty($combine_pag_arr)) {
            // $combine_pag_arr[] = array_diff($all_pag, $pvt_code);   // 此处排除PVT租车产品
            $combine_pag_arr[] = $all_pag;
        }
        $ret->combine_pags = my_array_unique($combine_pag_arr);
        $ret->combine_pags = $ret->combine_pags[0]; // 这里用0是因为一个拼团应该只有一组或一个产品
        // 一些不在常规混拼的团, 仅有一个拼团号的订单则加上该团
        foreach ($all_orders as $key => $value) {
            if ($value->combine_cnt === 1) {
                $ret->combine_pags[] = mb_strtoupper($value->PAG_Code);
            }
        }
        $ret->combine_pags = array_values(array_unique(array_filter($ret->combine_pags)));
        $ret->person_num = 0;
        $ret->PAG_Code = "";
        $ret->order_cost = array();
        $ret->totalPrice_RMB = 0;
        $pag_sns = array();
        $unique_coli = array();
        foreach ($all_orders as $ko => $vo) {
            if (in_array(mb_strtoupper($vo->PAG_Code), $ret->combine_pags)
                || null === $vo->COLD_ServiceSN
            ) {
                $pag_sns[] = $vo->COLD_ServiceSN;
                // 整团单拼时, 避免重复计算人数
                // 订单人数不重复计
                // 总人等
                if ( ! in_array(mb_strtoupper($vo->PAG_Code), $pvt_code) && ! in_array($vo->COLI_SN, $unique_coli)) {
                    $unique_coli[] = $vo->COLI_SN;
                    $ret->person_num += $vo->COLD_PersonNum + $vo->COLD_ChildNum;
                }
                $ret->startdate = $vo->COLD_StartDate;
                if ($coli_sn !== NULL) {
                    $tour_s = new stdClass();
                    if ($vo->COLI_SN == $coli_sn) {
                        $tour_s->COLD_SN = $vo->COLD_SN;
                        $tour_s->vei_sn = $vo->COLD_PlanVEI_SN;
                        $tour_s->person_num = $vo->COLD_PersonNum + $vo->COLD_ChildNum;
                        $tour_s->adult_num = $vo->COLD_PersonNum;
                        $tour_s->child_num = $vo->COLD_ChildNum;
                        $tour_s->PAG_code = mb_strtoupper($vo->PAG_Code);
                        // $tour_s->real_code = isset($vo->real_code) ? $vo->real_code : $vo->PAG_Code;
                        $tour_s->real_code = isset($vo->real_code)&&in_array($vo->real_code, $ret->combine_pags) ? $vo->real_code : mb_strtoupper($vo->PAG_Code);
                        $tour_s->real_pag_sn = isset($vo->real_pag_sn) ? $vo->real_pag_sn : $vo->COLD_ServiceSN;
                        $tour_s->totalPrice = $vo->COLD_TotalPrice;
                        $ret->order_cost[] = $tour_s;
                        $ret->coli_id = $vo->coli_ID;
                    }
                    // 预定产品的团款转换人民币, 写入财务表产品的备注
                    // 补充的产品不算
                    if ( ! isset($vo->real_pag_sn) && $vo->COLI_SN == $coli_sn) {
                        $vo->COLD_TotalPrice = $vo->COLD_TotalPrice===NULL ? 0 : $vo->COLD_TotalPrice;
                        if ($payment_currency == "USD" ) {
                            $ret->totalPrice_RMB = bcadd($ret->totalPrice_RMB, bcmul($vo->COLD_TotalPrice, $currency_rate));
                        } else {
                            $ret->totalPrice_RMB = bcadd($ret->totalPrice_RMB, $this->OrderFinance_model->convert_to_RMB($vo->COLD_TotalPrice, 'USD'));
                        }
                    }
                }
            }
        }
        $this_order_real_pag_sns = array_map(function($ele) {return $ele->real_pag_sn;}, $ret->order_cost);
        $pags_info = $this->OrderFinance_model->get_pag_info(implode(',', array_unique(array_filter($this_order_real_pag_sns))),$ret->order_cost[0]->vei_sn); // $pag_sns
        $ret->vendor_name = implode(",", array_values(array_unique(array_filter( array_map(function($ele) {return $ele->VEI2_CompanyBN;}, $pags_info))))) ;
        // $ret->vendor_name = trim($ret->vendor_name);
        $ret->pag_name = implode("; ", array_map(function($ele) {return $ele->PAG_Title;}, $pags_info)) ;
        $ret->PAG_Code = implode(",", $ret->combine_pags);
        $ret->comment = "拼团" . $combineNo . ", 按" . $ret->person_num . "人等";
        $ret->comment .= $ret->totalPrice_RMB>0 ? (", 报价RMB " . $ret->totalPrice_RMB) : "";
        $combine_cost = $this->OrderFinance_model->get_combine_sumMoney($combineNo, $ret->order_cost[0]->vei_sn);
        $ret->cost_category = $combine_cost->cost_category;
        $ret->cost_sum = $combine_cost->cost_sum;
        $ret->person_cost = bcdiv($ret->cost_sum, $ret->person_num);
        foreach ($ret->order_cost as $kc => $voc) {
            $ret->order_cost[$kc]->order_cost_sum = bcmul($voc->person_num, $ret->person_cost);
        }
        if ($debug!=false) {
            return $this->output->set_content_type('application/json')->set_output(json_encode($ret));
        }
        return $ret;
    }

    /*!
     * pvt计算
     * @example 180515061M
     * @date   2018-07-18
     */
    public function pvt_basic($combineNo="", $coli_sn=0, $processed_code=array(), $debug=false)
    {
        $ret = new stdClass();
        $ret->processed_code = array();
        $all_orders_raw = $this->OrderFinance_model->get_all_combine_order($combineNo, $processed_code);
        if (empty($all_orders_raw)) {
            return null;
        }
        $all_orders = $all_orders_raw;
        // 取出供应商id, 有多个供应商时, 说明拆分为多个pvt
        // 多地PVT
        $all_vei_cnt = count(array_unique(array_map(function($ele) {return mb_strtoupper($ele->COLD_PlanVEI_SN);}, $all_orders_raw)));
        if ($all_vei_cnt > 1) {
            $all_vei = array_unique(array_map(function($ele) {return mb_strtoupper($ele->COLD_PlanVEI_SN);}, $all_orders_raw));
            $all_orders = array();
            foreach ($all_orders_raw as $kor => $vor) {
                if ($vor->COLD_PlanVEI_SN === $all_orders_raw[0]->COLD_PlanVEI_SN) {
                    $all_orders[] = $vor;
                    $ret->processed_code[] = $vor->PAG_Code;
                }
            }
        }
        $ret->coli_sn = $coli_sn;
        $ret->coli_id = $all_orders[0]->coli_ID;
        $ret->cold_sn = array_unique(array_map(function($ele) {return $ele->COLD_SN;}, $all_orders));
        $ret->vei_sns = array_unique(array_map(function($ele) {return $ele->COLD_PlanVEI_SN;}, $all_orders));
        // 总报价
        $ret->totalPrice = 0;
        foreach ($all_orders as $kal => $val) {
            $ret->totalPrice = bcadd($ret->totalPrice, $val->COLD_TotalPrice);
        }
        // 预定的产品数
        $ret->tour_count = count(array_unique(array_map(function($ele) {return mb_strtoupper($ele->PAG_Code);}, $all_orders)));
        $person_num = $this->OrderFinance_model->get_order_person_num($coli_sn, implode(",", $ret->cold_sn));
        $ret->person_num = $person_num->person_num;
        $ret->adult_num = $person_num->adult_num;
        $ret->child_num = $person_num->child_num;
        $combine_cost = $this->OrderFinance_model->get_combine_sumMoney($combineNo, $ret->vei_sns[0]);
        $ret->startdate = $all_orders[0]->COLD_StartDate;
        $ret->person_grade = ($all_orders[0]->COLD_PersonNum + $all_orders[0]->COLD_ChildNum );
        $ret->cost_category = $combine_cost->cost_category;
        $ret->cost_sum = $combine_cost->cost_sum;
        $ret->person_cost = bcdiv($ret->cost_sum, $ret->person_num);
        $ret->comment = "PVT[" . $combineNo . "],共" . $ret->person_num . "人";
        $pag_sns = array_values(array_unique(array_map(function($ele) {return $ele->COLD_ServiceSN;}, $all_orders)));
        $pags_info = $this->OrderFinance_model->get_pag_info(implode(',', $pag_sns),  $all_orders[0]->COLD_PlanVEI_SN);
        $ret->PAG_Code = implode(",", array_values(array_unique(array_map(function($ele) {return mb_strtoupper($ele->PAG_Code);}, $pags_info))));
        $ret->vendor_name = implode(",", array_values(array_unique(array_filter(array_map(function($ele) {return $ele->VEI2_CompanyBN;}, $pags_info))))) ;
        $ret->pag_name = implode("; ", array_map(function($ele) {return $ele->PAG_Title;}, $pags_info)) ;
        if ($debug!=false) {
            return $this->output->set_content_type('application/json')->set_output(json_encode($ret));
        }
        return $ret;
    }

    /*!
     * 获取允许拼团的数组
     * @date   2018-07-18
     * @param  string     $tour_code 产品编号
     * @return array                 含允许拼团产品编号的数组
     */
    public function get_allowed_combine($tour_code="")
    {
        $allowed = null;
        $all_allowed = $this->allowed_combine();
        foreach ($all_allowed as $key => $va) {
            if (in_array($tour_code, $va)) {
                $allowed = $va;
                break;
            }
        }
        return $allowed;
    }
    /** 允许混合拼团的不同编号产品 */
    public function allowed_combine()
    {
        return array(
            // * 不同产品但部分行程相同所以允许拼团 *
            array("XASIC-15", "XASIC-41"),
            array("BJSIC-47", "BJSIC-41"),
            // * 产品编号不同实际是同一产品 *
            array("SHSIC-31", "SHSIC-41"),
            array("SHSIC-32", "SHSIC-42"),
            array("SHSIC-33", "SHSIC-43"),
            array("SHSIC-34", "SHSIC-44")
        );
    }

    /** 允许拆分再拼团的产品编号 */
    public function spread_code()
    {
        return array(
            "XASIC-42" => array("XASIC-41"),
            "BJSIC-42" => array("BJSIC-41"),
            "BJSIC-43" => array("BJSIC-41","BJSIC-42"),
            "SHSIC-42" => array("SHSIC-41"),
            "SHSIC-43" => array("SHSIC-41","SHSIC-42")
        );
    }

    /** 肯定是PVT */
    public function forbidden_combine()
    {
        return array(
            "BJALC-209",
            // "BJSIC-16",
            "SHSIC-45",
            "SHSIC-57",
            "XASIC-16"
        );
    }

}

/* End of file order_finance.php */
/* Location: ./webht/third_party/trippestOrderSync/controllers/order_finance.php */
