<?php
/**
 * Created by PhpStorm.
 * User: chouchou
 * Date: 2019-6-25
 * Time: 23:30
 */

namespace app\admin\controller;

//账单控制器
use app\admin\model\CopyModel;
use app\admin\model\OrderModel;
use app\admin\model\StatementModel;
use app\admin\validate\StatementAddValidate;
use think\facade\Request;

class Statement extends Base
{
    //添加 编辑
    //首次 多次
    public function create($id){
        //抄表单信息 通过cid查询 得到本次抄表的基本信息与上次抄表的基本信息或电表初始值
        $copy = CopyModel::getCopyEmInfoByCid($id);

        //查询上次信息
        $statement = StatementModel::getStatementByCpId($id);

        //身份信息
        $identity = (new Staff)->getIdentity();
        $this->assign('iden',$identity);

        $order = OrderModel::get(['cp_id'=>$id]);
        $this->assign('order',$order);

        $this->assign('statement',$statement);

        $this->assign('copy',$copy);
        return $this->fetch('add');
    }

    public function store(){
        $data = Request::post();
        $validate = new StatementAddValidate();

        if(Request::post('state_id')){
            $state = StatementModel::find(Request::post('state_id'));
        } else {
            $state = new StatementModel();
        }

        if($data['emt_id'] == 1 || $data['emt_id'] == 3){
            if(!$validate->scene('common')->check($data)){
                return jsonErr($validate->getError());
            }
        } elseif($data['emt_id'] == 2 || $data['emt_id'] == 4){
            if(!$validate->scene('card')->check($data)){
                return jsonErr($validate->getError());
            }
            $state->recharge = $data['recharge'] ?: '';
            $state->power_over = $data['power_over'] ?: '';
        }

        $state->emt_id = $data['emt_id'];
        $state->copy_id = $data['copy_id'];
        $state->photo_id = $data['photo_id'];
        $state->repo_power = $data['repo_power'];
        $state->yd_unit = $data['yd_unit'] ?: '1.123';
        $state->financ_unit = $data['financ_unit'] ?: '1.123';
        $state->financ_pay = $data['financ_pay'];
        $state->remark = $data['remark'];

        if($state->save()){
            //更新order状态
            $order = OrderModel::order('id desc')->get(['cp_id'=>$data['copy_id']]);
            $order->statement_id = $state->id;

            //更新抄表单数据
            $copy = CopyModel::get($data['copy_id']);

            $copy->photo_id = $data['em_photo_id'];
            $copy->save();


            if($order->save()){
                return jsonSuc('保存账单成功');
            } else {
                return jsonErr('更新订单信息失败');
            }

        } else {
            return jsonErr('保存账单异常');
        }
    }

    public function upCpPhoto(){
        $file = Request::file('copy_photo');
        $upload = new Upload($file,1);
        $result = $upload->upload();

        if(!empty($result)){
            return jsonSuc('抄表单附件上传成功',$result);
        } else {
            return jsonErr($result);
        }
    }
}