<?php
namespace app\em\controller;
use app\admin\controller\Base;
use app\em\model\EmInvoice;
use app\em\model\EmPaymentReceipt;
use app\em\model\EmReceiptType;
use app\em\validate\AddReceiptValidate;
use think\facade\Request;

/**
 * 缴费发票
 * Class Receipt
 * @package app\em\controller
 */
class Receipt extends Base
{
    //显示缴费凭证表单
    public function create(){
        $payment_id = Request::param('payment_id');
        //将缴费应缴金额传递给模板
        $balance = (new EmInvoice())->alias('ei')
            ->leftJoin(['em_payment_invoice'=>'epi'],'epi.invoice_id=ei.invoice_id')
            ->where('epi.payment_id','=',$payment_id)
            ->where('ei.payment_balance','>',0)
            ->sum('ei.payment_balance');
        $this->assign('balance',$balance?:0);
        $this->assign('payment_id',$payment_id);
        $types = EmReceiptType::select();
        $this->assign('types',$types);
        return $this->fetch();
    }

    public function store(){
        $data = Request::post();
        $validata = new AddReceiptValidate();

        if(!$validata->check($data)){
            return json(['status'=>0,'message'=>$validata->getError()]);
        }

        //获取certId
        $data['receipt_id'] = $this->createReceiptId();

        //保存凭证
        $receiptModel = new EmPaymentReceipt();
        if($receiptModel->save($data)){
            //更新缴费单状态
            return json(['status'=>1,'message'=>'上传发票成功']);
        } else {
            return json(['status'=>0,'message'=>'添加发票失败']);
        }
    }

    //查看列表
    public function receipts(){
        $payment_id = Request::param('payment_id');
        $list = EmPaymentReceipt::with('file,types')->where('payment_id','=',$payment_id)->order('receipt_id asc')->select();
        foreach ($list as &$item){
            if(!empty($item->file->src)){
                $item->file->src = ltrim($item->file->src,'.');
            }
        }
         $this->assign('data',$list);
        return $this->fetch('list');
    }

    //创建凭证id
    private function createReceiptId(){
        $epr = EmPaymentReceipt::field('id')->order('id desc,create_time desc')->find();
        if(!$epr) $id = 1;
        else $id = $epr->id + 1;
        return "RT".date('Ymd').zero($id);
    }
}