<?php

namespace app\api\controller;

use app\api\service\auth\GroupMysqlAdapter;
use app\api\service\auth\ApiAuthGroupService;
use app\api\validate\User as UserValidate;
use think\exception\ValidateException;
use app\common\model\GroupUser as GroupUserModel;
use app\common\model\User as UserModel;
use app\common\model\WorkerOut as WorkerOutModel;
use \think\facade\Filesystem;
use app\admin\controller\user\GroupUser as AdminGroupUser;
use app\api\controller\Worker;
use app\common\model\ScanLog;
class GroupUser extends Base
{

    protected $noNeedLogin = ['login'];
    protected $today_worker_out_num=0;
    protected function _initialize()
    {
        parent::_initialize();
    }

    public function userinfo(GroupUserModel $userModel)
    {
        $user = $userModel->find($this->userinfo['id']);
        return  $this->success('ok', $user);
    }

    //编辑用户
    public function edit(GroupUserModel $userModel)
    {
        $data = $this->request->post();
        try {
            validate(UserValidate::class)->scene('edit')->check($data);
            $user = $userModel->find($this->userinfo['id']);
            if (!$user) {
                return $this->error('用户不存在');
            }
            $user->save($data);
            return $this->success('ok');
        } catch (ValidateException $e) {
            return $this->error($e->getError());
        }
    }

    //修改密码
    public function password(GroupUserModel $userModel)
    {
        $data = $this->request->post();
        try {
            validate(UserValidate::class)->scene('password')->check($data);
            $user = $userModel->find($this->userinfo['id']);
            if (!$user) {
                return $this->error('用户不存在');
            }
            if ($user->password != md5(md5($data['oldpassword'] . $user->salt))) {
                return $this->error('旧密码错误');
            }
            $user->password = md5(md5($data['password'] . $user->salt));
            $user->save();
            return $this->success('ok');
        } catch (ValidateException $e) {
            return $this->error($e->getError());
        }
    }

