<?php
/**
 * v2 抄表模块
 */
namespace app\em\controller;
use app\admin\controller\Base;
use app\em\model\Staff;
use app\em\model\Station;
use app\em\model\UseageDetail;
use app\em\validate\UseageGeneralInfoValidate;
use think\facade\Request;
use think\facade\Session;

class Useage extends Base
{
    //获取抄表单列表
    public function index(){
        $map=[];
        //权限检测
        $user = Session::get('user');
        if(!$user['is_admin']){
            $permissionData=check_data();
            if($permissionData){
                $map[]=$permissionData;
            }
        }

        $this->assign('admin',$user['is_admin']);
        $search_text = Request::get('search_text');
        $search_type = Request::get('search_type');
        if($search_text){
            switch ($search_type) {
                case '1':
                    $this->assign('search_text',$search_text);
                    $map[]=['ue.useage_id','like',"%$search_text%"];
                    $this->assign('search_type',$search_type);
                    break;
                case '2':
                    $this->assign('search_text',$search_text);
                    $map[]=['station.station_name','like',"%$search_text%"];
                    $this->assign('search_type',$search_type);
                    break;
                case '3':
                    $this->assign('search_text',$search_text);
                    $map[]=['em.em_numb','like',"%$search_text%"];
                    $this->assign('search_type',$search_type);
                    break;
            }
        }else{
            $this->assign('search_type','');
            $this->assign('search_text','');
        }


        //抄表时间查询条件
        $dateStart = strtotime(Request::get('date_start'));
        $dateEnd = strtotime(Request::get('date_end'));
        //区间查询
        if( !empty($dateStart) && !empty($dateEnd) ){
            $map[] = ['ue.current_date','between',[$dateStart,$dateEnd]];
            $this->assign('date_start',Request::get('date_start'));
            $this->assign('date_end',Request::get('date_end'));
        } elseif (!empty($dateStart) && empty($dateEnd)){
            $map[] = ['ue.current_date','>',$dateStart];
            $this->assign('date_start',Request::get('date_start'));
            $this->assign('date_end','');
        } elseif (empty($dateStart) && !empty($dateEnd)){
            $map[] = ['ue.current_date','<',$dateEnd];
            $this->assign('date_end',Request::get('date_end'));
            $this->assign('date_start','');
        }else{
            $this->assign('date_start','');
            $this->assign('date_end','');
        }
        $page =Request::param('page')?Request::param('page'):1;
        $limit = Request::param('limit')?Request::param('limit'):10;

        $data = (new \app\em\model\Useage)->getCopyList($map,$page,$limit);
        $copyCount = (new \app\em\model\Useage)->getCopyListCount($map);
        if(Request::param('page')){
            return ['code'=>0,'msg'=>'','count'=>$copyCount,'data'=>$data];
        }
        return $this->fetch();
    }

    //生成抄表单
    public function create($detail=false){

        $em_id = Request::param('id');

        if(!(new Em())->checkEmComplete($em_id)){
            $this->error('电表信息不完整,需要补充基础信息','/em');
        }

        $em = (new \app\em\model\Em)->getEmUseageInfoById($em_id,$detail);

        //基站信息
        $station_info = Station::getBaseInfoById($em->station_id);
        $this->assign('station',$station_info);

        //当前用户
        $user  =  Session::get('user');
        $this->assign('uid',$user['user_id']);

        //员工列表
        $this->assign('staffs',(new Staff())->getStaffs($user['is_admin'],'','useage'));
        $this->assign('em',$em);

        if($em->rule->pricing_type == 1){
            $template = 'default';
        } else {
            $template = 'special';
        }

        $this->assign('detail',$detail);
        return $this->fetch($template);
    }

    //保存抄表单
    public function store(){
        //获取表单数据
        $data = Request::post();
        //数据验证
        $validate = new UseageGeneralInfoValidate();
        //根据计量模式 验证去表单数据
        if(!$validate->scene('s'.$data['pricing_type'])->check($data)){
            return json(['status'=>0,'message'=>$validate->getError()]);
        }

        //获取电表基本信息
        $em = (new \app\em\model\Em)->getEmInfoById(['id'=>$data['em_id']],'rule');
        //保存抄表单
        $uModel = new \app\em\model\Useage();
        //如果是普通计量模式
        if($data['pricing_type'] != 1){
            $data['current_sum_numb'] = $data['current_numb'];
            $data['last_sum_numb'] = $data['last_numb'];
        }
        //生成抄表单ID
        $data['useage_id'] = $this->getUId();
        $uModel->save($data);

        //抄表详情更新
        $udModel = new UseageDetail();  //抄表详情模型
        //如果是普通计量模式
        if($data['pricing_type'] == 1){

            //添加抄表详情记录
            $data['type'] = 5;   //保存详情类型 5->default
            $udModel->save($data);

            //更新主表
            $data['type'] = $data['pricing_type'];  //保存峰谷信息
            $data['last_sum_numb'] = $data['last_numb'];
            $data['current_sum_numb'] = $data['current_numb'];
            $uModel->save($data);
        } else {
            $typeArr = [];
            $data['last_sum_numb'] = 0;
            $data['current_sum_numb'] = 0;
            for ($i=0;$i<4;$i++){
                $temp = $data;
                $last_key = 'uType'.($i+1).'_last_numb';
                $curr_key = 'uType'.($i+1).'_current_numb';
                $price_key = 'uType'.($i+1).'_price';

                //组装峰谷信息
                $temp['type'] = $i+1;
                $temp['last_numb'] = $data[$last_key];
                $temp['current_numb'] = $data[$curr_key];
                $temp['price'] = $data[$price_key];

                //抄表汇总记录
                $data['last_sum_numb'] += $temp['last_numb'];
                $data['current_sum_numb'] += $temp['current_numb'];
                $typeArr[] = $temp;
            }

            $udModel->saveAll($typeArr);

            //更新主表
            $data['type'] = $data['pricing_type'];  //保存峰谷信息
            $uModel->save($data);
        }
        return json(['status'=>1,'message'=>'添加抄表记录成功']);
    }

