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

class ReceiptSettle extends Base
{
//显示缴费凭证表单
    public function create(){
        $settle_id = Request::param('settle_id');
        $balance = (new EmInvoice())->alias('ei')
            ->leftJoin(['em_settle_invoice'=>'epi'],'epi.invoice_id=ei.invoice_id')
            ->where('epi.settle_id','=',$settle_id)
            ->where('ei.settle_balance','>',0)
            ->sum('ei.settle_balance');
        $this->assign('balance',$balance?:0);
        $this->assign('settle_id',$settle_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 EmSettleReceipt();
        if($receiptModel->save($data)){
            //更新缴费单状态
            return json(['status'=>1,'message'=>'上传发票成功']);
        } else {
            return json(['status'=>0,'message'=>'添加发票失败']);
        }
    }

    //查看列表
    public function receipts(){
        $settle_id = Request::param('settle_id');
        $list = EmSettleReceipt::with('file,types')->where('settle_id','=',$settle_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 = EmSettleReceipt::field('id')->order('id desc,create_time desc')->find();
        if(!$epr) $id = 1;
        else $id = $epr->id + 1;
        return "JSRT".date('Ymd').zero($id);
    }
}