<?php
namespace app\mobile\controller;

use think\facade\Db;

/** 新版更换班组：使用 OmsAuth 凭证，身份和岗位从数据库读取。 */
class OmsTeam extends OmsBase
{
    private function result($data) { return json(['code'=>0, 'data'=>$data]); }

    private function describe($rows)
    {
        $base = Db::name('team_base')->column('title', 'id');
        $leaders = Db::name('admin_user')->column('truename', 'id');
        foreach ($rows as &$row) {
            foreach (['id','aid','project','line','shift'] as $key) $row[$key] = (int)$row[$key];
            $row['project_name'] = $base[$row['project']] ?? '未设置';
            $row['line_name'] = $base[$row['line']] ?? '未设置';
            $row['aid_name'] = $leaders[$row['aid']] ?? '暂无班长';
            $row['shift_name'] = [1=>'白班', 2=>'夜班'][$row['shift']] ?? '班次未设置';
        }
        return $rows;
    }

    private function employee($account)
    {
        $member = Db::name('member_list')->where(['id'=>$account['user_id'], 'eid'=>$account['username'], 'status'=>1])->find();
        if (!$member) $this->fail('员工身份已变更，请重新认证', 401);
        return $member;
    }

    public function index()
    {
        return $this->guarded(function () {
            $this->requireMethod('GET');
            $account = $this->current();
            $employee = (int)$account['admin_id'] === 0;
            $current = null;
            $canJoin = $employee;
            if ($employee) {
                $member = $this->employee($account);
                $team = Db::name('team_list')->find($member['tid']);
                if (!$team) $this->fail('当前班组信息异常，请联系管理员', 409);
                $current = $this->describe([$team])[0];
            } else {
                $canJoin = (int)Db::name('admin_user')->where(['id'=>$account['admin_id'], 'username'=>$account['username'], 'status'=>1])->value('job') === 9;
            }
            return $this->result([
                'isEmployee'=>$employee, 'canJoin'=>$canJoin, 'adminId'=>(int)$account['admin_id'],
                'currentTeam'=>$current,
                'teams'=>$this->describe(Db::name('team_list')->where('status',1)->field('id,team,project,line,aid,shift')->order('project,line,team,id')->select()->toArray()),
            ]);
        });
    }

    public function shift()
    {
        return $this->guarded(function () {
            $this->requireMethod('POST');
            $account = $this->current();
            $id = $this->request->post('id');
            $shift = $this->request->post('shift');
            $expected = $this->request->post('expectedShift');
            if (!is_scalar($id) || !preg_match('/^[1-9][0-9]{0,9}$/D',(string)$id) || (float)$id>2147483647) $this->fail('班组编号不正确');
            foreach ([$shift,$expected] as $value) if (!is_scalar($value) || !in_array((string)$value,['1','2'],true)) $this->fail('班别参数不正确');
            $team = Db::transaction(function () use ($account,$id,$shift,$expected) {
                $team = Db::name('team_list')->where('id',(int)$id)->lock(true)->find();
                if (!$team || (int)$team['status']!==1) $this->fail('班组已停用或不存在',409);
                $admin = Db::name('admin_user')->where('id',(int)$account['admin_id'])->lock(true)->find();
                if (!$admin || (int)$admin['status']!==1 || $admin['username']!==$account['username'] || (int)$team['aid']!==(int)$admin['id']) $this->fail('仅该班组对应的班长可修改班别',403);
                if ((int)$team['shift']!==(int)$expected) $this->fail('班组班别已变化，请重新加载后操作',409);
                Db::name('team_list')->where('id',(int)$id)->update(['shift'=>(int)$shift]);
                $team['shift']=(int)$shift;
                return $team;
            });
            return $this->result(['team'=>$this->describe([$team])[0]]);
        });
    }

    public function join()
    {
        return $this->guarded(function () {
            $this->requireMethod('POST');
            $account = $this->current();
            $id = $this->request->post('id');
            if (!is_scalar($id) || !preg_match('/^[1-9][0-9]{0,9}$/', (string)$id) || (float)$id > 2147483647) $this->fail('班组编号不正确');
            $employee = (int)$account['admin_id'] === 0;
            $oldLeader = 0;
            $changed = Db::transaction(function () use ($account, $id, $employee, &$oldLeader) {
                $team = Db::name('team_list')->where('id', (int)$id)->lock(true)->find();
                if (!$team || (int)$team['status'] !== 1) $this->fail('班组已停用或不存在', 409);
                if ($employee) {
                    $member = Db::name('member_list')->where('id',$account['user_id'])->lock(true)->find();
                    if (!$member || (int)$member['status'] !== 1 || $member['eid'] !== $account['username']) $this->fail('员工身份已变更，请重新认证', 401);
                    if ((int)$member['tid'] === (int)$id) return false;
                    Db::name('member_list')->where('id',$member['id'])->update(['tid'=>(int)$id]);
                } else {
                    $admin = Db::name('admin_user')->where('id',$account['admin_id'])->lock(true)->find();
                    if (!$admin || (int)$admin['status'] !== 1 || $admin['username'] !== $account['username']) $this->fail('管理人员身份已变更，请重新认证', 401);
                    if ((int)$admin['job'] !== 9) $this->fail('仅班长岗位可认领班组', 403);
                    $oldLeader = (int)$team['aid'];
                    if ($oldLeader === (int)$account['admin_id']) return false;
                    Db::name('team_list')->where('id',(int)$id)->update(['aid'=>(int)$account['admin_id']]);
                }
                return true;
            });
            if (!$employee && $changed) {
                foreach (array_unique([$oldLeader, (int)$account['admin_id']]) as $aid) {
                    $this->cache()->delete($this->cacheKey('suggestion:managed-teams:'.$aid));
                }
            }
            $team = $this->describe([Db::name('team_list')->find((int)$id)])[0];
            return $this->result(['changed'=>$changed, 'isEmployee'=>$employee, 'team'=>$team, 'profile'=>$this->profileData($account)]);
        });
    }
}
