<?php
namespace app\em\model;
class EmInvoice extends Base
{
    protected $table = 'em_invoice';

    /**
     * 首页列表
     * @param int $page
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getList($page = 0){
        $config = !empty($config) ?: [
            'list_rows'=>30,
            'page'=> $page,
            'type'     => '\app\extend\PageLayUi',
            'var_page' => 'page'
        ];
        $data = self::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')
            ->paginate($config);
        return $data;
    }
    //账单查询+search
    public function getInvoiceList($map,$Nowpage,$limits){
        $data = self::alias('inv')
                ->field('inv.*')
                ->field('station.station_name,em.em_numb')
                ->field('eu.last_sum_numb,eu.current_sum_numb,eu.current_date,FROM_UNIXTIME(eu.current_date,"%Y-%m-%d %H:%i:%S") as now_date')
                ->join(['em_invoice_useage'=>'eiu'],'eiu.invoice_id = inv.invoice_id')
                ->join(['em_useage'=>'eu'],'eu.useage_id = eiu.useage_id')
                ->join(['em_account'=>'ea'],'ea.account_id = inv.account_id')
                ->join(['em'],'em.id=ea.em_id')
                ->join(['station_info'=>'station'],'station.station_id=em.station_id')
                ->where($map)
                ->page($Nowpage, $limits)
                ->order('inv.id desc')
                ->select()
                ->toarray();


        foreach ($data as &$item){
            if($item['payment_balance'] == 0){
                $item['paid_amount'] = $item['payment_amount'] ;
            } else {
                $item['paid_amount'] = round($item['payment_amount'] - $item['payment_balance'],3);
            }

            if($item['settle_balance'] == 0){
                $item['sett_amount'] = $item['settle_amount'] ;
            } else {
                $item['sett_amount'] = round($item['settle_amount'] - $item['settle_balance'],3);
            }
        }
        return $data;
    }
    public function getInvoiceCount($map){
        $data = self::alias('inv')
                ->field('inv.*')
                ->field('station.station_name,em.em_numb')
                ->field('eu.last_sum_numb,eu.current_sum_numb,eu.current_date')
                ->join(['em_account'=>'ea'],'ea.account_id = inv.account_id')
                ->join(['em'],'em.id=ea.em_id')
                ->join(['em_invoice_useage'=>'eiu'],'eiu.invoice_id = inv.invoice_id')
                ->join(['em_useage'=>'eu'],'eu.useage_id = eiu.useage_id')
                ->join(['station_info'=>'station'],'station.station_id=em.station_id')
                ->where($map)
                ->count();
        return $data;
    }
    //通过invoice_id查询列表数据
    public function getListByInvIds($ids){
        $data = self::alias('inv')
            ->field('inv.*')
            ->field('station.station_name')
            ->field('em.em_numb')
            ->join(['em_account'=>'ea'],'ea.account_id = inv.account_id')
            ->join(['em'],'em.id=ea.em_id')
            ->join(['station_info'=>'station'],'station.station_id=em.station_id')
            ->where(['inv.invoice_id'=>$ids])
//            ->where('inv.payment_balance','neq',0)
            ->select();
        return $data;
    }

    //账单详情
    public function getInvoiceDetail($id){
        //当前账单对象
        if(strstr($id,'ZD')){
            $inv = self::alias('in')
                ->field('in.*,r.src')
                ->leftJoin(['receipt'=>'r'],'r.id = in.cert_id')
                ->get(['invoice_id'=>$id]);
        } else {
            $inv = self::alias('in')
                ->field('in.*,r.src')
                ->leftJoin(['receipt'=>'r'],'r.id = in.cert_id')
                ->get($id);
        }

        //查询抄表单ID
        $eiu = EmInvoiceUseage::where(['invoice_id'=>$inv->invoice_id])->find();

        //查询抄表信息
        $useage = Useage::get(['useage_id'=>$eiu->useage_id]);

        if($useage->photo_id) {
            $receipt = Receipt::get(['id'=>$useage->photo_id]);
            if($receipt) $useage['photo'] = $receipt;
        } else {
            $useage['photo'] = [];
        }

        //获取电表信息
        $em = Em::with('rule')->field('id,station_id,em_numb,em_type_id,rate')->where(['id'=>$useage->em_id])->find();

        $emr = EmRule::field('charge_type,pay_price,settle_price')->where(['em_id'=>$em->id])->order('id desc,create_time desc')->find();
        //电表类型
        $emt = EmType::field('name as typeName')->where(['id'=>$em->em_type_id])->find();

        $em->typeName = $emt['typeName'];
        if($emr->charge_type == 1){
            $em->chargeType = '读表';
        } else if($emr->charge_type == 2){
            $em->chargeType = '包月';
        } else if($emr->charge_type == 3){
            $em->chargeType = '包年';
        }
        //获取基站信息
        $station = Station::field('station_name,station_sp_code')->where(['station_id'=>$em->station_id])->find();
        //组合
        $inv->em = $em;
        $inv->em->emr = $emr;
        $inv->station = $station;
        $inv->useage = $useage;

        $inv->payStatus = getInvoicesStatusName($inv->status,0);
        $inv->settleStatus = getInvoicesStatusName($inv->status,1);


        //峰谷表
        if($inv['type'] != 5){
            $ud = UseageDetail::field('*,case type
                            when 1 then "尖峰段"
                            when 2 then "峰段"
                            when 3 then "谷段"
                            when 4 then "平段"
                            else "普通" end as typeName
                            ')
                            ->where(['useage_id'=>$useage->useage_id])->select();
            $totle = [];
            $totle['typeName'] = '汇总';
            $totle['rate'] = $inv->rate;

            $totle['last_numb'] = $inv->rate;
            $totle['price'] = '/';
            $totle['status'] = parseStatus($inv->status,1);
            $totle['current_numb'] = 0;
            $totle['repo_numb'] = 0;
            $totle['amount'] = $totle['settle_amount'] = 0;
            $totle['settle_price'] = ($inv->em->emr->settle_price?:0) * $inv->em->rate;
            $totle['settle_status'] = parseStatus($inv->status,2);

             //峰谷表与普通抄表
            if($ud) {
                foreach ($ud as $u){
                    $u->rate = $inv->rate;
                    $u->repo_numb = $u->current_numb - $u->last_numb;
                    $u->amount = $u->repo_numb * $u->price;
                    $totle['last_numb'] += $u->last_numb;
                    $totle['current_numb'] += $u->current_numb;
                    $totle['repo_numb'] += $u->repo_numb;
                    $totle['amount'] += $u->amount;
                    $totle['settle_amount'] += $u->repo_numb*$totle['settle_price'];
                    if($inv->em->emr->settle_price != ''){
                        $totle['settle_amount'] = $totle['repo_numb'] * $totle['settle_price'];
                    }
                    else{
                        $totle['settle_amount'] = $inv->settle_amount ?: 0;
                    }
                }
                $inv->useage->ud = $ud;
            } else { //包年包月
                $totle['price'] = $inv->em->emr->price;
                $totle['settle_price'] = $inv->em->emr->settle_price;
                $totle['last_numb'] = $inv->useage->last_numb;
                $totle['current_numb'] = $inv->useage->current_numb;
                $totle['repo_numb'] = $totle['current_numb']-$totle['last_numb'];
                $totle['amount'] = $totle['repo_numb'] * $totle['price'];
                if($inv->em->emr->settle_price != ''){
                    $totle['settle_amount'] = $totle['repo_numb'] * $totle['settle_price'];
                }
                else{
                    $totle['settle_amount'] = $inv->settle_amount ?: 0;
                }
            }
            $inv->useage->totle = $totle;
        } else {
            $totle = [];
            if($inv->em->emr->settle_price != ''){
                $totle['settle_amount'] = $inv->em->emr->settle_price * $inv->repo_numb ;
                $totle['settle_amount'] = round($totle['settle_amount'],3);
            }
            else{
                $totle['settle_amount'] =  0;
            }
        }

        if($inv->payment_balance == 0){
            $inv->paid_amount = $inv->payment_amount;
        } else {
            $inv->paid_amount = $inv->payment_amount - $inv->payment_balance;
        }

        if($inv->settle_balance == 0){
            $inv->sett_amount = $inv->settle_amount;
        } else {
            $inv->sett_amount = $inv->settle_amount - $inv->settle_balance;
        }

        return $inv;
    }

    public function photo(){
        return $this->belongsTo('Receipt','cert_id');
    }
}