<?php

namespace app\common\controller;

use app\BaseController;
use app\admin\model\Enterprise;
use app\common\api\CompanyApi;
use app\common\api\TalentConditionApi;
use app\common\api\TalentLogApi;
use app\common\api\TalentState;
use app\common\model\LivingAllowance as LaModel;
use app\common\model\TalentChecklog;
use app\common\state\IntegralState;
use app\common\state\ProjectState;
use app\enterprise\api\TalentApi;
use app\enterprise\model\Talent;
use app\common\api\DictApi;
use think\facade\Db;
use app\admin\model\User;

/**
 * 需要权限的公共方法放这
 * Description of Tool
 *
 * @author sgq
 */
class Data extends BaseController {

    //protected $middleware = [ApiEncrypt::class];

    public function __construct(\think\App $app) {
        parent::__construct($app);
    }

    public function getEnterprise(\think\Request $request){
        $pageSize = $request->param('pageSize',20);
        $page = $request->param('page',1);
        $where[] = ["delete", "=", 0];
        $where[] = ['type','=',1];
        $list = Enterprise::where($where)->limit(($page-1)*$pageSize, $page*$pageSize)->order("createTime", 'desc')->field('id,industryFieldNew,enterpriseTag,organizationTag,institutionTag,enterpriseType,name,idCard,street,address,legal,ephone,agentName,agentPhone,username,password,bankCard,bankNetwork,bank,agentEmail,imgurl,bankImg,domainImg,typeImg,beian,checkState,checkMsg,checkUser,active,activeMsg,createTime,updateUser,updateTime,modify_fields,modify_files')->select()->toArray();
        $json = [
            'code' => 200,
            'msg' => '查询成功',
            'data' => $list
        ];
        $ret = base64_encode($this->curlPost("http://sm4.jinjianghc.com/sm4_cbc.php",['data' => json_encode($json),'key' => '3eh2rxdtkULT2zpkDdRiRGH8PL5J0LsZ','iv' => 'jKihG4wF622ocb8z']));
        return $ret;
        //return openssl_encrypt(json_encode($json),'sm4-cbc','3eh2rxdtkULT2zpkDdRiRGH8PL5J0LsZ',OPENSSL_RAW_DATA,'jKihG4wF622ocb8z');
    }

    public function getTalent(\think\Request $request){
        $pageSize = $request->param('pageSize',20);
        $page = $request->param('page',1);
        $enterprise_id = $request->param('enterprise_id',0);
        if(empty($enterprise_id)){
            $json = [
                'code' => 0,
                'msg' => '企业ID不能为空',
            ];
            $ret = base64_encode($this->curlPost("http://sm4.jinjianghc.com/sm4_cbc.php",['data' => json_encode($json),'key' => '3eh2rxdtkULT2zpkDdRiRGH8PL5J0LsZ','iv' => 'jKihG4wF622ocb8z']));
            return $ret;

            //return openssl_encrypt(json_encode($json),'sm4-cbc','3eh2rxdtkULT2zpkDdRiRGH8PL5J0LsZ',OPENSSL_RAW_DATA,'jKihG4wF622ocb8z');
        }
        $where[] = ["delete", "=", 0];
        $where[] = ["enterprise_id",'=',$enterprise_id];
        $field = 'id,salary_pay_way,salary_pay_month,tax_insurance_month,labor_contract_rangetime,pre_import_type,enterprise_id,name,headimgurl,card_type,card_number,sex,birthday,nationality,province,city,county,nation,politics,talent_arrange,talent_condition,fj_talent_condition_text,qz_talent_condition_text,highest_degree,graduate_school,major,professional,pro_qua,bank,bank_number,bank_account,study_abroad,abroad_school,abroad_major,phone,email,apply_year,import_way,return,fst_work_time,cur_entry_time,cur_quit_time,position,source,source_batch,source_city,source_county,fujian_highcert_pubtime,fujian_highcert_exptime,quanzhou_highcert_pubtime,quanzhou_highcert_exptime,createTime,updateTime,modify_fields,modify_files,first_submit_time,new_submit_time,first_dept_check_time,pass_dept_check,checkState,highProcess,isEffect,publicBatch,certificateGetTime,certificateExpireTime,certificateNo,experience,education,annual_salary,break_faith,identifyGetTime,identifyConditionName,title,check_companys,re_check_companys,isImport,fjImport,qzImport,qz_talent_level,fj_talent_level,qz_talent_info,fj_talent_info,isMatchZhiren,active,identifyMonth,fst_city_work_time';
        $list = Talent::where($where)->limit(($page-1)*$pageSize, $page*$pageSize)->field($field)->select()->toArray();
        $json = [
            'code' => 200,
            'msg' => '查询成功',
            'data' => $list
        ];
        $ret = base64_encode($this->curlPost("http://sm4.jinjianghc.com/sm4_cbc.php",['data' => json_encode($json),'key' => '3eh2rxdtkULT2zpkDdRiRGH8PL5J0LsZ','iv' => 'jKihG4wF622ocb8z']));
        return $ret;
        //return openssl_encrypt(json_encode($json),'sm4-cbc','3eh2rxdtkULT2zpkDdRiRGH8PL5J0LsZ',OPENSSL_RAW_DATA,'jKihG4wF622ocb8z');

    }

