<?php

/**
 * v2 电表模块
 */
namespace app\em\controller;

use app\admin\controller\Base;
use app\admin\model\DepartmentModel;
use app\admin\model\ElectricMeter;
use app\admin\model\ElectricMeterType;
use app\admin\model\OperatorModel;
use app\admin\model\StaffModel;
use app\em\model\Dc;
use app\em\model\EmList;
use app\em\model\EmRule;
use app\em\validate\EmAddBaseInfoValidate;
use app\em\validate\EmAddRuleValidate;
use think\Exception;
use think\facade\Request;
use think\facade\Session;

class Em extends Base
{
    /**
     * 电表列表
     */
    public function index(){
        $map=[];
        //权限检测
        $user = Session::get('user');
        if(!$user['is_admin']){
            $permissionData=check_data();
            if($permissionData){
                $map[]=$permissionData;
            }
        }
        $search_text = Request::param('search_text');
        $search_type = Request::param('search_type');
        if($search_text){
            switch ($search_type) {
                case '1':
                    $this->assign('search_text',$search_text);
                    $map[]=['s.station_name','like',"%$search_text%"];
                    $this->assign('search_type',$search_type);
                    break;
                case '2':
                    $this->assign('search_text',$search_text);
                    $map[]=['s.station_sp_code','like',"%$search_text%"];
                    $this->assign('search_type',$search_type);
                    break;
                case '3':
                    $this->assign('search_text',$search_text);
                    $map[]=['s.proj_number','like',"%$search_text%"];
                    $this->assign('search_type',$search_type);
                    break;
                case '4':
                    $this->assign('search_text',$search_text);
                    $map[]=['em.em_numb','like',"%$search_text%"];
                    $this->assign('search_type',$search_type);
                    break;
                case '5':
                    $this->assign('search_text',$search_text);
                    $map[]=['em.qrcode','like',"%$search_text%"];
                    $this->assign('search_type',$search_type);
                    break;
                case '6':
                    $this->assign('search_text',$search_text);
                    $map[]=['d.rent','like',"%$search_text%"];
                    $this->assign('search_type',$search_type);
                    break;
            }
        }else{
            $this->assign('search_type','');
            $this->assign('search_text','');
        }
        $operator =  Request::param('operator');
        if($operator){
            $map[] = ['s.original_sp_id','=',$operator];
            $this->assign('operator',$operator);
        }else{
            $this->assign('operator','');
        }
        $area_id =Request::param('area_id');
        if($area_id){
            $map[] = ['s.area_id','=',$area_id];
            $this->assign('area_id',$area_id);
        }else{
            $this->assign('area_id','');
        }
        $page =Request::param('page')?Request::param('page'):1;
        $limit = Request::param('limit')?Request::param('limit'):10;

        $emModel = new EmList();
        $list = $emModel->getEmList($map,$page,$limit);
        $emCount= $emModel->getEmListCount($map);
        if(Request::param('page')){
            return ['code'=>0,'msg'=>'','count'=>$emCount,'data'=>$list];
        }
        $region=new ElectricMeter();
        $operator=new OperatorModel();
        $operators = OperatorModel::field('operator_id,operator_name')->where('operator_state','=',1)->select()->toArray();
        $this->assign('regions',getTree($region->regions()));
        $this->assign('operators',$operators);
        return $this->fetch();
    }

    /**
     * 添加电表页面
     */
    public function create(){
        $sid = Request::param('sid');
        //$sid 验证
        //获取基站基本信息
        $station_info = \app\em\model\Station::getBaseInfoById($sid);
        $this->assign('station',$station_info);

        //获取电表类型
        $emType = ElectricMeterType::select();
        $this->assign('eType',$emType);

        //获取员工信息
        $user  =  Session::get('user');
        if($user['is_admin']){
            $staffs = StaffModel::field('id,name')->select()->toArray();
        } else {
            $staff = StaffModel::find($user['user_id'])->toArray();
            $dIds = (new DepartmentModel)->getNodeIds($staff['d_id']);
            $staffs = StaffModel::field('id,name')->where('d_id','in',$dIds)->select()->toArray();
        }
        $this->assign('users',$staffs);
        $this->assign('uid',$user['user_id']);

        return $this->fetch();
    }

