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

class OrderFinance_model extends CI_Model {
    function __construct() {
        parent::__construct();
        $this->load->helper('array');
        $this->HT = $this->load->database('HT', TRUE);
        bcscale(4);
    }

    public function get_order_info($coli_sn=0)
    {
        $sql = "SELECT
                    coli.COLI_SN,coli.COLI_ID as ordernumber,
                    coli.COLI_WebCode as Agenter,
                    coli.COLI_ApplyDate as reservedate
                    ,coli.COLI_Cost as basemoney
                    ,ISNULL(coli.COLI_OtherCost,0) as otherCost
                    ,dbo.ConvertToRMB(ISNULL(coli.COLI_Currency,'USD'),ISNULL(coli.COLI_Price,0)) OrderPrice
                    ,gri.GRI_SN ,gri.GRI_No as TuanName
                    ,opi.OPI_Name as ChinaName,opi.OPI_SN as operater,opi.OPI_DEI_SN
                    ,gut.GUT_NationalityID,COI2_Country as country
                    ,(
                        select top 1 BPE_GuestType
                        from BIZ_ConfirmLineDetail
                        inner join BIZ_BookPeopleList on BPL_COLD_SN=COLD_SN
                        inner join BIZ_BookPeople on BPE_SN=BPL_BPE_SN
                        where COLD_COLI_SN=coli.COLI_SN
                    ) as guesttype
                    ,(
                        select COUNT(0)
                        from BIZ_ConfirmLineDetail
                        where COLD_COLI_SN=coli.COLI_SN
                        and isnull(DeleteFlag,0)=0
                        and COLD_ServiceType='D'
                        and COLD_PlanVEI_SN in (1343,29188,30548,30016)
                    ) as pag_cnt
                from BIZ_ConfirmLineInfo coli
                inner join GRoupInfo gri on coli.COLI_GRI_SN=gri.GRI_SN and gri.DeleteFlag=0
                inner join OperatorInfo opi on opi.OPI_SN=coli.COLI_OPI_ID
                left join BIZ_GUEST gut on gut.GUT_SN=coli.COLI_GUT_SN
                left join CountryInfo2 on COI2_COI_SN=gut.GUT_NationalityID and COI2_LGC=2
                where coli.COLI_SN=$coli_sn ";
        return $this->HT->query($sql)->row();
    }

    public function get_order_detail($coli_sn=0, $service_type='D', $tulanduo=null)
    {
        $vei_sql = ($tulanduo===null) ? "" : " AND COLD_PlanVEI_SN NOT IN (1343,29188,30548,30016) ";
        $sql = "SELECT * from
                BIZ_ConfirmLineDetail cold
                where isnull(cold.DeleteFlag,0)=0 and COLD_ServiceType=?
                and COLD_COLI_SN=$coli_sn
                $vei_sql
                ";
        return $this->HT->query($sql, array($service_type))->result();
    }

    /** 订单的所有拼团号 */
    public function get_order_combineNo($coli_sn=0)
    {
        $sql = "SELECT gci.GCI_combineNo,gci.GCI_groupType,gci.GCI_VEI_SN
                from GroupCombineInfo gci
                inner join BIZ_ConfirmLineInfo coli on gci.GCI_GRI_SN=COLI_GRI_SN and GCI_combineNo<>'cancel'
                where coli.COLI_SN=$coli_sn
                group by gci.GCI_combineNo,gci.GCI_groupType,gci.GCI_VEI_SN
                order by gci.GCI_groupType desc";
        return $this->HT->query($sql)->result();
    }

