<?php

namespace catchAdmin\stations\controller;

use catcher\base\CatchRequest as Request;
use catcher\CatchResponse;
use catcher\base\CatchController;
use catchAdmin\stations\model\Station as stationModel;
use think\facade\Db;
use catcher\Utils;
use catcher\library\excel\Excel;
use catchAdmin\stations\excel\KqExport;
use catchAdmin\stations\excel\DwExport;
use catchAdmin\stations\excel\SkExport;

class Station extends CatchController
{
    protected $stationModel;

    public function __construct(StationModel $stationModel)
    {
        $this->stationModel = $stationModel;
    }

    /**
     * 列表
     * @time 2021年05月21日 15:17
     * @param Request $request 
     */
    public function index(Request $request): \think\Response
    {
        $field = $request->get('field')?:'id';
        $order = $request->get('order')?:'desc';
        return CatchResponse::paginate($this->stationModel->getStationList($field,$order));
    }

    /**
     * 保存信息
     * @time 2021年05月21日 15:17
     * @param Request $request 
     */
    public function save(Request $request): \think\Response
    {
        $data = $request->post();
        if (!$data['school_id']) {
            return CatchResponse::fail('请选择学校');
        }
        if (!$data['access_id']) {
            return CatchResponse::fail('请选择出入口');
        }
        if (!$data['orientation']) {
            return CatchResponse::fail('请选择基站朝向');
        }
        $data['station_mac'] = strtoupper(trim($data['station_mac']));
        if (!$data['station_mac']) {
            return CatchResponse::fail('请输入基站Mac');
        }
        $regex = "/^([A-F0-9]{12})$/";
        if (!preg_match($regex, $data['station_mac'])) {
            return CatchResponse::fail('基站Mac格式不正确');
        }
        if ($this->stationModel->where('station_mac', $data['station_mac'])->count()) {
            return CatchResponse::fail('该基站已存在');
        }
        $data['station_code'] = substr($data['station_mac'], -6);
        if (!trim($data['station_name'])) {
            return CatchResponse::fail('请输入基站名称');
        }
        if (!trim($data['longitude'])) {
            return CatchResponse::fail('请输入经度');
        }
        if (!trim($data['latitude'])) {
            return CatchResponse::fail('请输入纬度');
        }
        if (!trim($data['address'])) {
            return CatchResponse::fail('请输入安装地址');
        }
        $data['station_type'] = 1;
        $data['station_model'] = 2; // 1-G31W1,2-G23
        $city_info = Db::table('departments')->where('id', $data['school_id'])->field('province_id,city_id,district_id')->find();
        $data = array_merge($data, $city_info);
        return CatchResponse::success($this->stationModel->storeBy($data));
    }

    /**
     * 读取
     * @time 2021年05月21日 15:17
     * @param $id 
     */
    public function read($id): \think\Response
    {
        return CatchResponse::success($this->stationModel->findBy($id));
    }

    /**
     * 更新
     * @time 2021年05月21日 15:17
     * @param Request $request 
     * @param $id
     */
    public function update(Request $request, $id): \think\Response
    {
        $data = $request->post();
        if (!$data['school_id']) {
            return CatchResponse::fail('请选择学校');
        }
        if (!$data['access_id']) {
            return CatchResponse::fail('请选择出入口');
        }
        if (!$data['orientation']) {
            return CatchResponse::fail('请选择基站朝向');
        }
        $data['station_mac'] = strtoupper(trim($data['station_mac']));
        if (!$data['station_mac']) {
            return CatchResponse::fail('请输入基站Mac');
        }
        $regex = "/^([A-F0-9]{12})$/";
        if (!preg_match($regex, $data['station_mac'])) {
            return CatchResponse::fail('基站Mac格式不正确');
        }
        $gid = $this->stationModel->where('station_mac', $data['station_mac'])->value('id');
        if ($gid && $gid != $id) {
            return CatchResponse::fail('该基站已存在');
        }
        $data['station_code'] = substr($data['station_mac'], -6);
        if (!trim($data['station_name'])) {
            return CatchResponse::fail('请输入基站名称');
        }
        if (!trim($data['longitude'])) {
            return CatchResponse::fail('请输入经度');
        }
        if (!trim($data['latitude'])) {
            return CatchResponse::fail('请输入纬度');
        }
        if (!trim($data['address'])) {
            return CatchResponse::fail('请输入安装地址');
        }
        unset($data['creator_id']);
        //城市
        $city_info = Db::table('departments')->where('id', $data['school_id'])->field('province_id,city_id,district_id')->find();
        $data = array_merge($data, $city_info);
        return CatchResponse::success($this->stationModel->updateBy($id, $data));
    }

