<?php
namespace app\job;

use app\common\api\BatchApi;
use app\common\api\TalentLogApi;
use app\common\model\TalentChecklog;
use app\common\state\ProjectState;
use think\queue\Job;
use think\facade\Log;
use think\facade\Db;
use app\common\api\ChuanglanSmsApi;
// 给类文件的命名空间起个别名
use PhpOffice\PhpSpreadsheet\Spreadsheet;
//Xlsx类  保存文件功能类
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use app\admin\api\DataApi;

class Data {

    public function fire(Job $job, $data) {
        if ($this->deal($data)) {
            Log::info(json_encode($data));
            $job->delete();
            return true;
        }
        Log::error(json_encode($data));
        if ($job->attempts() >= 3) {
            $job->delete();
            return false;
        }
        $job->release(10); //10秒后重试
    }

    public function deal($data): bool {
        $id = $data['id'];
        $res = Db::table("new_data_check")->where('id', $id)->findOrEmpty();
        switch ($data['type']){
            case '1':
                if ($res) {
                    if ($res['task_status'] != -1) {
                        return true;
                    }
                    try {
                        $path = dirname(dirname(dirname(__FILE__)));
                        $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($path ."/public/storage/" . $res['task_file']);
                        $sheet = $spreadsheet->getSheet(0);
                        $datas = $sheet->toArray();
                        $datas = array_slice($datas, 1); //去标题
                        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
                        $dataapi = new DataApi();
                        for ($index = 0; $index <= count($datas); $index++) {
                            $cards_list = [];
                            if(empty($datas[$index][2])){//如果文件没有提供出生日期，查询系统内的出生日期
                                echo "正在查询第" . ($index + 1) . "人({$datas[$index][0]})的出生日期\r\n";
                                $info = Db::table('new_talent_info')->where("name ", "=", $datas[$index][0])->where('card_number', '=', $datas[$index][1])->find();
                                if($info){
                                    $birthday = $info['birthday'];
                                }else{
                                    $birthday = false;
                                }
                            }else{
                                $birthday = $datas[$index][2];
                            }
                            if($birthday){
                                echo "正在查询第" . ($index + 1) . "人({$datas[$index][0]}----{$birthday})的证件号\r\n";
                                $cards = $dataapi->IDNumber($datas[$index][0],date("Ymd",strtotime($birthday)));
                                if($cards['code'] == '01' && count($cards['data']) >= 1){
                                    foreach ($cards['data'] as $card){
                                        array_push($cards_list,$card['aac147']);
                                    }
                                }
                            }
                            array_push($cards_list,$datas[$index][1]);
                            array_push($cards_list,substr($datas[$index][1],4));//到底里把所有能取到证件号的渠道得到的证件号放一起
                            $cards_list = array_unique($cards_list);//去掉重复的证件号码
                            $shixian = [];
                            $yanglao = [];//定义失业险和养老险数据
                            foreach ($cards_list as $v){
                                if(count($shixian) == 0){
                                    echo "正在查询第" . ($index + 1) . "人({$datas[$index][0]}----{$v})的失业险\r\n";
                                    $start = $data['year'] . "01";
                                    $end = $data['year'] + 1 . "01";
                                    $res = $dataapi->queryUnemploymentInsuranceByIdAndTime($v,"{$start}","{$end}");
                                    Db::table('data_check_log')->save(['realname' => $datas[$index][0],'card' => $v,'params' => json_encode(['card' => $v,'start' => $start,'end' => $end]), 'result' => json_encode($res),'createTime' => date("Y-m-d H:i:s",time())]);
                                    if($res){
                                        $i = 0;
                                        $months = [];
                                        if(count($res['data']) > 0){
                                            foreach ($res['data'] as $k => $v){
                                                if(strpos($v['AAB069'],"晋华") !== false || strpos($v['AAB069'],"渠梁") !== false){
                                                    $i++;
                                                    array_push($months,$v['AAE003']);
                                                }
                                            }
                                            sort($months);
                                            $res_str = "2022年共缴费{$i}个月，分别是：".implode('、',$months);
                                            echo "第". ($index + 1) . "失业险整理完毕，姓名：{$datas[$index][1]}，".$res_str."\r\n";
                                            $sheet->setCellValue('F' . ($index+1), $res_str);
                                            break;
                                        }
                                    }
                                }





                                echo "第". ($index + 1) . "失业险整理完毕，姓名：{$datas[$index][1]}，2022年共缴费0个月\r\n";
                                $sheet->setCellValue('F' . ($index+1), "2022年共缴费0个月");
                                sleep(3);
                            }








                        }




                    } catch (\Exception $e) {
                        var_dump($e->getMessage());
                        Db::table("new_data_check")->where('id', $id)->update(['task_result' => $e->getMessage(), 'task_status' => 0, 'updateTime' => date("Y-m-d H:i:s", time())]);
                        return false;
                    }
                }
                $path = dirname(dirname(dirname(__FILE__)));
                $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($path . "/test.xlsx");
                $sheet = $spreadsheet->getSheet(0);
                $datas = $sheet->toArray();


                break;
        }
    }
}