<?php
namespace app\admin\controller;
use think\Db;
class AttendanceMachine extends Auth
{

    public function index(){
        if(request()->isAjax()){
            //分页参数
            $length = input('rows',10,'intval');   //每页条数
            $page = input('page',1,'intval');      //第几页
            $start = ($page - 1) * $length;     //分页开始位置
            //排序
            $sortRow = input('sidx','id','trim');      //排序列
            $sort = input('sord','desc','trim');        //排序方式
            $order = $sortRow.' '.$sort;

            $sn = input('sn','','trim');
            if($sn){
                $map[] = ['sn','like','%'.$sn.'%'];
            }

            $map[] = ['org_id','=',$this->orgId];
            $map[] = ['del','=',0];
            $map= empty($map) ? true: $map;
            //数据查询
            $lists = db('attendance_machine')->limit($start,$length)->where($map)->order(['id'=>'desc'])->select();
            foreach ($lists as $k=>$v){
                $lists[$k]['org_name'] = db('org')->where('id',$v['org_id'])->value('name');
            }
            //数据返回
            $totalCount = db('attendance_machine')->where($map)->count();
            $totalPage = ceil($totalCount/$length);
            $result['page'] = $page;
            $result['total'] = $totalPage;
            $result['records'] = $totalCount;
            $result['rows'] = $lists;
            return json($result);
        }else{
            $orgList = db('org')->where('del',0)->where('enable',1)->where('type',2)->select();
            $this->assign('orgList',$orgList);
            return $this->fetch();
        }

    }

    /**
     * 新增/编辑
     */
    public function add($id=0){
        if(request()->isPost()){
            $res = model('AttendanceMachine')->updates();
            if($res){
                $this->success('操作成功',url('index'));
            }else{
                $this->error(model('AttendanceMachine')->getError());
            }
        }else{
            $title = '新增';
            if($id){
                $title = '编辑';
                $info = db('attendance_machine')->where('id',$id)->find();

                $this->assign('info',$info);
            }
            $orgList = db('org')->where('del',0)->where('enable',1)->where('type',2)->select();
            $this->assign('orgList',$orgList);
            $this->assign('title',$title);
            return $this->fetch();
        }
    }

    /**
     * 删除记录
     * @param int $id
     */
    public function del($id=0){
        if(!$id){
            $this->error('参数错误');
        }
        $res = db('attendance_machine')->where('id',$id)->setField('del',1);
        if($res){
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }
    }

    // 清空设备数据
    public function clear(){
        $id = input('id/d',0);
        $info = model('AttendanceMachine')->info($id);
        $title = "清除全部数据";
        $command = 'C:${CmdID}:CLEAR DATA';
        $ret = model('AttendanceMachineCmd')->add($id,$title,$command);
        if($ret){
            $this->success('命令添加成功');
        }else{
            $this->error('命令添加失败');
        }
    }

    // 重新导入数据
    public function reload(){
        $id = input('id/d',0);
        $info = model('AttendanceMachine')->info($id);
        if($info['org_id'] > 0){
            $users = db('user')
                ->alias('u')
                ->join('user_org uo','uo.user_id = u.id')
                ->where('u.del',0)
                ->where('u.enable',1)
                ->where('uo.org_id',$info['org_id'])
                ->where('u.kq_img','<>','')
                ->field('u.id,u.kq_name as name,u.kq_img as img')
                ->select();
            $users = $users?$users:[];
            foreach ($users as $k=>$v){
                $users[$k]['card'] = 1000000000 + $v['id']; // 物业用户
                $users[$k]['id'] = "WY{$v['id']}";
            }
        }

        if(empty($users) && !isset($users)){
            $this->error('当前项目无打卡人员');
        }

        Db::startTrans();
        try{
            // 先清空数据,再导入
            $title = "清除全部数据";
            $command = 'C:${CmdID}:CLEAR DATA';
            $ret = model('AttendanceMachineCmd')->add($id,$title,$command);
            if(!$ret){
                exception('清空数据添加失败');
            }

            // 导入超级管理员
            $admin = config('app.machine_admin');
            $ret = model('AttendanceMachineCmd')->updateAdminInfo($info['id'],$admin['id'],$admin['name'],$admin['card']);
            if(!$ret){
                exception('操作失败');
            }

            foreach ($users as $k=>$v){
                $ret = model('AttendanceMachineCmd')->updateUserInfo($info['id'],$v['id'],$v['name'],$v['card']);
                if(!$ret){
                    exception('操作失败');
                }

                $ret = model('AttendanceMachineCmd')->updateUserImg($info['id'],$v['id'],$v['name'],$v['img']);
                if(!$ret){
                    exception('操作失败');
                }
            }

            Db::commit();
            $this->success('命令添加成功');
        }catch (Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
    }


}