<?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 think\facade\Db;
use app\common\logic\BaseLogic;
use PhpOffice\PhpSpreadsheet\IOFactory;
use app\common\model\master_worker\MasterWorkerTemporary;


/**
 * MasterWorkerTemporary逻辑
 * Class MasterWorkerLogicTemporary
 * @package app\adminapi\logic\master_worker
 */
class MasterWorkerTemporaryLogic 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 {
            if (MasterWorkerTemporary::where('mobile', $params['mobile'])->value('mobile')) {
                self::setError('该手机号已存在！');
                return false;
            }
            if($params['category_ids']){
                foreach ($params['category_ids'] as $val){
                    is_array($val)?($ids[] = end($val)):($ids[] = $val);
                }
                $params['category_ids'] = implode(',',$ids);
            }
            $number = MasterWorkerTemporary::count();
            $number++;
            $worker_number = str_pad($number, 6, '0', STR_PAD_LEFT);
            MasterWorkerTemporary::create([
                'worker_number' => $worker_number,
                'real_name' => $params['real_name'],
                'mobile' => $params['mobile'],
                'is_disable' => $params['is_disable'],
                'work_status' => $params['work_status']??0,
                'remark' => $params['remark']??'',
                'category_ids' => $params['category_ids']??'',
            ]);
            
            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
    {
        Db::startTrans();
        try {
            if($params['category_ids']){
                foreach ($params['category_ids'] as $val){
                    is_array($val)?($ids[] = end($val)):($ids[] = $val);
                }
                $params['category_ids'] = implode(',',$ids);
            }
            $update = [
                'real_name' => $params['real_name'],
                'is_disable' => $params['is_disable'],
                'work_status' => $params['work_status']??0,
                'remark' => $params['remark']??'',
                'category_ids' => $params['category_ids']??'',
            ];
            MasterWorkerTemporary::where('id', $params['id'])->update($update);
            
            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 MasterWorkerTemporary::destroy($params['id']);
    }


    /**
     * @notes 获取详情
     * @param $params
     * @return array
     * @author likeadmin
     * @date 2024/07/10 18:17
     */
    public static function detail($params): array
    {
        $info = MasterWorkerTemporary::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']);
        }
        return $info;
    }

    /**
     * 导入工程师
     */
    public static function import($file) {
        
        $mobile = [];
        try {
            // 移动文件到指定目录
            $info = $file->move(root_path('public') . 'uploads');
            if ($info) {
                $filePath = $info->getPathname();

                // 读取 Excel 文件
                $spreadsheet = IOFactory::load($filePath);
                $worksheet = $spreadsheet->getActiveSheet();
                $highestRow = $worksheet->getHighestRow();

                $number = MasterWorkerTemporary::count();
                // 假设第一行为表头，从第二行开始读取数据
                for ($row = 2; $row <= $highestRow; $row++) {
                    
                    $data = [
                        'real_name' => $worksheet->getCell('A' . $row)->getValue(),
                        'mobile' => $worksheet->getCell('B' . $row)->getValue(),
                        'remark' => $worksheet->getCell('C' . $row)->getValue(),
                    ];
                    if (empty($data['mobile'])) {
                        continue;
                    }
                    if(MasterWorkerTemporary::where('mobile', $data['mobile'])->value('mobile')){
                        $mobile[] = $data['mobile']; 
                        continue;
                    }
                    $number += 1;
                    $data['worker_number'] = str_pad($number, 6, '0', STR_PAD_LEFT);
                    MasterWorkerTemporary::create($data);
                }
                if ($mobile) {
                    self::setError('手机号'.implode(',',$mobile).'已存在');
                    return false;
                }
                return true;
            } else {
                self::setError($file->getError());
                return false;
            }
        } catch (\Exception $e) {
            self::setError($e->getMessage());
            return false;
        }
    }
}