    /**
     * 拼团号下的所有订单
     * * 仅包价线路产品
     * * 2018-10-10 增加按COLD_PersonNum降序排序, 计算拼团人数时按多的算.
     *     180217342 订单中2人参加两个项目拼同一个团但是人数不同
     */
    public function get_all_combine_order($combineNo="", $processed_code=array())
    {
        $processed_sql = empty($processed_code) ? "" : " and PAG_Code not in (" . my_implode("'",",",$processed_code) . ") ";
        $sql = "SELECT gci.GCI_combineNo,gci.GCI_VendorOrderId
                ,COLI_SN,coli_ID--,COLI_ApplyDate,COLI_GroupCode
                ,COLD_SN,cold.COLD_ServiceSN--,COLD_EndDate
                ,cold.COLD_PlanVEI_SN
                ,PAG_Code ,pag_sub.PAGS_CN_Title, cold.COLD_StartDate,PAG_DefaultVEI_SN
                ,COLD_PersonNum ,COLD_ChildNum , cold.COLD_StartDate,COLD_EndDate, cold.COLD_TotalPrice
                ,PAG_Title
                ,(select count(1) from GroupCombineInfo where gci_gri_sn=coli_gri_sn) as combine_cnt
                from GroupCombineInfo gci
                inner join BIZ_ConfirmLineInfo coli on gci.GCI_GRI_SN=COLI_GRI_SN and coli.COLI_State NOT IN (50)
                inner join BIZ_ConfirmLineDetail cold on cold.COLD_COLI_SN=coli.COLI_SN
                    and cold.COLD_ServiceType='D' and cold.DeleteFlag=0 and COLD_PlanVEI_SN = GCI_VEI_SN
                left join BIZ_PackageInfo pag on PAG_SN=COLD_ServiceSN
                left join BIZ_PackageInfoSub pag_sub on pag_sub.PAGS_SN=COLD_ServiceSN2
                where gci.GCI_combineNo =?
                $processed_sql
                order by GCI_combineNo asc,cold.COLD_StartDate asc,cold.COLD_PersonNum desc";
        return $this->HT->query($sql, array($combineNo))->result();
    }

    /** 拼团的成本明细,总成本信息 */
    public function get_combine_sumMoney($combineNo="", $vendor=null)
    {
        $ret = new stdClass();
        $vendor_sql = $vendor===null ? '' : " AND GCOD_VEI_SN=$vendor ";
        $sql = "SELECT GCOD_operationType,GCOD_subType,SUM(cast(gcod.GCOD_sumMoney as float)) cost
                from GroupCombineOperationDetail gcod
                where gcod.GCOD_GCI_combineNo =?
                    $vendor_sql
                group by GCOD_GCI_combineNo,GCOD_operationType,GCOD_subType";
        $ret->cost_detail = $this->HT->query($sql, array($combineNo))->result();
        $ret->cost_sum = array_sum(array_map(function ($ele){return $ele->cost;}, $ret->cost_detail));

        $ret->cost_category = array();
        $ret->cost_category['water'] = 0;
        $ret->cost_category['guide_meal'] = 0;
        $ret->cost_category['otherCosts'] = 0;
        $ret->cost_category['otherReceives'] = 0;
        $ret->cost_category['guiderOperations'] = 0;
        $ret->cost_category['touristCarOperations'] = 0;
        $ret->cost_category['sceneryOperations'] = 0;
        $ret->cost_category['restraurantOperations'] = 0;
        foreach ($ret->cost_detail as $key => $value) {
            if ($value->GCOD_operationType=='otherCosts' && $value->GCOD_subType=='客人水费') {
                $ret->cost_category['water'] += $value->cost;
                continue;
            } elseif ($value->GCOD_operationType=='otherCosts' && $value->GCOD_subType=='餐补（司陪）') {
                $ret->cost_category['guide_meal'] += $value->cost;
                continue;
            } elseif ($value->GCOD_operationType=='trafficOperations') {
                $ret->cost_category['otherCosts'] += $value->cost;
                continue;
            }
            $ret->cost_category[$value->GCOD_operationType] += $value->cost;
        }
        return $ret;
    }

    /** 子订单中人数最多的预定 */
    public function get_max_cold_person_num($coli_sn=0, $cold_str='')
    {
        $sql = "SELECT
                    ISNULL(MAX(ISNULL(COLD_PersonNum,0)+ISNULL(COLD_ChildNum,0)+ISNULL(COLD_BabyNum,0)), 0) person_num
                    ,ISNULL(MAX(COLD_PersonNum), 0) adult_num
                    ,ISNULL(MAX(COLD_ChildNum+ISNULL(COLD_BabyNum,0)), 0) child_num
                    from BIZ_ConfirmLineDetail
                    where COLD_COLI_SN=$coli_sn ";
        $sql .= $cold_str==='' ? " " : " and COLD_SN in ($cold_str) ";
        $ret = $this->HT->query($sql)->row();
        return $ret;
    }

