<?php
namespace app\workerapi\logic;

use app\adminapi\logic\training\TrainingBlockConfigLogic;
use app\adminapi\logic\training\TrainingWorkerTaskLogic;
use app\common\model\master_worker\MasterWorker;
use app\common\model\master_worker\MasterWorkerScore;
use app\common\model\master_worker_credential\MasterWorkerCredentialImages;
use app\common\model\master_worker_register\MasterWorkerRegister;
use app\common\model\service_area\ServiceArea;
use app\common\logic\BaseLogic;
use app\common\model\sale\Sale;
use app\common\service\ConfigService;
use think\facade\Config;
use think\facade\Db;
use think\facade\Log;

/**
 * MasterWorkerRegister逻辑
 * Class MasterWorkerRegisterLogic
 * @package app\workerapi\logic\master_worker_register
 */
class MasterWorkerRegisterLogic extends BaseLogic
{

    /**
     * 获取详情
     */
    public static function detail($params): array
    {
        return MasterWorkerRegister::findOrEmpty($params['id'])->append(['credential_images','credential_name','city_text','maintain_exp_type_text','other_exp_type_text','vehicle_type_text'])->toArray();
    }

    public static function createMasterWorker(array $params)
    {
        Log::info('面试创建工程师-101:'.json_encode($params));
        $masterWorkerRegister = MasterWorkerRegister::where('id', $params['worker_register_id'])->findOrEmpty();
        if ($masterWorkerRegister->isEmpty()) {
            return 0;
        }
        $where = ['mobile' => $masterWorkerRegister['mobile']];
        $masterWorker = MasterWorker::where($where)->findOrEmpty();
        if ($masterWorker->isEmpty()) {
            $number = MasterWorker::count();
            $number += 1;
            if ($number < 100000) {
                $number = str_pad($number, 6, '0', STR_PAD_LEFT);
            }
            $userSn = MasterWorker::createUserSn();
            $passwordSalt = Config::get('project.unique_identification');
            $password = create_password($masterWorkerRegister['mobile'], $passwordSalt);
            $avatar = ConfigService::get('default_image', 'user_avatar');
            
            $service_area_id = ServiceArea::serviceAreaId(['lon' => $masterWorkerRegister['lon'], 'lat' => $masterWorkerRegister['lat']]);

            /*系统自动填写工程师入驻信息（除身份证、银行卡外，代招人、时间段默认全选、合作形式默认全日接单、工作状态默认正常工作、
            结算类型是半月、半径默认3公里、服务类目为空、质保金比例默认15%、质保金缴纳方式分期抵扣、
            根据AI里面的回复确定清洗还是维修）。确认接单地址。*/
            $masterWorker = MasterWorker::create([
                'sn' => $userSn,
                'worker_number' => $number,
                'avatar' => $avatar,
                'nickname' => '用户' . $userSn,
                'account' => $masterWorkerRegister['mobile'],
                'mobile' => $masterWorkerRegister['mobile'],
                'real_name' => $masterWorkerRegister['name']??'',
                'password' => $password,
                'channel' => 1,
                'lon' => $masterWorkerRegister['lon']??0,
                'lat' => $masterWorkerRegister['lat']??0,
                'distance' => 3000,
                'province' => $masterWorkerRegister['province']??0,
                'city' => $masterWorkerRegister['city']??0,
                'service_area_id' => $service_area_id,
                'area_name' => $masterWorkerRegister['area_name']??'',
                'tenant_id' => 0,
                'category_ids' => '',
                // 1清洗 2维修
                'earnest_money' => ($params['is_rinse']==1)?3000:5000,
                'retention_pay_status' => 2,
                'installment_ratio' => 15,
                'time_period' => '1,2,3,4',
                'cooperation' => 2,
                'recruiting_behalf' => Sale::where('id',$masterWorkerRegister['sale_id']??0)->value('sale_name')??'',
                'settlement_type' => 2,
                'identity_source' => 1,
            ]);
            //添加工程师汇总评分数据
            MasterWorkerScore::create([
                'worker_id' => $masterWorker->id
            ]);
            Log::info('面试创建工程师-102:'.$masterWorker->id);
            MasterWorkerRegister::where('id', $params['worker_register_id'])->update(['worker_id' => $masterWorker->id,'status'=>1]);
            $block_setting = TrainingBlockConfigLogic::getBlockConfig(1);
            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 $masterWorker->id;
    }


    /**
     * 获取证件
     */
    public static function credential($worker_register_id): array
    {
        return MasterWorkerCredentialImages::where('worker_register_id', $worker_register_id)->select()->toArray();
    }
    /**
     * 修改证件
     */
    public static function setCredential(array $params)
    {
        Db::startTrans();
        try {
            MasterWorkerCredentialImages::where('id', $params['id'])->update([
                'worker_register_id' => $params['worker_register_id'],
                'image' => $params['image'],
                'image_name' => $params['image_name'],
                'start_time' => strtotime($params['start_time']??0),
                'end_time' => strtotime($params['end_time']??0),
                'audit_state' => 0,
                'number' => $params['number']??'',
            ]);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }









}