<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\adminapi\logic\master_worker;


use app\common\model\master_worker\MasterWorker;
use app\common\logic\BaseLogic;
use app\common\model\master_worker\MasterWorkerScore;
use app\common\model\master_worker\MasterWorkerRetentionMoneyLog;
use app\common\model\master_worker_credential\MasterWorkerCredentialImages;
use app\common\model\service_area\ServiceArea;
use think\db\Query;
use think\facade\Config;
use think\facade\Db;


/**
 * MasterWorker逻辑
 * Class MasterWorkerLogic
 * @package app\adminapi\logic\master_worker
 */
class MasterWorkerLogic extends BaseLogic
{


    /**
     * @notes 添加
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/07/10 18:17
     */
    public static function add(array $params): bool
    {
        Db::startTrans();
        try {
            $service_area_id = ServiceArea::serviceAreaId(['lon' => $params['lon'], 'lat' => $params['lat']]);
            if (!empty($params['lon']) && !empty($params['lat']) && !$service_area_id) {
                self::setError('您所选的位置已超出服务区域！');
                return false;
            }
            $masterWorker = MasterWorker::create([
                'sn' => $params['sn'],
                'avatar' => $params['avatar'],
                'real_avatar' => $params['real_avatar'],
                'real_name' => $params['real_name'],
                'nickname' => $params['nickname'],
                'account' => $params['account'],
                'password' => $params['password'],
                'mobile' => $params['mobile'],
                'sex' => $params['sex'],
                'channel' => $params['channel'],
                'is_disable' => $params['is_disable'],
                'login_ip' => $params['login_ip'],
                'login_time' => $params['login_time'],
                'is_new_user' => $params['is_new_user'],
                'estimate_money' => $params['estimate_money'],
                'user_money' => $params['user_money'],
                'earnest_money' => $params['earnest_money'],
                'exp' => $params['exp'],
                'lon' => $params['lon'],
                'lat' => $params['lat'],
                'distance' => $params['distance'],
                'province' => $params['province'],
                'city' => $params['city'],
                'service_area_id' => $service_area_id,
                'area_name' => $params['area_name'],
                'cooperation' => $params['cooperation']??0,
                'time_period' => $params['time_period']??'',
                'work_status' => $params['work_status']??0,
                'recruiting_behalf' => $params['recruiting_behalf']??'',
                'settlement_type' => $params['settlement_type']??2,
                'labels' => (isset($params['labels']) && $params['labels'])?implode(',',$params['labels']):'',
                'remark' => $params['remark']??'',
                'is_wecall' => $params['is_wecall']??0,
            ]);
            
            //添加工程师汇总评分数据
            MasterWorkerScore::create([
                'worker_id' => $masterWorker->id
            ]);

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


    /**
     * @notes 编辑
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/07/10 18:17
     */
    public static function edit(array $params): bool
    {
        if($params['category_ids']){
            foreach ($params['category_ids'] as $val){
                is_array($val)?($ids[] = end($val)):($ids[] = $val);
            }
            //$params['category_ids'] = ["goods_category_ids"=>$params['category_ids'],"ids"=>$ids];
            $params['category_ids'] = implode(',',$ids);
        }
        /*if($params['tenant_id']){
            // 绑定租户 绑定团队-组员
            $team_id = MasterWorkerTeam::where('tenant_id',$params['tenant_id'])->value('id');
        }*/
        Db::startTrans();
        try {
            $detail = MasterWorker::where('id', $params['id'])->field('id,lon,lat,address,service_area_id')->findOrEmpty()->toArray();
            $address = $params['address']??'';
            if ($detail['address'] != $address && !empty($address)) {
                $lon_lat = get_address_lat_lng($address);
                $params['lon'] = $lon_lat['lon'];
                $params['lat'] = $lon_lat['lat'];
                $service_area_id = ServiceArea::serviceAreaId(['lon' => $params['lon'], 'lat' => $params['lat']]);
                if (!empty($params['lon']) && !empty($params['lat']) && !$service_area_id) {
                    self::setError('您所选的位置已超出服务区域！');
                    return false;
                }
            } else {
                $params['lon'] = $detail['lon'];
                $params['lat'] = $detail['lat'];
                $service_area_id = $detail['service_area_id'];
                if (empty($address)) {
                    $address = getAddressByLatLng($params['lon'], $params['lat']);
                }
            }
            $update = [
                'sn' => $params['sn'],
                'avatar' => $params['avatar'],
                'real_avatar' => $params['real_avatar'],
                'real_name' => $params['real_name'],
                'nickname' => $params['nickname'],
                'account' => $params['account'],
                'password' => $params['password'],
                'mobile' => $params['mobile'],
                'sex' => $params['sex'],
                'channel' => $params['channel'],
                'is_disable' => $params['is_disable'],
                'login_ip' => $params['login_ip'],
                'login_time' => $params['login_time'],
                'is_new_user' => $params['is_new_user'],
                'estimate_money' => $params['estimate_money'],
                'user_money' => $params['user_money'],
                'exp' => $params['exp'],
                'address' => $address,
                'lon' => $params['lon'],
                'lat' => $params['lat'],
                'distance' => $params['distance'],
                'province' => $params['province'],
                'city' => $params['city'],
                'service_area_id' => $service_area_id,
                'area_name' => $params['area_name'],
                'earnest_money' => $params['earnest_money'],
                'earnest_money_usable' => $params['earnest_money_usable'],
                'earnest_money_freeze' => $params['earnest_money_freeze'],
                'installment_ratio' => $params['installment_ratio'],
                'retention_pay_status' => $params['retention_pay_status'],
                'retention_money_status' => $params['retention_money_status'],
                'category_ids' => $params['category_ids']??'',
                'cooperation' => $params['cooperation']??0,
                'time_period' => $params['time_period']?implode(',',$params['time_period']):'',
                'work_status' => $params['work_status']??0,
                'recruiting_behalf' => $params['recruiting_behalf']??'',
                'settlement_type' => $params['settlement_type']??2,
                'labels' => (isset($params['labels']) && $params['labels'])?implode(',',$params['labels']):'',
                'remark' => $params['remark']??'',
                'is_wecall' => $params['is_wecall']??0,
            ];
            //'tenant_id' => $params['tenant_id']??0,
            MasterWorker::where('id', $params['id'])->update($update);
            
            if (is_numeric($params['score']['weight_score'])) {
                $exists = MasterWorkerScore::where('worker_id', $params['id'])->value('id');
                if ($exists) {
                    MasterWorkerScore::where('worker_id',$params['id'])->update(['weight_score' => $params['score']['weight_score']]);
                } else {
                    MasterWorkerScore::create([
                        'worker_id' => $params['id'],
                    'weight_score' => $params['score']['weight_score'],
                    ]);
                }
            }

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


    /**
     * @notes 删除
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/07/10 18:17
     */
    public static function delete(array $params): bool
    {
        return MasterWorker::destroy($params['id']);
    }


    /**
     * @notes 获取详情
     * @param $params
     * @return array
     * @author likeadmin
     * @date 2024/07/10 18:17
     */
    public static function detail($params): array
    {
        $info = MasterWorker::with(['workerInfo'=>function(Query $query){
            $query->field('worker_id,real_name,id_card,id_card_front_img,id_card_opposite_img,mobile,address');
        },'workerRegister'=>function(Query $query){
            $query->field('id as worker_register_id,worker_id,maintain_exp_type,other_exp_type,city,vehicle_type,name,age,mobile')->append(['maintain_exp_type_text','other_exp_type_text','vehicle_type_text','city_text']);
        }])
            ->append(['time_period'])
            ->findOrEmpty($params['id'])->toArray();
        if(!empty($info['category_ids'])){
            $info['category_ids'] = explode(',',$info['category_ids']);
            $info['category_ids'] = array_map('intval', $info['category_ids']);
        }
        $info['is_up_retention_pay'] = 0;
        if(MasterWorkerRetentionMoneyLog::where(['worker_id' => $params['id'],'action' => 1])->count('id') > 0){
            $info['is_up_retention_pay'] = 1;
        }
        $info['score'] = MasterWorkerScore::where(['worker_id' => $params['id']])->field('comprehensive_score,weight_score')->findOrEmpty()->toArray();
        $images = MasterWorkerCredentialImages::where(['worker_register_id' => $info['workerRegister']['worker_register_id']])->select()->toArray();
        $info['credential_info'] = $images;
        return $info;
    }

    /**
     * 获取加盐密码
     * @param $params
     * @return false|string
     */
    public static function saltToPassword($params){
        try{
            $passwordSalt = Config::get('project.unique_identification');
            $password = create_password($params['password'], $passwordSalt);
            return ['password' => $password];
        } catch (\Exception $e){
            self::setError($e->getMessage());
            return false;
        }

    }

    /**
     * 获取所有工程师选项列表
     * @param $params
     * @return array
     */
    public static function getAllWorkers($params){
        try{
            return MasterWorker::where(['is_disable'=>0])->column('id,id as value,worker_number as name,real_name,account,mobile');
        } catch (\Exception $e){
            self::setError($e->getMessage());
            return [];
        }

    }
}