<?php

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

class Dms_model extends CI_Model {

    function __construct() {
        parent::__construct();
        $this->HT = $this->load->database('TOURMANAGER_LOCAL', TRUE);
		$this->INFO = $this->load->database('INFORMATION_LOCAL', TRUE);
    }

    /**
     * @description: 
     * @return {*}
     * @Date Changed: 
     */    
    function Login($username,$password){
        $sql = "select top 1 dt_id,dt_username,dt_payrule,dt_usertype,dt_HtId from DMS_Distributor ";
        $sql .= " where dt_status=1 and  dt_username=? and dt_password=? ";
        $query = $this->INFO->query($sql,array($username,$password));
        if ($query->num_rows() > 0) {
            return $query->row();
        }else{
            return null;
        }
    }

    /**
     * 订单列表
     */
    function trainorder($arrKeyword){
        $htid = $arrKeyword->htid ==false?-1:$arrKeyword->htid;
        $page = $arrKeyword->page ==false?0:$arrKeyword->page;
        $pagesize = $arrKeyword->per_page>0 ? $arrKeyword->per_page :20;
        if ($page < 1) {
            $page = 1;
        }  
        

        $sql = "   SELECT * from (                      
            select row_number() over (order by COLI_ApplyDate desc) as rownumber, COLI_SN,COLI_ID,COLI_ApplyDate,COLI_servicetype,COLI_State,COLI_sourcetype,COLI_GUT_SN
            ,GUT_Title,GUT_FirstName,GUT_LastName
            ,tb2.*
            from BIZ_ConfirmLineInfo bci
            inner join BIZ_Guest bg on bci.COLI_GUT_SN = bg.GUT_SN 
            outer apply ( select top 1 COLD_COLI_SN,FlightsNo,DepartureCity,ArrivalCity from BIZ_ConfirmLineDetail inner join BIZ_FlightsOrderInfo 
            on FOI_COLD_SN=COLD_SN where COLD_COLI_SN=bci.COLI_SN) tb2 
            where COLI_State in(8,9,61,62)              
            AND  COLI_servicetype='2' 
            and isnull(DeleteFlag,0)<>1 ";
        
        if ($htid == 32083 || $htid==32084){
            $sql .= " and  COLI_sourcetype in(32083,32084)  ";
        }else {
            $sql .= "   and COLI_sourcetype ='".$htid."'";
        }
        
        $sql .= "    )t   ";
       

        $sql2 = $sql."  Where t.rownumber > ? And t.rownumber <= ?";

        $begin = ($page - 1) * $pagesize;
        $end = $begin + $pagesize;
        $qurey = $this->HT->query($sql);
        $count = $qurey->num_rows(); //总记录数

        $qurey2 = $this->HT->query($sql2, array($begin, $end));
        //return 数据和总数
        return array('data' => $qurey2->result(), 'total' => $count);
    }

    /**
     * @description: 
     * @param {*} $arrKeyword
     * @return {*}
     * @Date Changed: 
     */    
    function get_DmList($arrKeyword){
        $s_username = $arrKeyword->s_username ==false?"": trim($arrKeyword->s_username);
        $s_ename = $arrKeyword->s_ename ==false?"": trim($arrKeyword->s_ename);
        $page = $arrKeyword->page ==false?0:$arrKeyword->page;
        $pagesize = $arrKeyword->per_page>0 ? $arrKeyword->per_page :20;
        if ($page < 1) {
            $page = 1;
        }    

        $sql = "SELECT * from (
                    SELECT row_number() over (order by dt_id desc) as rownumber,dt_id,dt_username,dt_password,dt_HTid,dt_payrule,dt_usertype,isnull(dt_status,1) as dt_status
                    ,(select dpr_rule from dms_payrule where dpr_id = dt_payrule) as dpr_rule
                    ,(select syc2_CodeDiscribe  FROM tourmanager.dbo.V_System_Code where SYC_Type=32 AND LGC_LGC=2 AND SYC_SN=dt_HtId) as dmsName
                    ,isnull((select SUM(dp_paymoney) from DMS_PayRecord where dp_HtId=dt_HtId and dp_status>0),0) as TrainPaySum
                    from DMS_Distributor
                )t  where 1=1 ";
        if ($s_username!=""){
            $sql .= " and dt_username like '%".$s_username."%' ";
        }    
        if ($s_ename!=""){
            $sql .= " and dmsName like '%".$s_ename."%' ";
        }   
         $sql2 = $sql . "  and t.rownumber > ? And t.rownumber <= ? order by dt_id desc";

         $begin = ($page - 1) * $pagesize;
         $end = $begin + $pagesize;
         $qurey = $this->INFO->query($sql);
         $count = $qurey->num_rows(); //总记录数
 
