<?php

namespace app\admin\controller;

use app\admin\model\ContractModel;
use app\admin\model\CopyModel;
use app\admin\model\DepartmentModel;
use app\admin\model\ElectricMeter;
use app\admin\model\ElectricMeterType;
use app\admin\model\EngineRoom;
use app\admin\model\OperatorModel;
use app\admin\model\StaffModel;
use app\admin\validate\EmAddValidate;
use think\facade\Session;
use think\Request;
use app\station\model\Station as StationModel;

/**
 * 电表控制器
 * Class Em
 * @package app\admin\controller
 */
class Em extends Base
{

    public function index(Request $request)
    {
                $map=[];
                //权限检测
                $user = Session::get('user');
                if(!$user['is_admin']){
                    $permissionData=check_data();
                    if($permissionData){
                    $map[]=$permissionData; 
                    }
                }
                $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[]=['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.number','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[]=['er.rent','like',"%$search_text%"];
                  $this->assign('search_type',$search_type);
                        break;
                    }
               }else{
                  $this->assign('search_type','');
                  $this->assign('search_text','');
               }
                 $operator = $request->get('operator');
                 if($operator){
                     $map[] = ['s.original_sp_id','=',$operator];
                     $this->assign('operator',$operator);
                 }else{
                     $this->assign('operator','');
                 }
                  $area_id = $request->get('area_id');
                 if($area_id){
                     $map[] = ['s.area_id','=',$area_id];
                     $this->assign('area_id',$area_id);
                 }else{
                      $this->assign('area_id','');
                 }
                $page = $request->get('page')?$request->get('page'):1;

