<?php
namespace app\workerapi\logic;
use app\adminapi\logic\master_worker_register\MasterWorkerRegisterLogic;
use app\adminapi\logic\training\TrainingBlockConfigLogic;
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\goods_category\GoodsCategory;
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;
use think\facade\Log;

/**
 * @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'])->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('该手机号已占用');
            }

            if(isset($params['category_ids']) && !empty($params['category_ids']) && is_array($params['category_ids'])){
                $params['category_ids'] = implode(',',$params['category_ids']);
            }
            // 新增工程师 - 所属团队、租户
            $mwId = MasterWorkerRegisterLogic::createMasterWorker([
                'mobile' => $params['mobile'],
                'real_name' => $params['real_name'],
                'lon' => isset($params['lon'])?$params['lon']:0,
                'lat' => isset($params['lat'])?$params['lat']:0,
                'tenant_id'=>$team->tenant_id,
                'category_ids' => $params['category_ids']??'',
                'identity_source' => 1,
            ]);
            MasterWorker::where('id',$mwId)->update(['team_id'=>$team->id,'team_role'=>2]);

            $block_setting = TrainingBlockConfigLogic::getBlockConfig(1);
            \app\adminapi\logic\training\TrainingWorkerTaskLogic::add([
                'master_worker_id' => $masterWorker->id,
                'shop_goods_id' => $block_setting['shop_goods_id']??0,
                'training_task_id' => $block_setting['training_task_id']??0,
                'task_list' => $block_setting['task_list']??0,
            ]);

            return true;
        } catch (\Exception $e) {
            self::setError($e->getMessage());
            return false;
        }
    }

    public static function upTeamMember(array $params,int $masterWorkerId,int $userId = 0)
    {
        try {
            $team = MasterWorkerTeam::where('master_worker_id',$userId)->findOrEmpty();
            if ($team->isEmpty()) {
                throw new \Exception('团队不存在');
            }
            // $masterWorkerId 当前要修改的工程师ID
            // 若非自己的其他工程师存在则不允许修改
            $masterWorker =  MasterWorker::where('id','<>',$masterWorkerId)->where('mobile',$params['mobile'])->findOrEmpty();
            if (!$masterWorker->isEmpty()) {
                throw new \Exception('该手机号已占用');
            }
            if(isset($params['category_ids']) && !empty($params['category_ids']) && is_array($params['category_ids'])){
                $params['category_ids'] = implode(',',$params['category_ids']);
            }
            // 包括队长自己 ->where('team_role',2)
            MasterWorker::where('team_id',$team->id)->where('id',$masterWorkerId)->update(['real_name'=>$params['real_name'],'account'=>$params['mobile'],'mobile'=>$params['mobile'],'category_ids'=>$params['category_ids']??'']);
            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'])->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(!in_array($work->work_status, [1,2,3,4,5])){
                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'],'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,
                'type' => 0,
                '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::where('tenant_id',
                    (MasterWorkerTeam::where('id',$userInfo['team_id'])->value('tenant_id')??-1)
                )->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[] = [
                'is_allocation' => in_array($work_status, [1,2,3,4,5]) ? 1 : 0,
                'work_status' => $work_status,
                'work_status_text' => $name,
                'count_num' => $lists[$work_status]??0,
            ];
        }
        return $res;
    }

    /**
     * 团队工单统计- 当天日期的前x天范围
     * @param int $teamId
     * @param int $masterWorkerId
     * @return array
     */
    public static function TeamOrderStatistics($userInfo,$day_num = 7,$month = ''){
        if(!empty($day_num)){
            $start_time = strtotime(date('Y-m-d', time() - $day_num * 86400));
            $end_time = time();
        }
        if(!empty($month)){
            $start_time = strtotime($month.'-01');
            $end_time = $start_time + 31 * 86400;
        }
        $lists = ServiceWork::where('tenant_id',
            (MasterWorkerTeam::where('id',$userInfo['team_id'])->value('tenant_id')??-1)
        )->group('DATE(FROM_UNIXTIME(create_time))')
            ->field('DATE(FROM_UNIXTIME(create_time)) as days, COUNT(id) as count_num')
            ->where('create_time','between',[$start_time,$end_time])
            ->order('create_time desc')
            ->select()->toArray();
        return array_column($lists,'count_num','days');
    }
}