    public function getDict(\think\Request $request){
        $code = $request->param('code');
        if(empty($code)){
            $json = [
                'code' => 0,
                'msg' => '字典值不能为空',
            ];

            $ret = base64_encode($this->curlPost("http://sm4.jinjianghc.com/sm4_cbc.php",['data' => json_encode($json),'key' => '3eh2rxdtkULT2zpkDdRiRGH8PL5J0LsZ','iv' => 'jKihG4wF622ocb8z']));

            //$ret1 = $this->curlPost("http://sm4.jinjianghc.com/sm4_decbc.php",['data' => $ret,'key' => '3eh2rxdtkULT2zpkDdRiRGH8PL5J0LsZ','iv' => 'jKihG4wF622ocb8z']);
            //dump($ret1);die;

            return $ret;
            //return openssl_encrypt(json_encode($json),'sm4-cbc','3eh2rxdtkULT2zpkDdRiRGH8PL5J0LsZ',OPENSSL_RAW_DATA,'jKihG4wF622ocb8z');
        }
        $dict_self = DictApi::findDictByCode($code);
        if(!$dict_self){
            $json = [
                'code' => 200,
                'msg' => '查询成功，无此字典',
                'data' => null
            ];
            $ret = base64_encode($this->curlPost("http://sm4.jinjianghc.com/sm4_cbc.php",['data' => json_encode($json),'key' => '3eh2rxdtkULT2zpkDdRiRGH8PL5J0LsZ','iv' => 'jKihG4wF622ocb8z']));
            return $ret;
            //return openssl_encrypt(json_encode($json),'sm4-cbc','3eh2rxdtkULT2zpkDdRiRGH8PL5J0LsZ',OPENSSL_RAW_DATA,'jKihG4wF622ocb8z');
        }
        $child_dict = DictApi::findChildDictByCode($code);
        if(count($child_dict) > 0){
            $res = array_merge([$dict_self->toArray()],$child_dict);
        }else{
            $res = $dict_self;
        }
        $json = [
            'code' => 200,
            'msg' => '查询成功',
            'data' => $res
        ];

        $ret = base64_encode($this->curlPost("http://sm4.jinjianghc.com/sm4_cbc.php",['data' => json_encode($json),'key' => '3eh2rxdtkULT2zpkDdRiRGH8PL5J0LsZ','iv' => 'jKihG4wF622ocb8z']));

        return $ret;
        //return openssl_encrypt(json_encode($json),'sm4-cbc','3eh2rxdtkULT2zpkDdRiRGH8PL5J0LsZ',OPENSSL_RAW_DATA,'jKihG4wF622ocb8z');
    }

