<?php
namespace web\ambap;

class adduser {
    
    static function setwhere($db, $post) {
        $query = $post->get('query');
        $csql = new \ciy\sql('lab_user');
        
        if (isset($query['name']) && !empty(trim($query['name']))) {
            $csql->where('name like', trim($query['name']));
        }
        if (isset($query['usertitle']) && $query['usertitle'] > 0) {
            $csql->where('usertitle', $query['usertitle']);
        }
        if (isset($query['role']) && $query['role'] > 0) {
            $csql->where('role', $query['role']);
        }
        $liid =$post->getint('liid',0);
        if ($liid > 0) {
            $csql->where('role', $liid);
        }


        
        $csql->order('addtimes DESC');
        return [$query, $csql];
    }
    
    public static function json_list() {
        global $db;
        $rsuser = verifyfast();
        $post = new \ciy\post();
        
        list($where, $csql) = self::setwhere($db, $post);
        $pageno = $post->getint('pageno', 1);
        $pagecount = $post->getint('pagecount', 10);
        $csql->limit($pageno, $pagecount);
        
        try {
            $total = -1;
            $rows = $db->get($csql, $total);
            $ret = [
                'searchwhere' => $where,
                'pageno' => $pageno, 
                'pagecount' => $pagecount, 
                'count' => $total, 
                'list' => $rows
            ];
            
            if ($post->getbool('once')) {
                $ret['once'] = true;
                $ret['lis'] = getcatas($db, 'role'); 
                
                $input = [];
                $input[] = [
                    'type' => 'input',
                    'form' => 'name',
                    'name' => '成员姓名',
                    'prop' => ' style="width:8em;"'
                ];
                $input[] = [
                    'type' => 'select',
                    'form' => 'usertitle',
                    'name' => '头衔',
                    'select' => 'usertitle', 
                    'all' => '全部'
                ];
                $input[] = [
                    'type' => 'select',
                    'form' => 'role',
                    'name' => '状态',
                    'select' => 'role', 
                    'all' => '全部'
                ];
                
                $ret['searchinput'] = $input;
            }
            
            $ret['usertitle'] = getcatas($db, 'usertitle');
            $ret['role'] = getcatas($db, 'role');
            
            return succjson($ret);
        } catch (\Exception $e) {
            return errjson('查询列表失败：' . $e->getMessage());
        }
    }
    
    public static function json_info() {
        global $db;
        $post = new \ciy\post();
        $id = $post->getint('id');
        if ($id <= 0) {
            return errjson('请传入有效的成员ID');
        }
        $csql = new \ciy\sql('lab_user');
        $csql->where('id', $id);
        $row = $db->getone($csql);
        if (!is_array($row)) {
            return errjson('实验室成员数据不存在');
        }
        return succjson(['data' => $row]);
    }
    
    public static function json_add() {
        global $db;
        $post = new \ciy\post();
        $laborgid = $post->getint('laborgid', 0);
        $name = $post->get('name');
        $icon = $post->get('icon', '');
        $usertitle = $post->getint('usertitle', 0);
        $role = $post->getint('role', 30);
        $education = $post->getint('education', 50);
        $sn = $post->get('sn', '');
        $sex = $post->getint('sex', 90);
        $addtimes = $post->getint('addtimes');
        $mobile = $post->get('mobile', '');
        $email = $post->get('email', '');
        $pass = $post->get('pass');
        
        if (empty($pass)) {
            return errjson('请设置初始密码');
        }
        if (empty($name)) {
            return errjson('请填写成员姓名');
        }
        if (empty($sn)) {
            return errjson('请填写成员编号');
        }
        
        $csqlSn = new \ciy\sql('lab_user');
        $csqlSn->where('sn', $sn);
        $snExist = $db->getone($csqlSn);
        if ($snExist) {
            return errjson('成员编号已存在，请更换');
        }
        
        if (!empty($mobile)) {
            if (!preg_match('/^1[3-9]\d{9}$/', $mobile)) {
                return errjson('请输入有效的11位手机号');
            }
            $csqlMobile = new \ciy\sql('lab_user');
            $csqlMobile->where('mobile', $mobile);
            $mobileExist = $db->getone($csqlMobile);
            if ($mobileExist) {
                return errjson('该手机号已绑定其他成员，请更换');
            }
        }
        
        if (!empty($email) && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
            return errjson('请输入有效的邮箱地址');
        }
        
        $addtimes = intval($addtimes / 1000);
        if ($addtimes <= 0) {
            return errjson('加入日期转换失败，请重新选择');
        }

        $insertData = [
            'laborgid' => $laborgid,
            'stpstatus' => 10,
            'userlevel' => 10,
            'name' => $name,
            'dvotecnt' => 0,
            'exptimes' => 0,
            'icon' => $icon,
            'usertitle' => $usertitle,
            'role' => $role,
            'education' => $education,
            'sn' => $sn,
            'sex' => $sex,
            'addtimes' => $addtimes,
            'mobile' => $mobile,
            'email' => $email,
            'password' => $pass,
            'trytime' => 0,
            'logintimes' => time(),
            'ip' => getip()
        ];
        
        try {
            $csql = new \ciy\sql('lab_user');
            $insertResult = $db->insert($csql, $insertData);
            if ($insertResult === false) {
                return errjson('新增成员失败：' . $db->error);
            }
            
            $newMemberId = $db->insert_id();
            $successData = ['id' => $newMemberId, 'name' => $name];
            return succjson($successData);
        } catch (\Exception $e) {
            return errjson('新增成员失败：' . $e->getMessage());
        }
    }
    
