<?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\MasterWorkerRetentionMoneyLog;
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 {
            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'],
                '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']):'',
            ]);

            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);
        }
        Db::startTrans();
        try {

            MasterWorker::where('id', $params['id'])->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'],
                'lon' => $params['lon'],
                'lat' => $params['lat'],
                'distance' => $params['distance'],
                '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']):'',
            ]);
            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('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;
        }
        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 false|string
     */
    public static function getAllWorkers($params){
        try{
            return MasterWorker::where(['is_disable'=>0])->column('id,id as value,worker_number as name,account,mobile');
        } catch (\Exception $e){
            self::setError($e->getMessage());
            return false;
        }

    }
}