                $limit = $request->get('limit')?$request->get('limit'):10;
                $em= new ElectricMeter;
                $emList= $em->getEmList($map,$page,$limit);
                $emCount= $em->getEmListCount($map);
                if($request->get('page')){
                return ['code'=>0,'msg'=>'','count'=>$emCount,'data'=>$emList];
                }
             //运营商
        $operators = OperatorModel::field('operator_id,operator_name')->where('operator_state','=',1)->select()->toArray();
        //区域
        $this->assign('regions',getTree($em->regions()));
        $this->assign('operators',$operators);
        return $this->fetch('index');
    }
    public function search(Request $request){
        $em =  new ElectricMeter;
        $condition = ''; //查询条件信息
        $map = [];       //查询参数
        $regions = $em->regions();  //获取区域
        $pageCount = $request->get('page');


        $identity = (new Staff)->getIdentity();

        if($pageCount > 0){
           $map = Session::get('map');
           $condition = Session::get('condition');
        } else {
            //获取查询条件
            $type = $request->post('search_type');
            $text = $request->post('search_text');
            $operator = $request->post('operator') + 0;
            $area_id = $request->post('area') + 0;


            switch ($type){
                case 1:
                    $type = 's.station_name';
                    $condition .= '站名: ';
                    break;
                case 2:
                    $type = 's.station_sp_code';
                    $condition .= '站号: ';
                    break;
                case 3:
                    $type = 's.proj_number';
                    $condition .= '项目编号: ';
                    break;
                case 4:
                    $type = 'em.number';
                    $condition .= '电表识别号: ';
                    break;
                case 5:
                    $type = 'em.qrcode';
                    $condition .= '机房二维码: ';
                    break;
                case 6:
                    $type = 'er.rent';
                    $condition .= '出租单位名: ';
                    break;
            }

            if( !empty($text) ){
                $map[] =  [$type,'like',"%".$text."%"];
                $condition .= "<span style='color:#FFB800'> " .$text . " </span>";
            } else {
                $condition .= " 默认 ";
            }

            if( !empty($operator) ){
                $map[] = ['s.original_sp_id','=',$operator];
                if($operator == 1){
                    $condition .= " + 运营商: <span style='color:#FFB800'> 移动</span>";
                } else {
                    $condition .= " + 运营商: <span style='color:#FFB800'> 铁塔</span>";
                }
            } else {
                $condition .= " + 运营商: 默认 ";
            }


            if( $area_id > 0 ){
                $region = '';
                foreach ($regions as $v){
                    if($v['id'] == $area_id) $region = $v;
                }
                $map[] = ['s.area_id','=',$area_id];
                $condition .= " + 区域: <span style='color:#FFB800'>". $region['region_name'] ."</span>";
            } else {
                $condition .= " + 区域: 默认 ";
            }

            $user = Session::get('user');
            if(!$user['is_admin'] && $identity !=5){
                if(config('admin.search_area') == 1){
                    $staff = StaffModel::get($user['user_id']);
                    //通过员工的部门id查询 员工所在部门以及下属部门的所有基站数据
                    $dids = (new DepartmentModel)->getNodeIds($staff->d_id);

                    $stations = StationModel::field('station_id')
                        ->where('department_id','in',$dids)
                        ->select()
                        ->toArray();

                    $stationArr = [];
                    foreach ($stations as $station){
                        $stationArr[]= $station['station_id'];
                    }
                    $map[] = ['em.station_id','in',$stationArr];
                }
            }
            //保存查询条件跟查询信息给分页显示使用
            Session::set('map',$map);
            Session::set('condition',$condition);
        }

        $config  = [
            'list_rows'=>10,
            'page'=> $pageCount,
            'type'     => '\app\extend\PageLayUi',
            'var_page' => 'page'
        ];

        $list = $em->searchList($map,$config);
        $page = $list->render();

        $operators = OperatorModel::field('operator_id,operator_name')->where('operator_state','=',1)->select()->toArray();

        $this->assign('regions',$regions);
        $this->assign('condition',$condition);
        $this->assign('identity',$identity);
        $this->assign('data',$list);
        $this->assign('page',$page);
        $this->assign('operators',$operators);
        return $this->fetch('index');
    }

    public function create($sid){
        //取出电表类型
        $eType = ElectricMeterType::select()->toArray();

        //取出员工信息
        $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);
        //获取基站信息
        $station = (new Station())->getStationById($sid);

        $this->assign('eType',$eType);
        $this->assign('uid',$user['user_id']);
        $this->assign('station',$station);
        //通过user_id找到所在的组下面的所有成员
        return $this->fetch('add');
    }

    public function edit($id){
        $em =  ElectricMeter::with('photo')->find($id)->toArray(); //电表
        $em['photo']['src'] = ltrim($em['photo']['src'] ,'.'); //过滤路径中的点

        $station = (new Station)->getStationById($em['station_id'])->toArray(); //基站

        if($em['er_id']){
            $er = EngineRoom::find($em['er_id'])->toArray(); //机房
        } else {
            $er = [];
        }


        if($em['protocol_id']){
            $protocol = ContractModel::with('photo')->find($em['protocol_id'])->toArray();  //协议
        } else {
            $protocol = [];
        }

        if(isset($protocol['photo']))
            $protocol['photo']['src'] = ltrim($protocol['photo']['src'] ,'.');       //过滤路径中的点


        $contract = ContractModel::field('id,number,sign_time,period')->find($em['contract_id'])->toArray(); //合同

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

        //取出部门员工
        $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('staffs',$staffs);

        if(strlen($em['first_cp_date']) == 10 || strlen($em['first_cp_date']) == 11){
            $em['first_cp_date'] = date('Y-m-d',$em['first_cp_date']);
        }

        $this->assign('iden',$user['is_admin']);
        $this->assign('em',$em);
        $this->assign('station',$station);
        $this->assign('er',$er);
        $this->assign('protocol',$protocol);
        $this->assign('contract',$contract);
        return $this->fetch();
    }

    public function update(Request $request,EmAddValidate $validate){
        $type = $request->post('electric_type');

        //非供电局表
        $scene = 'upType'.$type;
        if(!$validate->scene($scene)->check($request->post())){
            return jsonErr($validate->getError());
        }


        if($request->post('is_protocol') == 1){
            if(!$validate->scene('protocol')->check($request->post())){
                return jsonErr($validate->getError());
            }
        }

        //电表信息
        $em  = ElectricMeter::find($request->post('em_id'));
        $em->emt_id =   $request->post('electric_type');     //电表类型

        $em->qrcode =   $request->post('qr_code') ?: $em->qrcode;     //缴费周期

        $em->number =   $request->post('electric_number');     //电表标号
        $em->pay_number =   $request->post('pay_number');     //缴费号
        $em->multiple =   $request->post('multiple');     //倍率
        $em->pay_cycle =   $request->post('pay_cycle');     //缴费周期

        $em->unit_price =   $request->post('unit_price');     //电表单价
        $em->address =   $request->post('address');     //地址
        $em->remark =   $request->post('electric_remark');     //备注
        $em->init_degree =   $request->post('init_degree');     //初始度数

        if($em->emt_id == 2 || $em->emt_id == 4){
            $em->init_amount =   $request->post('init_amount');     //初始读数
        }

        $em->first_cp_date =   strtotime($request->post('first_cp_date'));     //初始抄表日期
        $em->is_protocol =   $request->post('is_protocol');     // 协议
        $em->protocol_price = $request->post('protocol_price');  // 协议价格

        if($em->is_protocol == 1){
            $em->protocol_id = $request->post('protocol_id');  //上传协议ID
        }

        $em->staff_id =   $request->post('staff_id');     // 员工
        $em->photo_id =   $request->post('photo_id');     // 照片
        $em->status = 1 ;

        if($em->is_protocol && !$em->protocol_id){
            return jsonErr('需要添加电费补充协议');
        }

        //机房信息更新
        $erRes = $this->addEngineRoom();
        if(!$erRes){
            return jsonErr('更新机房信息失败');
        } else {
            $em->er_id = $erRes;
        }
        //合同信息更新
        $conRes = $this->updateContract();
        if(!$conRes){
            return jsonErr('更新合同信息失败');
        } else {
            $em->contract_id = $request->post('contract_id') ?: $em->contract_id;
        }

        if(!$em->save()){
            return jsonErr('更新电表信息失败');
        } else {
            return jsonSuc('更新成功');
        }

    }

    public function show($id){
        $em = (new ElectricMeter)->getEmById($id);

        //查询电表所属的抄表单信息
        $copy = CopyModel::getCopyByEmId($id);

        if($copy) {
            foreach ($copy as $k => $v) {
                if(isset($v['used_number'])) {
                    $copy[$k]['used_number'] = ceil($v['used_number'] * $em['multiple']);
                }
            }
        }

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

    public function export(){
        $user = Session::get('user');
        $staff = StaffModel::get($user['user_id']);
        $stations = StationModel::field('station_id')->where('department_id','=',$staff->d_id)->select()->toArray();

        $stationArr = [];
        foreach ($stations as $station){
            $stationArr[]= $station['station_id'];
        }
        //查询基站所属的电表ID
        $ems = (new ElectricMeter())->getEmsBySids($stationArr);
        $excel = new Excel;
        $excel->export($ems,'电表资料');
    }
//数据导入
    public function import(){
        $file = request()->file('file_name');
        $upload = new Upload($file,2); 
        $result = $upload->upload();
        $fileurl=$_SERVER['DOCUMENT_ROOT'].$result['src'];
        $excel = new Excel;
        $result=$excel->importExecl($fileurl);
        if($result['code']==200){
              return jsonSuc('导入成功!  总导入条数为 '.$result['data']['total'].' 条'.'  成功导入条数为  '.$result['data']['suc']. '  条'.'   失败'.$result['data']['er']. '条');
        }else{
            return jsonErr('模板格式错误');
        }
    }

    public function store(Request $request,EmAddValidate $validate){

        $type = $request->post('electric_type');

        $scene = 'type'.$type;
        if(!$validate->scene($scene)->check($request->post())){
            return jsonErr($validate->getError());
        }

        if($request->post('is_protocol') == 1){
            if(!$validate->scene('protocol')->check($request->post())){
                return jsonErr($validate->getError());
            }
        }

        //电表信息
        $em  = new ElectricMeter;
        $em->station_id =   $request->post('station_id');
        $em->emt_id =   $type;     //电表类型
        $em->number =   $request->post('electric_number');     //电表标号
        $em->pay_number =   $request->post('pay_number');     //缴费号
        $em->multiple =   $request->post('multiple');     //倍率
        $em->pay_cycle =   $request->post('pay_cycle');     //缴费周期
        $em->unit_price =   $request->post('unit_price');     //电表单价
        $em->address =   $request->post('address');     //地址
        $em->remark =   $request->post('electric_remark');     //备注
        $em->init_degree =   $request->post('init_degree');     //初始度数
        $em->init_amount =   $request->post('init_amount');     //初始余额
        $em->first_cp_date =   strtotime($request->post('first_cp_date'));     //初始抄表日期
        $em->is_protocol =   $request->post('is_protocol');     // 协议
        $em->protocol_id = $request->post('protocol_id');  //上传协议照片ID
        $em->staff_id =   $request->post('staff_id');     // 员工
        $em->photo_id =   $request->post('photo_id');     // 照片
        $em->status = 1 ;
        $em->qrcode =   $request->post('qr_code') ?: '';     //倍率


        $em->er_id = $this->addEngineRoom();



        if($em->er_id == 0)
            return jsonErr('添加机房数据错误,请重试');

        $resCon = $this->addContract();
        if($resCon['data'] == 0)
            return jsonErr($resCon['message']);
        $em->contract_id = $resCon['data'];

        //电表附件 如果上传则添加
        if($em->is_protocol == 1){
            $em->protocol_price = $request->post('protocol_price');
        }
        if($em->save()){
            return jsonSuc('添加电表成功!');
        } else {
            return jsonErr('添加电表失败');
        }

    }

    public function searchStations(){
        return $this->fetch('search');
    }

    public  function upProtocol(Request $request){
        $file = $request->file('upProtocol');
        $upload = new Upload($file,1);
        $result = $upload->upload();

        if(!empty($result)){
            return jsonSuc('协议上传成功',$result);
        } else {
            return jsonErr($result);
        }
    }

    public  function upAnnex(Request $request){

        $file = $request->file('annex_file');
        $upload = new Upload($file,1);
        $result = $upload->upload();

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

    private function addEngineRoom(){
        //机房
        $request = new Request;
        $em_id = $request->post('em_id');
        if($em_id){
            $em = ElectricMeter::get($em_id);
            $room = EngineRoom::get($em->er_id);
        }
        //新增
        if(!isset($room) || $room == ''){
            $room = new EngineRoom;
        }

        $room->name = $request->post('rent') ?: $room->name;
        $room->position = $request->post('room_position') ?: $room->position;
        $room->station_id = $request->post('station_id') ?: $room->station_id;
        $room->contact = $request->post('contact') ?: $room->contact;
        $room->tel = $request->post('contact_tel') ?: $room->tel;
        $room->receive = $request->post('receive') ?: $room->receive;
        $room->rent = $request->post('rent') ?: $room->rent;
        $room->property_position = $request->post('property_position') ?: $room->property_position;

        if($request->post('engineroom_remark')){
            $room->remark = $request->post('engineroom_remark');
        }


        if($room->save()){
            return $room->id;
        } else {
            return 0;
        }
    }

    private function addContract(){
         $request = new Request;
         $contract = new Contract;
         $user = Session::get('user');
         $staff = StaffModel::field('id,d_id')->find($user['user_id'])->toArray();
         $data['id'] = $request->post('contract_id') ?: null;
         $data['name'] = '新增电表合同';
         $data['number'] = $request->post('contract_number') ?: 'contract-add-000000';
         $data['u_id'] = $user['user_id'];
         $data['start_date'] = strtotime($request->post('contract_confirm_date'));
         $data['end_date'] = strtotime($request->post('contract_confirm_date'));
         $data['sign_date'] = strtotime($request->post('contract_confirm_date'));
         $data['d_id'] = $staff['d_id'];
         $data['type'] = 1;
         $data['file_id'] = 0;
         $data['remark'] = '';
         $data['period'] = $request->post('period');

         return $contract->store($data);

    }

    public function updateContract(){
        $request =  new Request;
        $em_id = $request->post('em_id');
        $em = ElectricMeter::get($em_id);
        $contract = ContractModel::get($em->contract_id);

        $contract->number = $request->post('contract_number') ?: $contract->number;
        $contract->sign_time = strtotime($request->post('contract_confirm_date')) ?: $contract->sign_time;
        $contract->period = $request->post('period') ?: $contract->period;
        return $contract->save();
    }

    public function storeProtocol(Request $request,Contract $contract){

        $user = Session::get('user');
        $staff = StaffModel::field('id,d_id')->find($user['user_id'])->toArray();

        //有ID则更新 没有ID则新增
        $data['id'] = $request->post('pro_id') ?: '';

        $data['name'] = $request->post('contract_name');
        $data['number'] = $request->post('contract_number');
        $data['u_id'] = $user['user_id'];
        $data['start_date'] = strtotime($request->post('contract_start_date'));
        $data['end_date'] = strtotime($request->post('contract_end_date'));
        $data['sign_date'] = strtotime($request->post('contract_sign_date'));
        $data['d_id'] = $staff['d_id'];
        $data['type'] = 2;

        //获取合同附件ID
        $data['file_id'] = $request->post('contract_file');
        $data['remark'] = $request->post('contract_remark');

        //计算合同区间
        $time = $data['end_date'] - $data['start_date'];
        $data['period'] = ceil($time/(3600*24*30));

        $resCon = $contract->store($data);

        if(!$resCon['data'])
            return jsonErr($resCon['message']);
        else
            return jsonSuc($resCon['message'],$resCon['data']);
    }

    public function updateProtocol(Request $request,Contract $contract){

        $user = Session::get('user');
        $staff = StaffModel::field('id,d_id')->find($user['user_id'])->toArray();

        $data['id'] = $request->post('pro_id');
        $data['name'] = $request->post('contract_name');
        $data['number'] = $request->post('contract_number');
        $data['u_id'] = $user['user_id'];
        $data['start_date'] = strtotime($request->post('contract_start_date'));
        $data['end_date'] = strtotime($request->post('contract_end_date'));
        $data['sign_date'] = strtotime($request->post('contract_sign_date'));
        $data['d_id'] = $staff['d_id'];
        $data['type'] = $request->post('contract_type') ?: 2 ;
        $data['file_id'] = $request->post('contract_file');
        $data['remark'] = $request->post('contract_remark');

        $time = $data['end_date'] - $data['start_date'];
        $data['period'] = ceil($time/(3600*24*30));

        $resCon = $contract->store($data);

        return $resCon ? $resCon->id : 0;
    }
}
