<?php

namespace app\workerapi\controller;

use think\Request;
use think\facade\Db;
use think\facade\Log;
use app\workerapi\logic\MasterWorkerLogic;
use app\workerapi\logic\MasterWorkerRegisterLogic;
use app\common\model\master_worker\MasterWorkerQuestion;
use app\common\model\master_worker\MasterWorkerInterview;
use app\common\model\master_worker_register\MasterWorkerRegister;

class InterviewController extends BaseApiController
{
    public array $notNeedLogin = ['lists'];
    private array $list = [
        [
            'id' => 1,
            'title' => '请问您目前的工作状态是全职工作还是自由工作？',
            'options' => [
                '全职工作',
                '自由工作'
            ],
            'type' => 1,
        ],
        [
            'id' => 2,
            'title' => '请问您是否有独立上门给客户提供家电维修/清洗/安装的经验？',
            'options' => [
                '有',
                '没有'
            ],
            'type' => 1,
        ],
        [
            'id' => 3,
            'title' => '请问您有没有在其他同类型平台的工作经验？',
            'options' => [
                '有',
                '没有'
            ],
            'type' => 1,
        ],
        [
            'id' => 4,
            'title' => '请简要说明过往工作经历（工作时间、工作内容等）',
            'type' => 3,
        ],
        [
            'id' => 5,
            'title' => '请选择您具备的经验？',
            'options' => [
                '家电清洗',
                '家电维修',
                //'不具备以上经验'
            ],
            'type' => 1,
        ]
    ];

    private array $list2 = [
        
        [
            'id' => 6,
            'title' => '请选择您会的项目？最多选5个，最后会根据您所选的项目进行答题。',
            'options' => [
                '天井机','风管机','家用中央空调','空调','油烟机','洗衣机','热水器','燃气灶','冰箱'
            ],
            'type' => 2,
        ],
        [
            'id' => 7,
            'title' => '请选择您会的项目？最多选5个，最后会根据您所选的项目进行答题。',
            'options' => [
                '空调加氟',
                '空调维修',
                '冰箱','制冷设备','油烟机','洗衣机','甩干机','燃气热水器','电热水器','燃气灶','干洗机',
            ],
            'type' => 2,
        ]
    ];