    public function getCheckLog(\think\Request $request){
        $mainId = $request->param('mainId');
        $enterpriseId = $request->param("enterpriseId");
        $category = $request->param("category");
        $type = $request->param("type");
        $list = [];
        switch ($type) {
            case 1:
                $talentInfo = TalentApi::getOne($mainId);
                $talent_condition = TalentConditionApi::getOne($talentInfo["talent_condition"]);
            case 2:
            case 3:
            case 4:
            case 6:
            case 7:
            case 8:
            case 9:
            case 19:
            case 20:
                $list = TalentLogApi::getList($type, $mainId);
                break;
            case 10:
                if ($enterpriseId) {
                    $where[] = ["mainId", "=", $enterpriseId];
                    $ids = \app\enterprise\model\EnterpriseRecord::where($where)->column("id");
                    $ids[] = $enterpriseId;
                    $where = [];
                    $where[] = ["type", "=", $type];
                    $where[] = ["active", "=", 1];
                    $where[] = ["mainId", "in", $ids];
                    $list = TalentChecklog::where($where)->order("createTime desc")->select();
                } else {
                    $list = TalentLogApi::getList($type, $mainId);
                }
                break;
        }
        $new_list = [];
        foreach ($list as $key => $item) {
            $new_item["description"] = $item["description"];
            switch ($item['type']) {
                case 2:
                case 3:
                case 4:
                case 6:
                case 7:
                case 8:
                case 9:
                case 19:
                    $new_item["stateName"] = \app\common\state\LivingAllowanceState::getStateName($item["state"]);
                    $new_item["stepName"] = \app\common\state\LivingAllowanceState::getStepName($item["step"]);
                    $new_item["stateChange"] = $item["stateChange"];
                    break;
                case 20:
                    $new_item["stepName"] = IntegralState::getLogStepName($item["state"]);
                    $new_item["stateName"] = IntegralState::getLogStateName($item["state"], $item["last_state"]);
                    if ($item["last_state"] && $item["new_state"]) {
                        $new_item["stateChange"] = sprintf("%s -> %s", IntegralState::getLogChangeName($item["last_state"]), IntegralState::getLogChangeName($item["new_state"], $item["last_state"]));
                    } else {
                        $new_item["stateChange"] = "";
                    }
                    break;
                case 10:
                    if ($item["category"] == "enterprise_change") {
                        switch ($item['step']) {
                            case 100:
                                $new_item["stepName"] = "<span class='label'>用户操作</span>";
                                break;
                            case 101:
                                $new_item["stepName"] = "<span class='label label-primary'>审核</span>";
                                break;
                            case 102:
                                $new_item["stepName"] = "<span class='label label-danger'>设置冻结</span>";
                                break;
                            case 103:
                                $new_item["stepName"] = "<span class='label label-info'>重置密码</span>";
                                break;
                        }
                        if ($category == "close_account") {
                            $new_item["stateName"] = \app\common\state\MainState::getStateName($item['state']);
                        } else {
                            switch ($item['state']) {
                                case 1:
                                    if ($item["stateChange"]) {
                                        $new_item["stateName"] = "<span class='label label-success'>待提交</span>";
                                    } else {
                                        $item['stateChange'] = "修改密码";
                                    }
                                    break;
                                case 2:
                                    $new_item["stateName"] = "<span class='label label-success'>待审核</span>";
                                    break;
                                case 3:
                                    $new_item["stateName"] = "<span class='label label-danger'>审核驳回</span>";
                                    break;
                                case 4:
                                    $new_item["stateName"] = "<span class='label label-primary'>审核通过</span>";
                                    break;
                                case 5:
                                    $new_item["stateName"] = "<span class='label label-warm'>重新提交</span>";
                                    break;
                                case 6:
                                    $new_item["stateName"] = "<span class='label label-danger'>初审驳回</span>";
                                    break;
                                case 7:
                                    $new_item["stateName"] = "<span class='label label-primary'>初审通过</span>";
                                    break;
                            }
                        }
                        $new_item["stateChange"] = $item['stateChange'];
                    } else {
                        switch ($item['step']) {
                            case 100:
                                $new_item["stepName"] = "<span class='label'>用户操作</span>";
                                break;
                            case 101:
                                $new_item["stepName"] = "<span class='label label-primary'>注册审核</span>";
                                break;
                            case 102:
                                $new_item["stepName"] = "<span class='label label-danger'>设置冻结</span>";
                                break;
                            case 103:
                                $new_item["stepName"] = "<span class='label label-info'>重置密码</span>";
                                break;
                        }
                        switch ($item['state']) {
                            case 1:
                                $new_item["stateName"] = "<span class='label label-success'>待审核</span>";
                                break;
                            case 2:
                                $new_item["stateName"] = "<span class='label label-danger'>审核驳回</span>";
                                break;
                            case 3:
                                $new_item["stateName"] = "<span class='label label-primary'>审核通过</span>";
                                break;
                            case 4:
                                $new_item["stateName"] = "<span class='label label-primary'>重新提交</span>";
                                break;
                            case 5:
                                $new_item["stateName"] = "<span class='label label-danger'>初审驳回</span>";
                                break;
                            case 6:
                                $new_item["stateName"] = "<span class='label label-primary'>初审通过</span>";
                                break;
                            default:
                                break;
                        }
                        $new_item["stateChange"] = $item['stateChange'];
                    }
                    break;
                case 1:
                    if ($item["step"] && $item["step"] != 3) {
                        $new_item["stepName"] = \app\common\state\LivingAllowanceState::getStepName($item["step"]);
                    } else {
                        $new_item["stepName"] = DictApi::getCheckLogStepName($item["state"], $item["step"]);
                    }
                    if (in_array($item["state"], [TalentState::REVERIFY_FAIL, TalentState::ZX_FAIL, TalentState::ANNOUNCED_REVERIFY_FAIL, TalentState::PUBLISH_FAIL])) {
                        $new_item["stateName"] = '<span class="label label-danger">审核不通过</span>';
                    } else if (in_array($item["state"], [TalentState::BASE_VERIFY_PASS, TalentState::BASE_REVERIFY_PASS, TalentState::FST_VERIFY_PASS, TalentState::DEPT_VERIFY_PASS, TalentState::REVERIFY_PASS])) {
                        if ($item["step"] == 3) {
                            if ($item["new_state"] == TalentState::SCND_SUBMIT) {
                                $new_item["stateName"] = '<span class="label label-danger">审核驳回</span>';
                            } else if ($item["new_state"] == TalentState::DEPT_VERIFY_PASS) {
                                $new_item["stateName"] = '<span class="label label-primary">审核通过</span>';
                            } else {
                                $new_item["stateName"] = '<span class="label label-success">待审核</span>';
                            }
                            if ($item["active"] === 0 && !in_array($item["companyId"], explode(",", $talent_condition["companyIds"]))) {
                                $new_item["stateName"] = '<span class="label">已废弃</span>';
                            }
                        } else {
                            $new_item["stateName"] = '<span class="label label-primary">审核通过</span>';
                        }
                    } else if (in_array($item["state"], [TalentState::BASE_REJECT, TalentState::BASE_REVERIFY_REJECT, TalentState::FST_VERIFY_REJECT, TalentState::DEPT_VERIFY_REJECT, TalentState::REVERIFY_REJECT])) {
                        $new_item["stateName"] = '<span class="label label-danger">审核驳回</span>';
                    } else if (in_array($item["state"], [TalentState::ZX_PASS, TalentState::ANNOUNCED, TalentState::ANNOUNCED_REVERIFY_PASS, TalentState::PUBLISH_PASS, TalentState::CERTIFICATED])) {
                        $new_item["stateName"] = '<span class="label label-primary">审核通过</span>';
                    } else if (in_array($item["state"], [TalentState::FST_SAVE, TalentState::SCND_SAVE])) {
                        $new_item["stateName"] = '<span class="label">保存未提交</span>';
                    } else if (in_array($item["state"], [TalentState::REVERIFY_CANCEL])) {
                        $new_item["stateName"] = '<span class="label label-primary">撤销审核</span>';
                    } else if (!$item["state"]) {
                        if ($item["typeFileId"]) {
                            $new_item["stateName"] = '<span class="label">添加附件</span>';
                        }
                    } else {
                        if (($item["last_state"] == TalentState::BASE_REJECT && $item["state"] == TalentState::FST_SUBMIT) || ($item["last_state"] == TalentState::FST_VERIFY_REJECT && $item["state"] == TalentState::SCND_SUBMIT)) {
                            $new_item["stateName"] = '<span class="label label-success">待审核（重新提交）</span>';
                        } else {
                            $new_item["stateName"] = '<span class="label label-success">待审核</span>';
                        }
                    }
                    if ($item["step"] == 3) {
                        $company = CompanyApi::getOne($item["companyId"]);
                        if ($item["active"] == 0) {
                            $new_item["description"] = "等待部门审核";
                            $new_item["stateChange"] = str_replace("部门", '"' . $company["name"] . '"', DictApi::getTalentInfoStateName($item["state"], $item["step"]));
                        } else {
                            $new_item["stateChange"] = sprintf("%s -> %s", str_replace("部门", '"' . $company["name"] . '"', DictApi::getTalentInfoStateName($item["state"], $item["step"])), DictApi::getTalentInfoStateName($item["new_state"], $item["step"]));
                        }
                    } else {
                        if ($item["last_state"] && $item["new_state"]) {
                            $new_item["stateChange"] = sprintf("%s -> %s", DictApi::getTalentInfoStateName($item["last_state"], $list[$key + 1]["step"]), DictApi::getTalentInfoStateName($item["new_state"], $list[$key - 1]["step"], $item["last_state"]));
                        } else {
                            $new_item["stateChange"] = $item["stateChange"] ?: "";
                        }
                    }
                    break;
            }
            $new_item["createUser"] = $item["updateUser"] && strpos($item["updateUser"], "企业用户") === false ? $item["updateUser"] : $item["createUser"]; //$item["updateUser"] ?: $item["createUser"];
            if ($new_item["createUser"] != "用户") {
                list($name, $company) = explode("(", $new_item["createUser"]);
                $where = [];
                $where[] = ["name", "=", $name];
                $user = \app\admin\model\User::where($where)->find();
                if ($user) {
                    $new_item["createUser"] = implode("(", [$user["account"], $company]);
                }
            }
            $new_item["createTime"] = $item["updateTime"] ?: $item["createTime"];
            $new_list[] = $new_item;
        }
        if ($type == ProjectState::TALENT) {
            if ($talentInfo["oldId"]) {
                $where = [];
                $where[] = ["mainId", "=", $talentInfo["oldId"]];
                $where[] = ["type", "=", ProjectState::TALENT];
                $before_list = Db::table("un_talent_checklog")->where($where)->order("createTime desc")->select();
                foreach ($before_list as $before_item) {
                    $new_list[] = [
                        "stepName" => DictApi::getOldStepNameByStep($before_item["step"]),
                        "stateName" => DictApi::getOldStateNameByState($before_item["state"]),
                        "stateChange" => $before_item["stateChange"],
                        "description" => $before_item["description"],
                        "createUser" => $before_item["createUser"],
                        "createTime" => $before_item["createTime"]
                    ];
                }
            }
        }

        if ($type == ProjectState::LEVELCHANGE) {
            $where = [];
            $where[] = ["mainId", "=", $mainId];
            $where[] = ["type", "=", ProjectState::LEVELCHANGE];
            $before_list = Db::table("un_talent_checklog")->where($where)->order("createTime desc")->select();
            foreach ($before_list as $before_item) {
                $new_list[] = [
                    "stepName" => DictApi::getOldStepNameByStep($before_item["step"]),
                    "stateName" => DictApi::getOldStateNameByState($before_item["state"]),
                    "stateChange" => $before_item["stateChange"],
                    "description" => $before_item["description"],
                    "createUser" => $before_item["createUser"],
                    "createTime" => $before_item["createTime"]
                ];
            }
        }

        $json = [
            'code' => 200,
            'msg' => '查询成功',
            'data' => $new_list
        ];

        $ret = base64_encode($this->curlPost("http://sm4.jinjianghc.com/sm4_cbc.php",['data' => json_encode($json),'key' => '3eh2rxdtkULT2zpkDdRiRGH8PL5J0LsZ','iv' => 'jKihG4wF622ocb8z']));
        return $ret;
    }