    /** 订单人数 */
    public function get_order_person_num($coli_sn=0, $cold_str='')
    {
        $ret = new stdClass();
        // 从订单客人名单列表中取
        $sql = "SELECT BPL_BPE_SN,isnull(bp.BPE_GuestType, '1') BPE_GuestType
                from BIZ_ConfirmLineDetail cold
                inner join BIZ_BookPeopleList bpl on bpl.BPL_COLD_SN=cold.COLD_SN
                inner join biz_bookpeople bp on bp.BPE_SN=bpl.BPL_BPE_SN
                where cold.COLD_COLI_SN=$coli_sn  AND cold.DeleteFlag=0
                group by bpl.BPL_BPE_SN,isnull(bp.BPE_GuestType, '1')";
        $query = $this->HT->query($sql);
        $ret->person_num = $query->num_rows();
        $guest_type_cnt = array_count_values(array_map(function($ele) { return $ele->BPE_GuestType; }, $query->result()));
        // 从子订单的人数中取最大值
        $max_person = $this->get_max_cold_person_num($coli_sn, $cold_str);
        if ($ret->person_num === 0 || $ret->person_num < $max_person->person_num
            || $cold_str!==''
        ) {
            // 没有客人名单时, 客人名单小于子订单人数(如新港接送)时
            // 使用子订单结果
            $ret->person_num = $max_person->person_num;
            $ret->adult_num = $max_person->adult_num;
        } else {
            // 订单列表人数 >= 子订单最大人数, 如180606288
            // 使用客人名单总数
            $ret->adult_num = $guest_type_cnt['1'];
        }
        $ret->child_num = $ret->person_num-$ret->adult_num;
        return $ret;
    }

    /** 获取产品信息:产品名称,供应商等 */
    public function get_pag_info($PAG_SN_str="", $cold_vei=null)
    {
        if ($PAG_SN_str=="") {
            return array();
        }
        $vei_sql = $cold_vei===null ? 'PAG_DefaultVEI_SN' : $cold_vei;
        $sql = "SELECT pag.PAG_SN,PAG_Code,PAG_DefaultVEI_SN,PAG_Title,vei2.VEI2_CompanyBN
                from BIZ_PackageInfo pag
                left join VEndorInfo2 vei2 on VEI2_VEI_SN=$vei_sql and VEI2_LGC=2
                where PAG_SN in ($PAG_SN_str)   ";
        return $this->HT->query($sql)->result();
    }

