<?php
namespace app\admin\controller;

use app\common\util\ExcelUtil;
use think\Db;
use think\Exception;

class AttendancePunchRecord 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;

            $title = input('title','','trim');
            if($title){
                $map[] = ['user_name','like','%'.$title.'%'];
            }
            $month = input('month',date('Y-m'),'trim');
            if($month){
                $map[] = ['month','=',$month];
            }

            $map[] = ['del','=',0];
            $map[] = ['org_id','=',$this->orgId];
            $map= empty($map) ? true: $map;
            //数据查询
            $lists = db('attendance_punch_record')
                ->where($map)
                ->limit($start,$length)
                ->order($order)
                ->select();

            foreach ($lists as $k=>$v){
                $lists[$k]['k'] = $k+1;
            }


            //数据返回
            $totalCount = db('attendance_punch_record')->where($map)->count();
            $totalPage = ceil($totalCount/$length);
            $result['page'] = $page;
            $result['total'] = $totalPage;
            $result['records'] = $totalCount;
            $result['rows'] = $lists;
            return json($result);
        }else{
            $this->assign('month',date('Y-m'));
            return $this->fetch();
        }
    }


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




    public function import(){
        return $this->fetch();
    }
    /**
     * 下载点模板
     */
    public function downloadtem(){
        set_time_limit(0);
        ini_set("memory_limit","512M");

        $header = [
            ['title' => '序号', 'name' => 'key','width'=>'20'],
            ['title' => '项目名称', 'name' => 'org_name','width'=>'20'],
            ['title' => '部门', 'name' => 'dep_name','width'=>'20'],
            ['title' => '打卡人员', 'name' => 'user_name','width'=>'20'],
            ['title' => '打卡方式', 'name' => 'way','width'=>'20'],
            ['title' => '班次', 'name' => 'class_content','width'=>'20'],
            ['title' => '打卡日期', 'name' => 'date','width'=>'20'],
            ['title' => '打卡时间', 'name' => 'time','width'=>'20'],
            ['title' => '打卡地点', 'name' => 'address','width'=>'20'],
            ['title' => '打卡设备识别码', 'name' => 'device_sn','width'=>'20'],
        ];

        $lists = [
            [
                'key' => '1',
                'org_name' => 'xxx项目',
                'dep_name' => '内科',
                'user_name' => '张三',
                'way' => '移动考勤',
                'class_content' => '7:30-5:30',
                'date' => '2024/5/10',
                'time' => '8:12:29',
                'address' => '山东省济南市历下区经十路16766号',
                'device_sn' => '1C52EE95-1226-4C85-AB5E-0C3E13494FEC',
            ]
        ];

        $filename = '打卡记录模板';
        ExcelUtil::export($filename,$header,$lists);

    }


    public function importexcel(){

        set_time_limit(0);
        ini_set("memory_limit", -1);
        ob_flush();//清空缓存
        flush();//刷新缓存

        try{
            $cols = ['key','org_name','dep_name','user_name','way','class_content','date','time','address','device_sn'];
            $lists = ExcelUtil::importExcel('file',$cols,2);
            if($lists === false){
                exit(ExcelUtil::getError());
            }
            if(empty($lists)){
                exit('文件内容为空');
            }

            foreach ($lists as $k=>$v){
                if(!$v['user_name']){
                    echo "<font color=\"red\" style='margin-left: 20px;font-size: 17px'>第".($k+1)."行,名称不存在,未导入</font><br />";
                    continue;
                }
                $dt = [
                    'org_id'=>$this->orgId,
                    'user_name'=>$v['user_name'],
                    'dep_name'=>$v['dep_name'],
                    'org_name'=>$v['org_name'],
                    'way'=>$v['way'],
                    'class_content'=>$v['class_content'],
                    'date'=>date('Y-m-d',strtotime($v['date'])),
                    'time'=>$v['time'],
                    'address'=>$v['address'],
                    'device_sn'=>$v['device_sn'],
                    'month'=>date('Y-m',strtotime($v['date'])),
                    'create_time'=>date('Y-m-d H:i:s'),
                ];
                $inset = Db::name('attendance_punch_record')->insert($dt);
                if(!$inset){
                    $msg = "第".($k+2)."行,导入失败";
                    echo "<font color=\"red\">".$msg."</font><br />";
                    continue;
                }

            }
            echo "<font color=\"green\">导入完成</font><br />";
        }catch (Exception $e){
            trace($e->getMessage(),'error');
            echo $e->getMessage();
            echo "<font color=\"red\">数据异常,已停止导入</font><br />";
        }
    }

    public function export(){

        set_time_limit(0);
        ini_set("memory_limit","512M");


        $title = input('title','','trim');
        if($title){
            $map[] = ['user_name','like','%'.$title.'%'];
        }
        $month = input('month',date('Y-m'),'trim');
        if($month){
            $map[] = ['month','=',$month];
        }

        $map[] = ['del','=',0];
        $map[] = ['org_id','=',$this->orgId];
        $map= empty($map) ? true: $map;
        //数据查询
        $lists = db('attendance_punch_record')
            ->where($map)
            ->order('id desc')
            ->select();

        foreach ($lists as $k=>$v){
            $lists[$k]['k'] = $k+1;
        }


        $header = [
            ['title' => '序号', 'name' => 'k','width'=>'20'],
            ['title' => '项目名称', 'name' => 'org_name','width'=>'20'],
            ['title' => '部门', 'name' => 'dep_name','width'=>'20'],
            ['title' => '打卡人员', 'name' => 'user_name','width'=>'20'],
            ['title' => '打卡方式', 'name' => 'way','width'=>'20'],
            ['title' => '班次', 'name' => 'class_content','width'=>'20'],
            ['title' => '打卡日期', 'name' => 'date','width'=>'20'],
            ['title' => '打卡时间', 'name' => 'time','width'=>'20'],
            ['title' => '打卡地点', 'name' => 'address','width'=>'20'],
            ['title' => '打卡设备识别码', 'name' => 'device_sn','width'=>'20'],
        ];



        $filename = '打卡记录';
        ExcelUtil::export($filename,$header,$lists);
    }

    public function delAll(){
        if(request()->isPost()){
            $data = request()->post();

            $ids = isset($data['ids'])&&!empty($data['ids']) ? $data['ids']:[];
            if(!$ids){
                $this->error('请选择记录');
            }
            $res = Db::name('attendance_punch_record')->whereIn('id',$ids)->setField('del',1);
            if($res){
                $this->success('操作成功',url('index'));
            }else{
                $this->error('操作失败');
            }
        }else{

            return $this->fetch();
        }

    }

}