    public function getSysUser(\think\Request $request){
        $pageSize = $request->param('pageSize',20);
        $page = $request->param('page',1);
        $where[] = ['type','=',1];
        $where[] = ['u.id','>',1];
        $list = User::alias("u")
            ->field("u.id,u.account,u.password,u.salt,u.name,u.phone,u.email,u.companyId,c.name as companyName,r.name as roleName,u.sex,u.status,u.freezeTime,u.createTime")
            ->leftJoin("sys_company c", "c.id=u.companyId")
            ->leftJoin("sys_role r", "r.id=u.roleId")
            ->where($where)
            ->limit(($page-1)*$pageSize, $page*$pageSize)->select()->toArray();
        //$list = Enterprise::where($where)->limit(($page-1)*$pageSize, $page*$pageSize)->order("createTime", 'desc')->field('id,industryFieldNew,enterpriseTag,organizationTag,institutionTag,enterpriseType,name,idCard,street,address,legal,ephone,agentName,agentPhone,username,password,bankCard,bankNetwork,bank,agentEmail,imgurl,bankImg,domainImg,typeImg,beian,checkState,checkMsg,checkUser,active,activeMsg,createTime,updateUser,updateTime,modify_fields,modify_files')->select()->toArray();
        $json = [
            'code' => 200,
            'msg' => '查询成功',
            'data' => $list
        ];
        $ret = base64_encode($this->curlPost("http://sm4.jinjianghc.com/sm4_cbc.php",['data' => json_encode($json),'key' => '3eh2rxdtkULT2zpkDdRiRGH8PL5J0LsZ','iv' => 'jKihG4wF622ocb8z']));
        return $ret;
    }