    public function get_order_payment($coli_sn=0, $detail=false)
    {
        $ret = new stdClass();
        $sql = "SELECT gai.GAI_SSDate,gai.GAI_SQJE,gai.GAI_SSJE,gai.GAI_Type,gai.GAI_SQJECurrency
                from BIZ_GroupAccountInfo gai
                where gai.GAI_COLI_SN=$coli_sn and gai.DeleteFlag=0";
        $payment = $this->HT->query($sql)->result();
        if ($detail === TRUE) {
            return $payment;
        }
        $ret->SSmoney =  0;
        $ret->patDate = "";
        $ret->payType = "";
        $ret->payTypeDesc = "";
        if ( ! empty($payment)) {
            foreach ($payment as $kp => $vp) {
                $ret->SSmoney = bcadd($ret->SSmoney, $vp->GAI_SSJE);
            }
            $ret->patDate = $payment[0]->GAI_SSDate;
            $ret->payType = $payment[0]->GAI_Type;
            $ret->payTypeDesc = $this->HT
                                     ->query("SELECT SYC2_CodeDiscribe
                                                FROM V_System_Code
                                                WHERE SYC_Type=15 AND LGC_LGC=2
                                                AND SYC_SN=?
                                                ", array($ret->payType))
                                     ->row()->SYC2_CodeDiscribe;
        }
        return $ret;
    }

    /** 判断各种项目的报表是否已存在 */
    public function report_tour_exists($coli_id=null, $cold_sn=null)
    {
        $sql = "SELECT top 10 ordernumber from report_tour where ordernumber=? ";
        $sql .= $cold_sn===null ? " " : " and RPT_COLD_SN=$cold_sn ";
        // if ($tourBz) {
        //     $tourBz = mb_ereg_replace('[^a-zA-Z0-9\-\[\]]$', '', strstr($tourBz, ",", true));
        //     if (stripos($tourBz, "pvt") === false) {
        //         $tourBz = str_replace("]", "", $tourBz);
        //     }
        //     $tourBz = str_replace("[", "[[]", $tourBz);
        //     $sql .= " and (tourBz like '%" . $this->HT->escape_like_str($tourBz) . "%'
        //                 OR tourBz='') ";
        // } else {
        //     $sql .= " AND tourCode='" . $tourCode . "' ";
        // }
        $num_rows = $this->HT->query($sql, array($coli_id))->num_rows();
        return $num_rows>0;
    }
    public function report_train_exists($coli_id=null, $TrainNo=null)
    {
        $sql = "SELECT top 1 OrderNumber from report_Train where OrderNumber=? and TrainNo=?";
        $num_rows = $this->HT->query($sql, array($coli_id, $TrainNo))->num_rows();
        return $num_rows>0;
    }
    public function report_room_exists($coli_id=null, $hotelName=null)
    {
        $sql = "SELECT top 1 ordernumber from report_room where ordernumber=? and hotelName=?";
        $num_rows = $this->HT->query($sql, array($coli_id, $hotelName))->num_rows();
        return $num_rows>0;
    }
    public function report_order_exists($coli_id=null, $gri_sn=null)
    {
        $sql = "SELECT top 1 ordernumber from report_order where ordernumber=? and ro_gri_sn=? and orderstats=1";
        $num_rows = $this->HT->query($sql, array($coli_id, $gri_sn))->num_rows();
        return $num_rows>0;
    }

    /** 图兰朵包价线路产品 */
    public function insert_report_tour_tulanduo($report_tour_arr=array())
    {
        foreach ($report_tour_arr as $krt => $vrt) {
            $tourBz_tmp = "";
            $tourBz_tmp = mb_ereg_replace('[^a-zA-Z0-9\-\[\]]$', '', strstr($vrt['tourBZ'], ",", true));
            if (stripos($tourBz_tmp, "pvt") === false) {
                $tourBz_tmp = str_replace("]", "", $tourBz_tmp);
            }
            $tourBz_tmp = str_replace("[", "[[]", $tourBz_tmp);
                $where = " ordernumber='" . $vrt['ordernumber'] . "' and RPT_COLD_SN IN (" . $vrt['this_coldsn'] . ") " ;
                $where .= "  AND (tourBZ like '%" . $this->HT->escape_like_str($tourBz_tmp) . "%'
                                OR tourBZ=''
                                OR orderstats=0
                            ) ";
                $delete_sql = "DELETE FROM tourmanager.dbo.Report_Tour where " . $where;
                $this->HT->query($delete_sql);
            unset($vrt['this_coldsn']);
            $this->HT->insert('tourmanager.dbo.Report_Tour', $vrt);
        }
        return TRUE;
    }