    private array $list3 = [
        [
            'id' => 9,
            'title' => '请选择您持有的证书？',
            'options' => [
                '低压电工作业',
                '高压电工作业',
                '高处作业',
                '制冷与空调作业',
                '焊接与热切割作业',
                '无',
            ],
            'type' => 1,
        ],
        [
            'id' => 10,
            'title' => '请简单描述您具备的其他技能？',
            'type' => 3,
        ]
    ];
    public function lists(Request $request)
    {
        // 获取单个 POST 参数
        $worker_register_id = $request->post('worker_register_id');
        $step = $request->post('step');
        // 获取所有 POST 参数
        $data = $request->post('data');
        Log::write('工程师面试请求: step='.$step.";data=".json_encode($data));
        if ( !in_array($step, [1,2,3,4,5])) {
            return $this->fail('参数错误');
        }
        if ($step > 1 && (empty($data) || !is_array($data))) {
            return $this->fail('答案不可为空');
        }
         
        Log::write('工程师面试请求: step='.$step.";data=".json_encode($data));
        $worker_register_id = MasterWorkerRegister::where('id',$worker_register_id)->value('id');
        if (!$worker_register_id) {
            return $this->fail('ID有误');
        }
        $info = MasterWorkerInterview::where("worker_register_id", $worker_register_id)->findOrEmpty();
        if ($info->isEmpty()) {
            $info = new MasterWorkerInterview();
            $info->worker_register_id = $worker_register_id;
        } else if ($info->status > 0) {
            return $this->fail('您已提交过面试题，请勿重复提交',['has_next' => 0,'is_success' => $info->status == 1 ? 1 : 0, 'list' => []]);
        }

        $msg = '操作成功';
        $has_next = 1;
        $is_success = 0;
        $result = [];
        $list = $this->list;
        $list2 = $this->list2;
        $list3 = $this->list3;
        $tmplist = array_column($list, null, 'id');
        if ($step == 1 ) {
            $result = $list;
        } elseif ($step == 2) {
            foreach($data as $item) {
                if (empty($item['id']) || ($item['id'] != 4 && empty($item['options']))) {
                    return $this->fail('参数错误');
                }
                if ($item['id'] == 5) {
                    $options = $item['options'];
                }
            }
            if (empty($options)) {
                return $this->fail('请选择您具备的经验');
            }
            $key = array_search($options, $tmplist[5]['options']);
            // if ($key === false || !isset($list2[$key])) {
            //     $has_next = 0;
            //     $info->status = 2;
            //     $msg = '很抱歉，您的测试未通过，感谢您的关注！';
            // } else {
            //     //根据上一步的选项判断
            //     $result[] = $list2[$key]; 
            // }
            
            switch($key) {
                case 0 :
                    $info->type = 1;
                    break;
                case 1 : 
                    $info->type = 2;
                    break;
                default : 
                    $info->type = 0;
            }
            try{
                Db::startTrans();

                MasterWorkerRegisterLogic::createMasterWorker(['worker_register_id' => $worker_register_id,'is_rinse' => $info->type]);

                $info->content = json_encode([1 => $data]);
                $info->status = 1;
                $info->save();
                $has_next = 0;
                $is_success = 1;
                $msg = '恭喜您成功入驻众盾闪修平台！';
                
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return $this->fail($e->getMessage());
            }
            
        } elseif ($step == 3) {
            $data = current($data);
            $id = empty($data['id']) ? 0 : $data['id'];            
            if ($id == 6 || $id == 7) {
                $question = MasterWorkerLogic::getQuestion(['type' => $info->type, 'category' => $data['options']]);
                foreach($question['list'] as $key => $item) {   
                    $item['options'] = str_replace(";; ",";;",$item['options']);
                    $question['list'][$key] = $item;
                    $temp = [
                        "id" => $item['id'],
                        "title" => $item['title'],
                        "options" => explode(";;",$item['options']),
                        "type" => strpos($item['title'], '多选题') !== false ? 2 : 1,
                    ];
                    $result[] = $temp;
                }
            } else {
                return $this->fail('参数有误');
            }
            $content = json_decode($info->content, true);
            $content[2] = $data;
            $info->content = json_encode($content);
            $info->save();
        } elseif (($step == 4 && $info->type == 3) || $step == 5) {
            try{
                Db::startTrans();

                MasterWorkerRegisterLogic::createMasterWorker(['worker_register_id' => $worker_register_id,'is_rinse' => $info->type]);

                $content = json_decode($info->content, true);
                $content[$step - 1] = $data;
                $info->content = json_encode($content);
                $info->status = 1;
                $info->save();
                $has_next = 0;
                $is_success = 1;
                $msg = '恭喜您成功入驻众盾闪修平台！';
                
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return $this->fail($e->getMessage());
            }
        } else {
            //校验
            $data = array_column($data, null, 'id');
            $ids = array_keys($data);
            $answers = MasterWorkerQuestion::where('type',$info->type)->whereIn('id',$ids)->column('answer','id');
            if (count($ids) != count($answers)) {
                return $this->fail('题目参数有误');
            }
            $rights = 0;
            foreach($data as &$item) {
                $answer = $answers[$item['id']];
                if (!in_array($item['options'],['对','错'])) {
                    $item['options'] = preg_replace('/[^a-zA-Z]/', '', $item['options']);

                    //用户选项排序
                    $options = str_split($item['options']);
                    sort($options);
                    $item['options'] = implode('', $options);
    
                    if (($answer == '对' || $answer == '错')) {
                        $item['options'] = $item['options'] == 'A' ? '对' : '错';
                    }
                }
                if ($item['options'] == $answer) {
                    $rights ++;
                }
                $item['answer'] = $answer;
            }
            if ($rights / count($data) >= 0.6) {
                $result = $list3; 
            } else {
                $has_next = 0;
                $info->status = 2;
                $msg = '很抱歉，您的测试未通过，感谢您的关注！';
            }
            $content = json_decode($info->content, true);
            $content[$step - 1] = $data;
            $info->content = json_encode($content);
            $info->save();
        }
        return $this->success($msg, ['has_next' => $has_next,'is_success' => $is_success, 'list' => $result], 1, 1);
    }

}