    /**
     * 删除
     * @time 2021年05月21日 15:17
     * @param $id
     */
    public function delete($id): \think\Response
    {
        return CatchResponse::success($this->stationModel->deleteBy($id, true));
    }
    /**
     * 导出考勤基站
     *
     * @time 2020年09月08日
     * @param Excel $excel
     * @param DeviceExport $deviceExport
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @return \think\response\Json
     */
    public function kqexport(Excel $excel, KqExport $kqExport)
    {
        // var_dump(Utils::publicPath('export/students'));导出路径
        return CatchResponse::success($excel->save($kqExport, Utils::publicPath('export/kqstations'), 'local', '考勤基站'));
    }
    /**
     * 导出定位基站
     *
     * @time 2020年09月08日
     * @param Excel $excel
     * @param DeviceExport $deviceExport
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @return \think\response\Json
     */
    public function dwexport(Excel $excel, DwExport $dwExport)
    {
        // var_dump(Utils::publicPath('export/students'));导出路径
        return CatchResponse::success($excel->save($dwExport, Utils::publicPath('export/dwstations'), 'local', '定位基站'));
    }
    /**
     * 导出室内插座基站
     *
     * @time 2020年09月08日
     * @param Excel $excel
     * @param DeviceExport $deviceExport
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @return \think\response\Json
     */
    public function skexport(Excel $excel, SkExport $skExport)
    {
        // var_dump(Utils::publicPath('export/students'));//导出路径
        return CatchResponse::success($excel->save($skExport, Utils::publicPath('export/skstations'), 'local', '室内插座基站'));
    }
    /**
     * 更新考勤基站配置
     * @time 2021年05月21日 15:17
     * @param Request $request 
     * @param $id
     */
    public function updateKqStationConfig(Request $request, $id): \think\Response
    {
        $data = $request->post();
        $config_list=$data['config_list'];
        if($config_list['IS_SLAVE']){
            $config_list['IS_SLAVE']=1;
        }else{
            $config_list['IS_SLAVE']=0;
        }

        $save_data = array(
            'in_station_mac' => strtoupper($config_list['Card_INMAC']),
            'out_station_mac' => strtoupper($config_list['Card_OUTMAC']),
            'config_list' => json_encode($config_list),
            'updated_at' =>time()
        );
   
        return CatchResponse::success( $this->stationModel->where('id', $id) ->update($save_data));
        // return CatchResponse::success( $this->stationModel->updateBy($id, $save_data));
        
    }

    /**
     * 获取发送主机信息
     * @time 2021年05月21日 15:17
     * @param $id
     */
    public function getSendHostInfo($id){
        $info =  $this->stationModel->where('id', $id) ->field('station_version,station_mac')->find();
        if(empty($info)){
            return array('success'=>false,'message'=>'未获取到终端信息');
        }
        if(!$info['station_mac']){
            return array('success'=>false,'message'=>'无终端版Imei号');

        }
        if(!$info['station_version']){
            return array('success'=>false,'message'=>'无终端版本号');
        }
       
        $host = Db::table('sys_config')->where('type','station_config')->where('field','kq_station_host')->value('fieldValue');
        if(!$host){
            $host='127.0.0.1';
        }
        if(substr($info['station_version'],-1) == 'G'){
            $port = 10242;
        }else{
            $port = 10241;
        }
        $host_info = array(
            'imei' => $info['station_mac'],
            'host' => $host,
            'port' => $port,
        );
        return array('success'=>true, 'message'=>'获取成功', 'data'=>$host_info);

    }

    /**
     * 下发IP配置
     * @time 2021年05月21日 15:17
     * @param Request $request 
     * @param $id
     */
    public function sendIpConfig(Request $request, $id): \think\Response
    {   
        $data = $request->post();
        $config_list=$data['config_list'];
        if($config_list['IS_SLAVE']){
            $config_list['IS_SLAVE']=1;
        }else{
            $config_list['IS_SLAVE']=0;
        }

        $save_data = array(
            'in_station_mac' => strtoupper($config_list['Card_INMAC']),
            'out_station_mac' => strtoupper($config_list['Card_OUTMAC']),
            'config_list' => json_encode($config_list),
            'updated_at' =>time()
        );
        // $res=$this->stationModel->updateBy($id, $save_data);
        // var_dump($res);
        $result=$this->getSendHostInfo($id);
        if(!$result['success']){
            CatchResponse::fail($result['message']);
        }
        $host_info = $result['data'];

        $socket = new \tcpclient\TcpClient( $host_info['host'],$host_info['port']);
        $cmd = array(
            "method" => "configRfid",
            "imei" => $host_info['imei'],
            'ip' => $config_list['LOCAL_IP'],
            'mask' => $config_list['LOCAL_MASK'],
            'gateway' => $config_list['LOCAL_GATEWAY'],
            'reportIp' => $config_list['REPORT_IP'],
            'master' => $config_list['IS_SLAVE'],
        );
        $res = $socket->send(json_encode($cmd));
     
        if(!$res['success']){
            return CatchResponse::fail($res['message']);
        }
        $res=$this->stationModel->where('id', $id)->update($save_data);
        if(!$res){
            CatchResponse::fail('保存配置失败');
        }
        return CatchResponse::success('下发成功');
    }


    /**
     * 终端控制指令
     * @time 2021年05月21日 15:17
     * @param Request $request 
     * @param $id
     */
    public function controlConfig(Request $request, $id): \think\Response
    {   
        $data = $request->post();

        $result=$this->getSendHostInfo($id);
        if(!$result['success']){
            CatchResponse::fail($result['message']);
        }
        $host_info = $result['data'];

        $socket = new \tcpclient\TcpClient( $host_info['host'],$host_info['port']);
        $cmd = array(
            "method" =>$data['command'],
            "imei" => $host_info['imei'],
        );
        if($data['command']=='upgrade'){
            $cmd['url']="no upgrade url";
            $cmd['version']="empty";
        }
        
        $res = $socket->send(json_encode($cmd));
        if(!$res['success']){
            return CatchResponse::fail($res['message']);
        }
      
        return CatchResponse::success('下发成功');
    }
    
    
}