    /** 火车票 */
    public function insert_report_train($coli_sn=0)
    {
        $train_cost = $this->get_train_cost($coli_sn);
        foreach ($train_cost as $ktc => $vtc) {
            if ($this->report_train_exists($vtc->OrderNumber, $vtc->TrainNo) === TRUE) {
                $where = " OrderNumber='" . $vtc->OrderNumber . "' AND TrainNo='" . $vtc->TrainNo . "' ";
                $update_sql = $this->HT->update_string('tourmanager.dbo.report_Train', json_decode(json_encode($vtc), TRUE), $where);
                $this->HT->query($update_sql);
            } else {
                $this->HT->insert('tourmanager.dbo.report_Train', json_decode(json_encode($vtc), TRUE));
            }
        }
        return $this->HT->query("SELECT * from tourmanager.dbo.report_Train inner join BIZ_ConfirmLineInfo on COLI_ID=OrderNumber WHERE COLI_SN=$coli_sn order by OrderID desc")->result();
    }
    public function get_train_cost($coli_sn=0)
    {
        $sql = "SELECT
                    dbo.BIZ_ConfirmLineInfo.COLI_ID OrderNumber,
                    FlightsNo TrainNo,
                    DepartureCity,
                    ArrivalCity,
                    left(convert(varchar,DepartureDate,120),10) as DepartureDate,
                    isnull(COLD_PersonNum,0)+ISNULL(COLD_ChildNum,0) as PassengerNo,
                    adultcost adultPrice,
                    COLD_TotalCost as TotalCost,
                    dbo.ConvertToRMB('USD',COLD_TotalPrice) as TotalPrice,
                    SUBSTRING(VEI2_CompanyBN,1,50) TrainProvide,
                     case when dbo.GetBIZTrainVEIDebt(COLD_SN)='YES' then '挂账' else ' ' end as TrainBZ,
                    0 as orderstats
                from BIZ_ConfirmLineDetail
                inner join BIZ_ConfirmLineInfo on COLI_SN=COLD_COLI_SN
                inner join BIZ_FlightsOrderInfo on FOI_COLD_SN = COLD_SN
                left join VEndorInfo2 on COLD_PlanVEI_SN = VEI2_VEI_SN and VEI2_LGC = 2
                where COLD_COLI_SN = $coli_sn
                    and isnull(BIZ_ConfirmLineDetail.DeleteFlag,0)=0
                    and COLD_ServiceType = '2' ";
        return $this->HT->query($sql)->result();
    }

    /** 酒店 */
    public function insert_report_hotel($coli_sn=0)
    {
        $hotel_cost = $this->get_hotel_cost($coli_sn);
        foreach ($hotel_cost as $khc => $vhc) {
            if ($this->report_room_exists($vhc->ordernumber, $vhc->hotelName) === TRUE) {
                $where = " ordernumber='" . $vhc->ordernumber . "' AND hotelName='" . $vhc->hotelName . "' ";
                $update_sql = $this->HT->update_string('tourmanager.dbo.report_room', json_decode(json_encode($vhc), TRUE), $where);
                $this->HT->query($update_sql);
            } else {
                $this->HT->insert('tourmanager.dbo.report_room', json_decode(json_encode($vhc), TRUE));
            }
        }
        return $this->HT->query("SELECT * from tourmanager.dbo.report_room inner join BIZ_ConfirmLineInfo on COLI_ID=ordernumber WHERE COLI_SN=$coli_sn order by orderId desc")->result();
    }
    public function get_hotel_cost($coli_sn)
    {
        $sql = "
            SELECT coli_id ordernumber,
                   SUBSTRING(v2.VEI2_CompanyBN,1,50) AS hotelName,
                   cityinfo2.CII2_Name AS cityName,
                   (SELECT SGC_ServiceGrade
                   FROM servicegradecode2
                   WHERE SGC2_LGC=2
                       AND SGC2_SGC_SN=Isnull(VEI_Grade,-1)) AS hotelStar,
                   (SELECT SUBSTRING(ROT2_TypeName,1,100) as ROT2_TypeName
                   FROM roomtype2
                   WHERE ROT2_ROT_SN=ISNULL(COLD_ServiceSN2,-1)
                       AND ROT2_LGC=1) AS roomtype,
                   left(convert(varchar,COLD_StartDate,120),10) AS starttime,
                   left(convert(varchar,COLD_EndDate,120),10) AS endtime,
                   CONVERT(int, COLD_Count) roomnumber,
                   isnull(HOI_ExtraNum,0) AS ExtraBedNumber,
                   DATEDIFF(DAY,COLD_StartDate,COLD_EndDate) as jianyeshu,
                    COLD_TotalCost*1.0/dbo.ZeroToOne(DATEDIFF(DAY,COLD_StartDate,COLD_EndDate)) as jianyecost,
                    0 as ExtraBedCost,
                    0 as ExtraBedPrice,
                    COLD_TotalCost roomcost,
                    dbo.ConvertToRMB('USD',COLD_TotalPrice) as roomprice,
                    dbo.ConvertToRMB('USD',(COLD_TotalPrice/1.03))-COLD_TotalCost as roomprofit,
                    SUBSTRING(VendorInfo2.VEI2_CompanyBN,1,50) AS roomprovide,
                    SUBSTRING(COLD_Describe,1,150) roombz,
                    0 as orderstats
                FROM BIZ_ConfirmLineDetail
                INNER JOIN BIZ_ConfirmLineInfo ON COLD_COLI_SN=COLI_SN
                LEFT JOIN BIZ_HotelOrderInfo ON HOI_COLD_SN = COLD_SN
                LEFT JOIN VEndorInfo2 ON COLD_PlanVEI_SN = VEI2_VEI_SN AND VEI2_LGC = 2
                LEFT JOIN Vendorinfo2 AS V2 ON COLD_ServiceSN = V2.VEI2_VEI_SN AND V2.VEI2_LGC = 2
                LEFT JOIN VendorInfo ON COLD_ServiceSN = VEI_SN
                LEFT JOIN cityinfo2 ON vendorinfo.VEI_CII_Name=cityinfo2.CII2_CII_SN AND cityinfo2.CII2_LGC=2
                WHERE COLD_COLI_SN = $coli_sn
                  AND BIZ_ConfirmLineDetail.DeleteFlag = 0
                  AND COLD_ServiceType = 'A'
        ";
        return $this->HT->query($sql)->result();
    }

