<?php


namespace app\em\model;


class EmSettle extends Base
{

    public function getSettleDateAttr($val){
        return date('Y-m-d H:i:s',$val);
    }
    public function setSettleDateAttr($val){
        return strtotime($val);
    }

    //结算单+search
    public function getSettleList($map,$Nowpage,$limits){
    //先找到账单
    $data = self::alias('settle')
        ->field('settle.*')
        ->field('case settle.status 
                when 0 then "未结算" 
                when 1 then "已结算" 
                when 2 then "已上结算发票" 
                when 3 then "凭证完整"
                when 4 then "已审核"
                end as status')
        ->field('esi.invoice_id,em.em_numb,r.region_name,station.station_name')
        ->join(['em_settle_invoice'=>'esi'],'esi.settle_id = settle.settle_id')
        ->join(['em_invoice'=>'inv'],'esi.invoice_id = inv.invoice_id')
        ->join(['em_account'=>'ea'],'ea.account_id = settle.account_id')
        ->join(['em'],'em.id=ea.em_id')
        ->join(['station_info'=>'station'],'station.station_id=em.station_id')
        ->join(['region'=>'r'],'station.area_id = r.id')
        ->where($map)
        ->order('settle.id desc')
        ->page($Nowpage, $limits)
        ->select()
        ->toarray();
    return $data;
}
    public function getSettleCount($map){
        //先找到账单
        $data = self::alias('settle')
            ->field('settle.*')
            ->field('esi.invoice_id')
            ->field('em.em_numb')
            ->field('r.region_name')
            ->join(['em_settle_invoice'=>'esi'],'esi.settle_id = settle.settle_id')
            ->join(['em_invoice'=>'inv'],'esi.invoice_id = inv.invoice_id')
            ->join(['em_account'=>'ea'],'ea.account_id = settle.account_id')
            ->join(['em'],'em.id=ea.em_id')
            ->join(['station_info'=>'station'],'station.station_id=em.station_id')
            ->join(['region'=>'r'],'station.area_id = r.id')
            ->where($map)
            ->count();

        return $data;
    }
    //通过结算单id返回结算单关联账单信息
    public function getInvsInfo($settle_id){
        //1.获取所关联账单的账单id,通过账单id查询账单信息
        $invIdArr = EmSettleInvoice::field('invoice_id')->where('settle_id','=',$settle_id)->select()->toArray();

        //降维
        $invArr = [];
        foreach ($invIdArr as $inv){
            $invArr[] = $inv['invoice_id'];
        }
        $invModel = new EmInvoice();
        $invs = $invModel->alias('inv')
            ->field('inv.*')
            ->field('station.station_name')
            ->field('em.em_numb')
            ->leftJoin(['em_invoice_useage'=>'eiu'],'eiu.invoice_id=inv.invoice_id')
            ->leftJoin(['em_useage'=>'eu'],'eu.useage_id = eiu.useage_id')
            ->leftJoin(['em'],'em.id=eu.em_id')
            ->leftJoin(['station_info'=>'station'],'station.station_id=em.station_id')
            ->where(['inv.invoice_id'=>$invArr])
            ->select();
        return $invs;
    }
}