    public function getShuoBo(\think\Request $request){
        $pageSize = $request->param('pageSize',20);
        $page = $request->param('page',1);
        $list = laModel::limit(($page-1)*$pageSize, $page*$pageSize)->select()->toArray();

    }

    public function test(){
        $str = "Hello World!";
        //$encrypt = openssl_encrypt(json_encode($str),'sm4-cbc','3eh2rxdtkULT2zpkDdRiRGH8PL5J0LsZ',OPENSSL_RAW_DATA,'jKihG4wF622ocb8z');

        $json = [
            'code' => 0,
            'msg' => '字典值不能为空',
        ];


        $encrypt = $this->curlPost("http://report.com/common/data/getDict",[]);

        $decrypt = openssl_decrypt($encrypt,'sm4-cbc','3eh2rxdtkULT2zpkDdRiRGH8PL5J0LsZ',OPENSSL_RAW_DATA,'jKihG4wF622ocb8z');
        //$decrypt = $this->curlPost("http://sm4.jinjianghc.com/decode.php",['data' => $encrypt]);

        dump($decrypt);
    }

    private function curlPost($url, $postFields) {

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); //若果报错 name lookup timed out 报错时添加这一行代码
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $ret = curl_exec($ch);
        if (false == $ret) {
            $result = curl_error($ch);
        } else {
            $rsp = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            if (200 != $rsp) {
                $result = "请求状态 " . $rsp . " " . curl_error($ch);
            } else {
                $result = $ret;
            }
        }
        curl_close($ch);
        return $result;
    }

}