    /**
     * 审核抄表单并生成账单
     */
    public function check(){
        $useage_id = Request::param('useage_id');
        $useage = \app\em\model\Useage::get(['useage_id' => $useage_id]);

        if($useage->status == 2) return json(['status'=>0,'message'=>'该抄表单已经生成了账单']);

        $inv = (new Invoice())->createInvoice($useage_id);
        $useage->status = 2;
        $useage->save();

        //触发销账逻辑
        $result = (new Invoice())->writeOffFromInvoice($inv->invoice_id,$inv->account_id);
        return json(['status'=>1,'message'=>"已审核,并生成账单,$result"]);
        //return json(['status'=>1,'message'=>"已审核,并生成账单"]);
    }

    //获取单号
    private function getUId(){
        $uModel = \app\em\model\Useage::field('id')->order('id desc,create_time desc')->find();
        if(!$uModel) $id = 1;
        else $id = $uModel->id + 1;
        return "CB".date('Ymd').zero($id);
    }

    /**
     * 通过useage_id获取抄表单详情
     * 通过useage_id找到电表类型
     * 通过电表类型判断是否是峰谷表
     * 如果是峰谷表就显示峰谷的详情
     * 如果不是峰谷表就显示单条记录
     */
    public function detail(){
        $uid = Request::param('useage_id');

        $useage = (new \app\em\model\Useage)->alias('u')
                                        ->field('u.*,em.rate')
                                        ->field('emr.pricing_type')
                                        ->leftJoin(['em'],'em.id=u.em_id')
                                        ->leftJoin(['em_rule'=>'emr'],'emr.em_id=em.id')
                                        ->where('u.useage_id','=',$uid)
                                        ->find();


        $em = (new \app\em\model\Em())->getBaseInfo($useage->em_id);


        $user  =  Session::get('user');
        if($useage){
            $this->assign('staffs',(new Staff())->getStaffs($user['is_admin'],$useage->staff_id));
        } else {
            $this->assign('staffs',(new Staff())->getStaffs($user['is_admin']));
        }

        $useage->repo_numb = round(round($useage->current_sum_numb - $useage->last_sum_numb,2) * $useage->rate,2);
        $this->assign('em',$em);
        $this->assign('useage',$useage);

         //判断是否是峰谷表
        if($useage->pricing_type == 2){
            //获取峰谷表详情
            $useage_detail = (new UseageDetail())->where('useage_id','=',$uid)->select()->toArray();
            foreach ($useage_detail as &$ud){
                switch ($ud['type']){
                    case 1:
                        $ud['typeName'] = '尖峰段';
                        break;
                    case 2:
                        $ud['typeName'] = '峰段';
                        break;
                    case 3:
                        $ud['typeName'] = '谷段';
                        break;
                    case 4:
                        $ud['typeName'] = '平段';
                        break;
                    default:
                        $ud['typeName'] = '普通';
                        break;
                }
            }
            $this->assign('useage_detail',$useage_detail);
            return $this->fetch('detail_special');
        } else {
            return $this->fetch('detail');
        }
    }


    public function del(){
        $uid = Request::param('uid');

        $useage = (new \app\em\model\Useage())->get(['useage_id'=>$uid]);
        $useage_details = (new UseageDetail())->select(['useage_id'=>$uid]);
        if(!$useage){
            return json(['status'=>0,'message'=>"删除异常，未找到单据编号，请联系管理员"]);
        }

        if($useage->delete()){
            if(!$useage_details->isEmpty()){
                foreach ($useage_details as $k => $v){
                    unset($useage_details[$k]);
                }
            }
            return json(['status'=>1,'message'=>"删除单据成功"]);
        } {
            return json(['status'=>0,'message'=>"删除异常，单据删除失败，请联系管理员"]);
        }
    }
}