    /**
     * 保存数据
     */
    public function store(){
        //数据验证
        $data = Request::post();

        //新增
        if(!isset($data['em_id'])){
            $em = \app\em\model\Em::get(['em_numb'=>$data['em_numb']]);
            if($em) return json(['status'=>0,'message'=>'电表号已经存在']);
        }

        //判断基础信息类别
        $baseValidate = new EmAddBaseInfoValidate();
        $type = 's'.$data['em_type_id'];
        if(!$baseValidate->scene($type)->check($data)){
            return json(['status' => 0,'message'=>$baseValidate->getError()]);
        }

        //判断缴费模式
        $ruleValidate = new EmAddRuleValidate();
        if($data['charge_type'] == 1){
            if(!$ruleValidate->scene('s1')->check($data)){
                return json(['status' => 0,'message'=>$ruleValidate->getError()]);
            }
        } else {
            if(!$ruleValidate->scene('s2')->check($data)){
                return json(['status' => 0,'message'=>$ruleValidate->getError()]);
            }
        }

        //组装信息
        if(isset($data['em_id']))
            return $this->updateAll($data);
        else
            return $this->storeAll($data);
    }

    //保存电表 缴费结算信息 与机房信息
    private function storeAll($data){
        //保存机房数据
        $dcModel = New Dc();
        if($dcModel->save($data)){
            $data['dc_id'] = $dcModel->id;
        }
        //保存电表数据
        $emModel = new \app\em\model\Em();
        if($emModel->save($data)){
            $data['em_id'] = $emModel->id;
        }

        //保存缴费结算数据
        $emRuleModel = new EmRule();
        $emRuleModel->save($data);

        (new Account())->createAccount($data['em_id']);
        return json(['status'=>1,'message'=>'添加电表成功']);
    }

    //更新写入数据
    private function updateAll($data){

        if(!$data['em_id'])
            throw new Exception('错误的更新操作,没有找到电表ID');

        //更新电表信息
        $emModel =  \app\em\model\Em::find($data['em_id']);
        $emModel->save($data);

        //保存机房数据
        $dcModel = new Dc();
        $dcModel->save($data,['id'=>$emModel->dc_id]);

        //保存缴费结算数据
        $emRuleModel = EmRule::order('id desc,create_time desc')->get(['em_id'=>$data['em_id']]);
        $emRuleModel->save($data);

        (new Account())->createAccount($data['em_id']);

        return json(['status'=>1,'message'=>'修改电表成功']);
    }

    /**
     * 编辑数据
     */
    public function update(){
        $emId = Request::param('id');
        $emModel = new \app\em\model\Em();
        $em = $emModel->getEmInfoById($emId);
        //获取基站基本信息
        $station_info =\app\em\model\Station::getBaseInfoById($em->station_id);
        $this->assign('station',$station_info);

        //获取电表类型
        $emType = ElectricMeterType::select();
        $this->assign('eType',$emType);

        //获取员工信息
        $user  =  Session::get('user');
        if($user['is_admin']){
            $em->edit = true;
            $staffs = StaffModel::field('id,name')->select()->toArray();
        } else {
            $em->edit = $this->checkEmComplete($emId);
            $staff = StaffModel::find($user['user_id'])->toArray();
            $dIds = (new DepartmentModel)->getNodeIds($staff['d_id']);
            $staffs = StaffModel::field('id,name')->where('d_id','in',$dIds)->select()->toArray();
        }
        $this->assign('users',$staffs);
        $this->assign('uid',$user['user_id']);

        $this->assign('info',$em);
        return $this->fetch();
    }


    public function checkEmComplete($em_id){
        $em = \app\em\model\Em::with('rule')->where('id','=',$em_id)->find();

        if(!$em || !isset($em->rule)){
            return false;
        }
        if(!isset($em->rule->settle_price)  || !isset($em->rule->pay_price)){
            return false;
        } else {
            return true;
        }
    }
}