    public static function json_update() {
        global $db;
        $rsuser = verifyfast();
        $post = new \ciy\post();
        $id = $post->getint('id');
        
        if ($id <= 0) {
            return errjson('请传入有效的成员ID');
        }
        
        $csql = new \ciy\sql('lab_user');
        $csql->where('id', $id);
        $datarow = $db->getone($csql);
        if (!is_array($datarow)) {
            return errjson('实验室成员数据不存在');
        }
        
        $name = $post->get('name');
        $icon = $post->get('icon', '');
        $usertitle = $post->getint('usertitle', $datarow['usertitle']);
        $role = $post->getint('role', $datarow['role']);
        $education = $post->getint('education', 50);
        $sn = $post->get('sn', '');
        $sex = $post->getint('sex', 90);
        $addtimes = $post->getint('addtimes');
        $mobile = $post->get('mobile', '');
        $email = $post->get('email', '');
        $pass = $post->get('pass', '');
        $stpstatus = $post->getint('stpstatus', 10);
        $userlevel = $post->getint('userlevel', 10);
        $dvotecnt = $post->getint('dvotecnt', 0);
        $exptimes = $post->getint('exptimes', 0);
        
        if (empty($name)) {
            return errjson('请填写成员姓名');
        }
        
        if (!empty($sn) && $sn != $datarow['sn']) {
            $csqlSn = new \ciy\sql('lab_user');
            $csqlSn->where('sn', $sn);
            $csqlSn->where('id !=', $id); 
            $snExist = $db->getone($csqlSn);
            if ($snExist) {
                return errjson('成员编号已存在，请更换');
            }
        } else {
            $sn = $datarow['sn']; 
        }
        
        if (!empty($mobile) && $mobile != $datarow['mobile']) {
            if (!preg_match('/^1[3-9]\d{9}$/', $mobile)) {
                return errjson('请输入有效的11位手机号');
            }
            $csqlMobile = new \ciy\sql('lab_user');
            $csqlMobile->where('mobile', $mobile);
            $csqlMobile->where('id !=', $id); 
            $mobileExist = $db->getone($csqlMobile);
            if ($mobileExist) {
                return errjson('该手机号已绑定其他成员，请更换');
            }
        } else {
            $mobile = $datarow['mobile']; 
        }
        
        if (!empty($email) && $email != $datarow['email']) {
            if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                return errjson('请输入有效的邮箱地址');
            }
        } else {
            $email = $datarow['email'];
        }
        
        if (!empty($addtimes)) {
            $addtimes = intval($addtimes / 1000);
            if ($addtimes <= 0) {
                return errjson('加入日期转换失败，请重新选择');
            }
        } else {
            $addtimes = $datarow['addtimes'];
        }
        
        $updata = [
            'laborgid' => $post->getint('laborgid', 0),
            'stpstatus' => $stpstatus,
            'userlevel' => $userlevel,
            'name' => $name,
            'dvotecnt' => $dvotecnt,
            'exptimes' => $exptimes,
            'icon' => $icon,
            'usertitle' => $usertitle,
            'role' => $role,
            'education' => $education,
            'sn' => $sn,
            'sex' => $sex,
            'addtimes' => $addtimes,
            'mobile' => $mobile,
            'email' => $email,
            'trytime' => $datarow['trytime'],
            'logintimes' => $datarow['logintimes'],
            'ip' => $datarow['ip']
        ];
        
        if (!empty($pass)) {
            $updata['password'] = $pass;
        }
        
        try {
            $db->begin(); 
            $csqlUpdate = new \ciy\sql('lab_user');
            $csqlUpdate->where('id', $id);
            $updateResult = $db->update($csqlUpdate, $updata);
            if ($updateResult === false) {
                throw new \Exception('更新成员失败：' . $db->error);
            }
            savelogdb($db, $rsuser['id'], 'lab_user', $datarow, $updata);
            $db->commit(); 
            
            $csqlNew = new \ciy\sql('lab_user');
            $csqlNew->where('id', $id);
            $newData = $db->getone($csqlNew);
            return succjson(['data' => $newData]);
        } catch (\Exception $e) {
            $db->rollback(); 
            return errjson('更新成员失败：' . $e->getMessage());
        }
    }
    
    public static function json_del() {
        global $db;
        $rsuser = verifyfast();
        $post = new \ciy\post();
        $id = $post->getint('id'); 
        
        $csql = new \ciy\sql('lab_user');
        $csql->where('id', $id); 
        $row = $db->getone($csql); 

        if (!is_array($row))
            return errjson('实验室成员数据不存在'); 

        try {
            $db->begin();
            $delid = $row['id'];
            delme($db, $delid, 'lab_user');
            savelogdb($db, $rsuser['id'], 'lab_user', $row, null);
            $db->commit(); 
        } catch (\Exception $ex) {
            $db->rollback(); 
            return errjson($ex->getMessage()); 
        }

        return succjson(); 
    }
}
?>