    public function login(ApiAuthGroupService $authService, GroupUserModel $userModel)
    {
        $data = $this->request->post();
        try {

            validate(UserValidate::class)->scene('login')->check($data);
            $terminal = $this->request->post('terminal/d', 0);
            $user = $authService->login($data['username'], $data['password'], $terminal);
        } catch (ValidateException $e) {

            return $this->error($e->getError());
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
        return  $this->success('ok', $user);
    }


    //退出登录
    public function logout()
    {
        GroupMysqlAdapter::logout($this->userinfo['id']);
        return  $this->success('ok');
    }

    //获取全部人员
    public function getAllUser(GroupUserModel $userModel)
    {
        $list = $userModel->where('status', 'normal')->field('id,nickname,avatar')->select();
        return $this->success('ok', $list);
    }

    //组员列表
    public function group_list(GroupUserModel $userModel)
    {
        $list = $userModel->where('status', 'normal')->where('pid', $this->userinfo['id'])->select()->each(function ($item, $key) {
            $item['avatar'] = request()->domain() . '/' . $item['avatar'];
            return $item;
        });;
        return $this->success('ok', $list);
    }

    //添加组员
    public function add_group_user(GroupUserModel $groupUserModel, UserModel $userModel)
    {
        $file = request()->file('avatar');
        $param = $this->request->post();
        try {
            validate(UserValidate::class)->scene('add_group_user')->check($param);
            // $todayTime = strtotime('today');

            //判断手机号和身份证号是否注册今天是否添加到该团队
            $where_item_id_card = [];
            $where_item_id_card[] = ['pid', '=', $this->userinfo['id']];
            $where_item_id_card[] = ['id_card', '=', $param['id_card']];
            // $where_item_id_card[]=['createtime', '>=',$todayTime];

            $group_user_data = $groupUserModel->where($where_item_id_card)->find();
            if (!empty($group_user_data)) return $this->error('该身份证号已添加');

            $where_item_mobile = [];
            $where_item_mobile[] = ['pid', '=', $this->userinfo['id']];
            $where_item_mobile[] = ['mobile', '=', $param['mobile']];
            // $where_item_mobile[]=['createtime', '>=',$todayTime];

            $group_user_data = $groupUserModel->where($where_item_mobile)->find();
            if (!empty($group_user_data)) return $this->error('该手机号已添加');

            $user = $userModel->find($this->userinfo['id']);

            $pid = $user['id'];
            $time = time();
            $add_data = [
                'pid' => $pid,
                'nickname' => $param['nickname'],
                'id_card' => $param['id_card'],
                'avatar' => '',
                'mobile' => $param['mobile'],
                'sex' => $param['sex'],
                'role' => '1',
                'status' => 'normal',
                'joinip' => request()->ip(),
                'jointime' => $time
            ];
            if (!empty($file)) {
                // 文件夹
                $folder = strtotime('today');
                $fileName = time() . '_' . mt_rand(1000, 9999) . '.png';

                $avatar = $file->move('uploads/avatar/' . $folder, $fileName);

                //检查目标文件是否存在
                if (!empty($avatar)) {
                    //有图片上传，进行添加用户
                    $add_data['avatar'] = $avatar;
                    $res = $groupUserModel->save($add_data);
                    if ($res) return $this->success('添加成功');
                } else {
                    return $this->error('头像上传失败');
                }
            } else {
                return $this->error('请上传头像');
            }
        } catch (ValidateException $e) {
            return $this->error($e->getError());
        }
        return $this->error('添加失败');
    }
    //修改组员
    public function edit_group_user(GroupUserModel $groupUserModel, UserModel $userModel)
    {
        $file = request()->file('avatar');
        $param = $this->request->post();
        try {
            validate(UserValidate::class)->scene('edit_group_user')->check($param);
            $user = $userModel->find($this->userinfo['id']);
            $edit_data = $groupUserModel->find($param['id']);
            if ($edit_data['pid'] != $this->userinfo['id']) return $this->error('无该用户');

            // $todayTime = strtotime('today');

            //判断手机号和身份证号是否注册今天是否添加到该团队
            $where_item_id_card = [];
            $where_item_id_card[] = ['id', '!=', $edit_data['id']];
            $where_item_id_card[] = ['pid', '=', $this->userinfo['id']];
            $where_item_id_card[] = ['id_card', '=', $param['id_card']];
            // $where_item_id_card[]=['createtime', '>=',$todayTime];

            $group_user_data = $groupUserModel->where($where_item_id_card)->find();
            if (!empty($group_user_data)) return $this->error('该身份证号已添加');

            $where_item_mobile = [];
            $where_item_mobile[] = ['id', '!=', $edit_data['id']];
            $where_item_mobile[] = ['pid', '=', $this->userinfo['id']];
            $where_item_mobile[] = ['mobile', '=', $param['mobile']];
            // $where_item_mobile[]=['createtime', '>=',$todayTime];

            $group_user_data = $groupUserModel->where($where_item_mobile)->find();
            if (!empty($group_user_data)) return $this->error('该手机号已添加');



            $pid = $user['id'];
            $time = time();
            $add_data = [
                'pid' => $pid,
                'nickname' => $param['nickname'],
                'id_card' => $param['id_card'],
                'mobile' => $param['mobile'],
                'sex' => $param['sex'],
                'role' => '1',
                'status' => 'normal',
                'joinip' => request()->ip(),
                'updatetime' => $time
            ];
            if (!empty($file)) {
                // 文件夹
                $folder = strtotime('today');
                $fileName = time() . '_' . mt_rand(1000, 9999) . '.png';

                $avatar = $file->move('uploads/avatar/' . $folder, $fileName);


                //检查目标文件是否存在
                if (!empty($avatar)) {
                    if (!empty($edit_data['avatar'])) {
                        $avatar_file = root_path() . 'public' . DS . $edit_data['avatar'];
                        if (file_exists($avatar_file)) {
                            unlink($avatar_file);
                        }
                    }
                    //有图片上传，进行添加用户
                    $add_data['avatar'] = $avatar;
                    $res = $edit_data->save($add_data);
                    if ($res) return $this->success('修改成功');
                }
            } else {
                $res = $edit_data->save($add_data);
                if ($res) return $this->success('修改成功');
            }
        } catch (ValidateException $e) {
            return $this->error($e->getError());
        }
        return $this->error('修改失败');
    }

    //获取今日出工人员列表
    public function get_worker_out_list(GroupUserModel $groupUserModel, UserModel $userModel, WorkerOutModel $workerOutModel)
    {
        try {
            $workerOutModel=new WorkerOutModel();
            $worker=new Worker();
            $scanLog=new ScanLog();
            $labor_cost_money_avg=empty($worker->quantity_labor_cost_money($scanLog))?0:$worker->quantity_labor_cost_money($scanLog);
            
            $todayTime = strtotime('today');
            $pid=$this->userinfo['id'];
            $where=[];
            $where[] = ['pid', '=',$pid];
            $list = $groupUserModel->where($where)
            ->select()->each(function ($item, $key) {
                $state=$this->get_worker_out_state($item['id'],$this->userinfo['id']);
                $state=$state==0?false:true;
                if($state){
                    $this->today_worker_out_num++;
                }
                $item['selected']=$state;
                $item['avatar']= $this->startsWithHttp($item['avatar'])?$item['avatar']:request()->domain().'/' . $item['avatar'];
                return $item;
            });
            $labor_cost_money_avg=0;
            if(empty($this->today_worker_out_num)||$this->today_worker_out_num==null||$this->today_worker_out_num==0){

            }else{
                $labor_cost_money_avg=round(bcdiv(strval($labor_cost_money_avg['labor_cost_money_sum']),strval($this->today_worker_out_num),2),2);
            }
            
            foreach ($list as $item) {
                if($item['selected']){
                    $item['balance']=$labor_cost_money_avg;
                }
                
            }
            return $this->success('出工人员列表',$list);
            
        } catch (ValidateException $e) {
            return $this->error($e->getError());
        }
    }
    //添加今日出工人员
    public function set_worker_out(GroupUserModel $groupUserModel, UserModel $userModel, WorkerOutModel $workerOutModel)
    {
        $param = $this->request->post();
        try {
            validate(UserValidate::class)->scene('set_worker_out')->check($param);
            $list = $this->comma_str_array($param['list']);
            if(empty($list)) return $this->error('请添加出工人员');;
            $add_worker=[];
            $pid=$this->userinfo['id'];
            $time=time();
            foreach ($list as $key => $value) {
                $state=$this->get_worker_out_state((int)$value,$pid);
                if($state>0) continue;
                $item=[
                    'user_id'=>(int)$value,
                    'pid'=>$pid,
                    'createtime'=>$time
                ];
                $add_worker[]=$item;
            }
            $res=$workerOutModel->saveAll($add_worker);
            if($res) return $this->success('添加出工人员成功');
            
        } catch (ValidateException $e) {
            return $this->error($e->getError());
        }
        return $this->error('添加出工人员失败');
    }

    //清除今日出工人员
    public function clear_worker_out(GroupUserModel $groupUserModel, UserModel $userModel, WorkerOutModel $workerOutModel)
    {
        $param = $this->request->post();
        try {
            validate(UserValidate::class)->scene('set_worker_out')->check($param);
            $list = $this->comma_str_array($param['list']);
            if(empty($list)) return $this->error('请添加取消人员');
            $add_worker=[];
            $pid=$this->userinfo['id'];
            $time=time();
            
            foreach ($list as $key => $value) {
                $id=$this->get_worker_out_id((int)$value,$pid);
                if(empty($id)) continue;
                $item=[
                    'id'=>$id,
                    'state'=>0,
                    'updatetime'=>$time
                ];
                $add_worker[]=$item;
            }
            $res=$workerOutModel->saveAll($add_worker);
            if($res) return $this->success('取消成功');
            
        } catch (ValidateException $e) {
            return $this->error($e->getError());
        }
         return $this->error('取消失败');
    }

    //获取今天出工人员状态，0=未出个，1=出工
    public function get_worker_out_state($id,$pid)
    {
        $groupUserModel=new GroupUserModel();
        $count=$groupUserModel->where('id',$id)->where('pid',$pid)->count();
        if($count==0) return 1;
        
        $workerOutModel=new WorkerOutModel();
        $todayTime = strtotime('today');
        $where=[];
        $where[] = ['user_id', '=',$id];
        $where[] = ['pid', '=',$pid];
        $where[] = ['state', '=',1];
        $where[]=['createtime', '>=',$todayTime];
        return $workerOutModel->where($where)->count();
    }

    //获取今天出工人员id
    public function get_worker_out_id($id,$pid)
    {
        $workerOutModel=new WorkerOutModel();
        $todayTime = strtotime('today');
        $where=[];
        $where[] = ['user_id', '=',$id];
        $where[] = ['pid', '=',$pid];
        $where[] = ['state', '=',1];
        $where[]=['createtime', '>=',$todayTime];
        $count=$workerOutModel->where($where)->count();
        if($count==0) return null;
        $id=$workerOutModel->where($where)->value('id');
        return $id;
    }
    
    //逗号分隔转数组
    public function comma_str_array($arr_string)
    {
        // 1. 清除所有空格（含全角）
        $array = str_replace([' ', '　'], '', $arr_string);

        // 2. 清除开头/结尾的逗号（关键改进）
        $array = trim($array, ',');
        $array=explode(',', $array);
        if(empty($array)) return null;
        $arr=[];
        foreach ($array as &$item) {
            if(empty($item)){
                continue;
            }
            $arr[]=$item;
        }
        return $arr;
    }
    // 方法1.1：使用strpos()精准匹配
    public function startsWithHttp($url)
    {
        return strpos($url, 'https://') === 0
            || strpos($url, 'http://') === 0;
    }
    //今日出工人员打包汇总
    public function worker_pack_sum(GroupUserModel $groupUserModel, UserModel $userModel, WorkerOutModel $workerOutModel)
    {
        $param = $this->request->post();
        try {
            
            
        } catch (ValidateException $e) {
            return $this->error($e->getError());
        }
    }

    
}
