<?php
namespace app\workerapi\logic;
use app\adminapi\logic\master_worker_register\MasterWorkerRegisterLogic;
use app\common\enum\worker\WorkerAccountLogEnum;
use app\common\enum\YesNoEnum;
use app\common\logic\BaseLogic;
use app\common\model\bank_account\BankAccount;
use app\common\model\master_worker\MasterWorker;
use app\common\model\master_worker\MasterWorkerAccountLog;
use app\common\model\master_worker\MasterWorkerAgree;
use app\common\model\master_worker\MasterWorkerInfo;
use app\common\model\master_worker\MasterWorkerTeam;
use app\common\model\works\ServiceWork;
use app\common\service\FileService;
use app\workerapi\lists\MasterWorkerLists;
use app\workerapi\lists\ServiceWorkLists;
use think\Exception;
use think\facade\Config;
use think\facade\Db;

/**
 * @author 林海涛
 * @date 2024/7/10 下午1:45
 */
class MasterWorkerTeamLogic extends  BaseLogic
{
    public static function getDetail(int $masterWorkerId)
    {
        try {
            $team = MasterWorkerTeam::where('master_worker_id',$masterWorkerId)->findOrEmpty();
            if ($team->isEmpty()) {
                throw new \Exception('团队不存在');
            }
            $team = $team->toArray();
            $team['count_num'] = MasterWorker::where('team_id',$team['id'])->where('team_role',2)->count();
            return $team;
        } catch (\Exception $e) {
            self::setError($e->getMessage());
            return [];
        }
    }

    public static function addTeamMember(array $params,int $masterWorkerId)
    {
        try {
            $team = MasterWorkerTeam::where('master_worker_id',$masterWorkerId)->findOrEmpty();
            if ($team->isEmpty()) {
                throw new \Exception('团队不存在');
            }
            $masterWorker =  \app\common\model\master_worker\MasterWorker::where('mobile',$params['mobile'])->findOrEmpty();
            if (!$masterWorker->isEmpty()) {
                throw new \Exception('该手机号已占用');
            }
            // 新增工程师
            $mwId = MasterWorkerRegisterLogic::createMasterWorker([
                'mobile' => $params['mobile'],
                'lon' => isset($params['lon'])?$params['lon']:0,
                'lat' => isset($params['lat'])?$params['lat']:0,
            ]);
            MasterWorker::where('id',$mwId)->update(['team_id'=>$team->id,'team_role'=>2]);
            return true;
        } catch (\Exception $e) {
            self::setError($e->getMessage());
            return false;
        }
    }


    public static function getMemberList(int $masterWorkerId)
    {
        try {
            $team = MasterWorkerTeam::where('master_worker_id',$masterWorkerId)->findOrEmpty();
            if ($team->isEmpty()) {
                throw new \Exception('团队不存在');
            }
            return MasterWorker::where('team_id',$team['id'])->where('team_role',2)->field(['id','nickname','avatar','mobile','real_name','team_role'])->select()->toArray();
        } catch (\Exception $e) {
            self::setError($e->getMessage());
            return [];
        }
    }


    /**
     * 分配给团队成员
     * @param int $teamId
     * @param int $masterWorkerId
     * @return array
     */
    public static function allocation($params,$userInfo){
        Db::startTrans();
        try {
            $work = ServiceWork::findOrEmpty($params['work_id']);
            if($work->isEmpty()){
                throw new Exception('工单不存在');
            }
            if($work->work_status != 1 ){
                throw new \Exception('工单已被领取，不可分配');
            }
            if($work->master_worker_id == $params['master_worker_id']){
                throw new \Exception('分配的工程师相同');
            }
            $worker = MasterWorker::where(['id'=>$params['master_worker_id'],'team_id' =>$userInfo['team_id'],'team_role' =>2,'is_disable' =>0])->findOrEmpty();
            if($worker->isEmpty()){
                throw new \Exception('成员工程师不存在或被禁用');
            }
            if($worker->master_worker_id){
                MasterWorker::setWorktotal('dec',$worker->master_worker_id);
            }
            $work->master_worker_id = $params['master_worker_id'];
            $work->work_status = 1;
            $work->dispatch_time = time();
            MasterWorker::setWorktotal('inc',$params['master_worker_id']);
            $work->save();
            $work_log = [
                'work_id'=>$work->id,
                'master_worker_id'=>$work->master_worker_id,
                'opera_log'=>'团队负责人['.$userInfo['user_id'].']'.$userInfo['real_name'].'于'.date('Y-m-d H:i:s',time()).'分配了工程师成员'.'编号['.$worker->worker_number.']'.$worker->real_name
            ];
            ServiceWorkerAllocateWorkerLogic::add($work_log);
            Db::commit();
            return true;
        }catch(\Exception $e){
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }

    /**
     * 团队成员工单统计
     * @param int $teamId
     * @param int $masterWorkerId
     * @return array
     */
    public static function MemberWorkStatistics($userInfo){
        $lists = ServiceWork::whereIn('master_worker_id',
                    MasterWorker::where('team_id', $userInfo['team_id'])->where('team_role', 2)->column('id')
                )->group('work_status')
                ->field('work_status, COUNT(id) as count_num')
                ->order('work_status asc')
                ->select()->toArray();
        $lists = array_column($lists,'count_num','work_status');
        $work_status_txt = array_slice(ServiceWork::WORK_STATUS_TXT, 1, 8,true);
        $res = [];
        foreach ($work_status_txt as $work_status => $name) {
            $res[] = [
                'work_status' => $work_status,
                'work_status_text' => $name,
                'count_num' => $lists[$work_status]??0,
            ];
        }
        return $res;
    }


}