         $qurey2 = $this->INFO->query($sql2, array($begin, $end));
         //计算订单总额
         $returndata = $qurey2->result();
         foreach ($returndata as $item) {
            $paydetail = $this->get_paydetail($item->dt_HTid);
            $trainOrderCount = $paydetail->count;
            $trainOrderTotal = $paydetail->total;
            $item->trainOrderCount = $trainOrderCount;
            $item->trainOrderTotal = $trainOrderTotal;
         }
         //return 数据和总数
         return array('data' => $returndata, 'total' => $count);
    }

    /**
     * 获取支付规则列表数据
     */
    function get_payrule(){
        $sql = "select * from dms_payrule ";
        $query = $this->INFO->query($sql);
        return $query->result();
    }

    function get_dmseasy(){
        $sql = "  select * from DMS_Distributor where dt_usertype='distributor'
        order by dt_username ";
        $query = $this->INFO->query($sql);
        return $query->result();
    }


    /**
     * 获取某一个分销商的所有财务信息
     */
    function get_paydetail($id){
        $sql = "select count(*) as oCount from BIZ_ConfirmLineInfo where COLI_State in(8,9,61,62) AND  COLI_servicetype='2' and isnull(DeleteFlag,0)<>1 ";
        if ($id == 32083 || $id==32084){
            $sql .= " and COLI_sourcetype in(32083,32084) ";
        }else{
            $sql .= " and COLI_sourcetype ='".$id."' ";
        }
        $query = $this->HT->query($sql);
        if ($query->num_rows()>0){
            $count = $query->row()->oCount;
        }else{
            $count = 0;
        }

        //付款规则
        $sql = "select top 1 dt_payrule from DMS_Distributor where dt_htid='".$id."'";
        $query = $this->INFO->query($sql);
        if ($query->num_rows()>0){
            $rule = $query->row()->dt_payrule;
        }else{
            $rule = 0;
        }

        if ($rule == 1){
            $total = $count * 1;
        }else if ($rule == 2 ){
            $total = $count * 2;
        }
        else if ($rule == 3 ){
            //按人数来算 ,1美元/人
            $rSql = "select isnull(sum(COLD_PersonNum),0) as sumP from BIZ_ConfirmLineDetail
             inner join BIZ_FlightsOrderInfo on FOI_COLD_SN=COLD_SN 
             where COLD_COLI_SN in( select COLI_SN from BIZ_ConfirmLineInfo where COLI_sourcetype='".$id."' and COLI_State in(8,9,61,62) 
             AND  COLI_servicetype='2' and isnull(DeleteFlag,0)<>1)";
             $queryR = $this->HT->query($rSql);
             if ($queryR->num_rows()>0){
                $total = $queryR->row()->sumP;
             }else{
                $total = 0 ;
             }
        }else {
            $total = 0;
        }

        //已支付

        $sql = "select  isnull(SUM(dp_paymoney),0) as osum  from DMS_PayRecord where dp_HtId= '".$id."'";
        $query = $this->INFO->query($sql);
        if ($query->num_rows()>0){
            $sum = $query->row()->osum;
        }else{
            $sum = 0;
        }

        $result = new stdClass();
        $result->count = $count;
        $result->total = round($total,2);
        $result->sum = round($sum,2);

        return $result;
    }

    function addsave($formData){
       
        $username = isset($formData->username)?$formData->username:"";
		$password = isset($formData->password)?$formData->password:"";
        $Htid = isset($formData->HtId)?$formData->HtId:0;
		$payrule = isset($formData->payrule)?$formData->payrule:1;
		$usertype = isset($formData->usertype)?$formData->usertype:"";
        $result = new stdClass;
        if ($usertype!=""){ //用户类型不为空才能进行添加
             //先判断htid是否重复，重复的话不允许添加.管理员不需要判断
             $sql = "select * from DMS_Distributor where dt_HtId=? and dt_usertype='distributor'";
             $query = $this->INFO->query($sql, array($Htid));
             if ($query->num_rows() > 0) {
                $result->status = 0;
                $result->msg = "翰特编码重复，不允许添加！";
            }else{
                $sql = "insert into DMS_Distributor (dt_username,dt_password,dt_HtId,dt_payrule,dt_usertype) values (?,?,?,?,?)";
                $query = $this->INFO->query($sql ,array($username,$password,$Htid,$payrule,$usertype));
                if ($query === true){
                    $result->status = 1;
                    $result->msg = "数据添加成功！";
                }else{
                    $result->status = 0;
                    $result->msg = "数据插入数据库失败，请联系管理员！";
                }
                
            }


        }else{
            $result->status = 0;
            $result->msg = "用户类型错误！";
        }        

        return $result;
    }

    /**
     * 保存修改
     */
    function editsave($formData){
        $username = isset($formData->username)?$formData->username:"";
		$password = isset($formData->password)?$formData->password:"";
        $Htid = isset($formData->HtId)?$formData->HtId:0;
		$payrule = isset($formData->payrule)?$formData->payrule:1;
		$usertype = isset($formData->usertype)?$formData->usertype:"";
        $id = isset($formData->id)?$formData->id:0;
        $result = new stdClass;
        if ($usertype!=""){ //用户类型不为空才能进行添加
             //先判断htid是否重复，重复的话不允许添加.管理员不需要判断
             $sql = "select * from DMS_Distributor where dt_HtId=? and dt_usertype='distributor' and dt_id<>?";
             $query = $this->INFO->query($sql, array($Htid,$id));
             if ($query->num_rows() > 0) {
                $result->status = 0;
                $result->msg = "翰特编码重复，不允许修改！";
            }else{
                $sql = "update DMS_Distributor set dt_username=?,dt_password=?,dt_HtId=?,dt_payrule=?,dt_usertype=? where dt_id = ?";
                $query = $this->INFO->query($sql ,array($username,$password,$Htid,$payrule,$usertype,$id));
                if ($query === true){
                    $result->status = 1;
                    $result->msg = "数据修改成功！";
                }else{
                    $result->status = 0;
                    $result->msg = "修改数据库失败，请联系管理员！";
                }
                
            }


        }else{
            $result->status = 0;
            $result->msg = "用户类型错误！";
        }        

        return $result;
    }


    /**
     * @description: 获取供应商详细信息
     * @param {*} $id
     * @return {*}
     * @Date Changed: 
     */    
    function getDmsDetail($id){
        $sql = "select top 1 * from DMS_Distributor where dt_id = ? ";
        $query = $this->INFO->query($sql ,array($id));
        return $query->result();
        
    }

    /**
     * @description: 删除分销商
     * @param {*} $id
     * @return {*}
     * @Date Changed: 
     */    
    function dmdDelete($id){
        $sql = " delete from DMS_Distributor where dt_id = ? ";
        $qurey = $this->INFO->query($sql ,array($id));
        $result = new stdClass;
        if ($qurey){
            $result->status = 1;
            $result->msg = "数据删除成功！";
        }else{
            $result->status = 0;
            $result->msg = "数据删除失败，请联系管理员!";
        }
        return $result;
    }

    /**
     * 支付记录
     */
    function payRecord($arrKeyword){
        $htid = $arrKeyword->htid ==false?0:$arrKeyword->htid;
        $page = $arrKeyword->page ==false?0:$arrKeyword->page;
        $pagesize = $arrKeyword->per_page>0 ? $arrKeyword->per_page :20;
        if ($page < 1) {
            $page = 1;
        }    

        $sql = "  SELECT * from (
            SELECT row_number() over (order by dp_id desc) as rownumber,*
            ,(select syc2_CodeDiscribe  FROM tourmanager.dbo.V_System_Code where SYC_Type=32 AND LGC_LGC=2 AND SYC_SN=dp_HtId) as dmsName
            from DMS_PayRecord
            where dp_HtId=?
        )t  ";


        $sql2 = $sql."  Where t.rownumber > ? And t.rownumber <= ?";

        $begin = ($page - 1) * $pagesize;
        $end = $begin + $pagesize;
        $qurey = $this->INFO->query($sql,array($htid));
        $count = $qurey->num_rows(); //总记录数

        $qurey2 = $this->INFO->query($sql2, array($htid,$begin, $end));
        //return 数据和总数
        return array('data' => $qurey2->result(), 'total' => $count);


    }

    /**
     * @description: 
     * @return {*}
     * @Date Changed: 
     */    
    function payrecord_addsave($formData){
        $paymoney = isset($formData->paymoney)?$formData->paymoney:0;
		$currency = isset($formData->currency)?$formData->currency:"USD";
        $HtId = isset($formData->HtId)?$formData->HtId:0;
		$paytype = isset($formData->paytype)?$formData->paytype:"Train";
        $filluser = isset($formData->filluser)?$formData->filluser:0;
        $result = new stdClass;
        if ($HtId!=0){ //必须有翰特ID才能进行添加

            $sql = " insert into DMS_PayRecord (dp_HtId,dp_paymoney,dp_currency,dp_paytype,dp_addtime,dp_filluser,dp_status) values(?,?,?,?,GETDATE(),?,1)";
            $query = $this->INFO->query($sql ,array($HtId,$paymoney,$currency,$paytype,$filluser));
            if ($query === true){
                $result->status = 1;
                $result->msg = "数据添加成功！";
            }else{
                $result->status = 0;
                $result->msg = "数据插入数据库失败，请联系管理员！";
            }
                
        


        }else{
            $result->status = 0;
            $result->msg = "企业的翰特ID有错误！";
        }        

        return $result;
    }


    /***
     * 
     */
    function payrecord_delete($id,$htid){
        $sql = "  update DMS_PayRecord set dp_status = 0 where dp_id=? and dp_HtId=? ";
        $qurey = $this->INFO->query($sql ,array($id,$htid));
        $result = new stdClass;
        if ($qurey){
            $result->status = 1;
            $result->msg = "数据删除成功！";
        }else{
            $result->status = 0;
            $result->msg = "数据删除失败，请联系管理员!";
        }
        return $result;
    }

}