    /** 非图兰朵供应商的包价线路产品 */
    public function insert_report_tour_others($coli_sn=0)
    {
        $other_tour_cost = $this->get_report_tour_others_cost($coli_sn);
        foreach ($other_tour_cost as $kotc => $votc) {
            if ($this->report_tour_exists($votc->ordernumber, $votc->RPT_COLD_SN) === TRUE) {
                $where = " ordernumber='" . $votc->ordernumber . "' AND RPT_COLD_SN=" . $votc->RPT_COLD_SN;
                $where .= "  AND tourBZ='" . $votc->tourBZ . "' ";
                $update_sql = $this->HT->update_string('tourmanager.dbo.Report_Tour', json_decode(json_encode($votc), TRUE), $where);
                $this->HT->query($update_sql);
            } else {
                $this->HT->insert('tourmanager.dbo.Report_Tour', json_decode(json_encode($votc), TRUE));
            }

        }
        return $this->HT->query("SELECT top 1 * from tourmanager.dbo.report_tour inner join BIZ_ConfirmLineInfo on COLI_ID=ordernumber WHERE COLI_SN=$coli_sn order by orderId desc")->result();
    }
    public function get_report_tour_others_cost($coli_sn=0)
    {
        $sql = "SELECT
                    dbo.BIZ_ConfirmLineInfo.COLI_ID ordernumber,
                    dbo.BIZ_PackageInfo.PAG_Code tourCode,
                    SUBSTRING(dbo.BIZ_PackageInfo.PAG_Title,1,200) tourname,
                    SUBSTRING(CONVERT(varchar,dbo.BIZ_ConfirmLineDetail.COLD_StartDate, 120), 1, 10) AS tourtime,
                    dbo.BIZ_ConfirmLineDetail.COLD_PersonNum tourRSd,
                    dbo.BIZ_ConfirmLineDetail.COLD_ChildNum tourRSx,
                    --@AdultCost,
                    (select top 1 PKP_AdultCost
                     from BIZ_PackagePrice
                     where PKP_PAG_SN=COLD_ServiceSN
                        and PKP_VEI_SN=COLD_PlanVEI_SN
                        and PKP_PersonStart<=isnull(COLD_PersonNum,0)+isnull(COLD_ChildNum,0)
                        and PKP_PersonStop >=isnull(COLD_PersonNum,0)+isnull(COLD_ChildNum,0)
                        and PKP_ValidDate <=   CONVERT(varchar(100),COLD_StartDate,23)
                        and PKP_InvalidDate >= CONVERT(varchar(100),COLD_StartDate,23)
                     ORDER BY PKP_PriceGrade
                        ) as tourCostRsd,
                    --@ChildCost,
                    (select top 1 PKP_ChildCost
                     from BIZ_PackagePrice
                     where PKP_PAG_SN=COLD_ServiceSN
                        and PKP_VEI_SN=COLD_PlanVEI_SN
                        and PKP_PersonStart<=isnull(COLD_PersonNum,0)+isnull(COLD_ChildNum,0)
                        and PKP_PersonStop >=isnull(COLD_PersonNum,0)+isnull(COLD_ChildNum,0)
                        and PKP_ValidDate <=   CONVERT(varchar(100),COLD_StartDate,23)
                        and PKP_InvalidDate >= CONVERT(varchar(100),COLD_StartDate,23)
                     ORDER BY PKP_PriceGrade
                        ) as tourCostRSx,
                    dbo.BIZ_ConfirmLineDetail.COLD_TotalCost tourcost,
                    dbo.BIZ_ConfirmLineDetail.COLD_SN RPT_COLD_SN,
                    dbo.ConvertToRMB('USD',dbo.BIZ_ConfirmLineDetail.COLD_TotalPrice) tourPrice,
                    dbo.ConvertToRMB('USD',dbo.BIZ_ConfirmLineDetail.COLD_TotalPrice)-dbo.BIZ_ConfirmLineDetail.COLD_TotalCost as tourProfit,
                    SUBSTRING(isnull(dbo.VEndorInfo2.VEI2_CompanyBN,'.'),1,50) as tourProvide,
                    SUBSTRING(dbo.BIZ_ConfirmLineDetail.COLD_Describe,1,70) as tourBZ,
                    1 as orderstats
                FROM dbo.BIZ_ConfirmLineDetail
                inner join BIZ_ConfirmLineInfo on COLI_SN=COLD_COLI_SN
                LEFT OUTER JOIN dbo.VEndorInfo2 ON dbo.VEndorInfo2.VEI2_VEI_SN = dbo.BIZ_ConfirmLineDetail.COLD_PlanVEI_SN AND dbo.VEndorInfo2.VEI2_LGC = 2
                INNER JOIN dbo.BIZ_PackageInfo ON dbo.BIZ_ConfirmLineDetail.COLD_ServiceSN = dbo.BIZ_PackageInfo.PAG_SN
                WHERE (dbo.BIZ_ConfirmLineDetail.COLD_ServiceType='D')
                    AND  (dbo.BIZ_ConfirmLineDetail.DeleteFlag = 0)
                    AND (dbo.BIZ_ConfirmLineDetail.COLD_COLI_SN=$coli_sn) ";
        return $this->HT->query($sql)->result();
    }

    /** 单团财务表 */
    public function insert_report_order($report_order_arr=array(), $coli_sn=0, $gri_sn=0)
    {
        $this->HT->query("DELETE from Report_Order where ordernumber = '" . $report_order_arr['ordernumber'] . "' AND orderstats=0 ");
        if ( $this->report_order_exists($report_order_arr['ordernumber'], $gri_sn) === TRUE ) {
            $where = " ordernumber='" . $report_order_arr['ordernumber'] . "' ";
            $update_sql = $this->HT->update_string('tourmanager.dbo.report_order', $report_order_arr, $where);
            $this->HT->query($update_sql);
        } else {
            $this->HT->insert('tourmanager.dbo.report_order', $report_order_arr);
        }
        return $this->get_report_order($report_order_arr['ordernumber']);
    }

    public function get_report_order($coli_id=0)
    {
        return $this->HT->query("SELECT top 1 * from tourmanager.dbo.report_order WHERE ordernumber='$coli_id' and orderstats=1 order by orderID desc")->row();
    }

    public function convert_to_RMB($money=0, $fromCurrency='USD')
    {
        // [dbo].[ConvertToRMB](@TargetCurrency varchar(6), @SourceMoney decimal(18,5))
        return $this->HT->query("SELECT tourmanager.dbo.[ConvertToRMB]('$fromCurrency',$money) as rmb ")->row()->rmb;
    }

    public function get_report_order_xh()
    {
        return $this->HT->query("SELECT MAX(xh)+1 as newxh from report_order")->row()->newxh;
    }

}

/* End of file orderFinance_model.php */
/* Location: ./webht/third_party/trippestOrderSync/models/orderFinance_model.php */
