<?php
/**
 *  ╔═══════════════════════════════════════════════════╗
 *  ║                                                   ║
 *  ║     ██╗  ██╗   █████╗    ██████╗                  ║
 *  ║     ██║  ██║  ██╔══██╗  ██╔═══██╗                 ║
 *  ║     ███████║  ███████║  ██║   ██║                 ║
 *  ║     ██╔══██║  ██╔══██║  ██║   ██║                 ║
 *  ║     ██║  ██║  ██║  ██║  ╚██████╔╝   SNS           ║
 *  ║                                                   ║
 *  ║                                                   ║
 *  ║     © 2023 HaoSNS™ All Rights Reserved            ║
 *  ║     官方网站: https://www.haosns.com                *
 *  ║     本代码由赣州乐易网络科技有限公司®提供             *
 *  ║                                                    *
 *  ║   未经授权禁止复制、传播或用于其他商业目的            *
 *  ║                                                   ║
 *  ╚═══════════════════════════════════════════════════╝
 */


namespace app\api\controller;

use app\adminapi\validate\RealVerifyValidate;
use app\common\model\RealVerify as Model;
use app\common\model\RealVerifyField;
use app\common\model\RealVerifyTypeField;
use app\common\model\RealVerifyType;
use app\common\service\ConfigService;
use think\facade\Log;

class RealVerify extends BaseShopController
{
    public function all()
    {
        $params = $this->request->param();

        if (!empty($params['user_id'])) {
            $uid = $params['user_id'];
        } else {
            $uid = $this->userId;
        }

        $res = Model::where('user_id', $uid)
            ->with([
                'user' => function ($query) {
                    $query->field('id,nickname');
                },
                'type' => function ($query) {
                    $query->field('id,name');
                },
                'fields' => function ($query) {
                    $query->with('typeField');
                }
            ])
            ->where('status', 1)
            ->select()
            ->toArray();

        foreach ($res as &$item) {
            foreach ($item['fields'] as $fieldKey => &$field) {
                if (str_contains($field['typeField']['key'], '手机') || str_contains($field['typeField']['key'], '电话')) {
                    $field['value'] = substr_replace($field['value'], '*********', 1, 9);
                }

                if ($field['typeField']['type'] === '身份证号码') {
                    $field['value'] = substr_replace($field['value'], '****************', 1, 16);
                }

                if ($field['typeField']['type'] === '身份证正面' || $field['typeField']['type'] === '身份证反面') {
                    unset($item['fields'][$fieldKey]);
                }
            }
        }

        return show(1, '查询成功', $res);
    }

    public function status()
    {
        $type_id = $this->request->param('type_id');

        if (empty($type_id)) {
            return show(0, '请求不合法');
        }

        $result = Model::where('user_id', $this->userId)
            ->where('type_id', $type_id)
            ->find();

        if (!$result) {
            return show(0, '查询失败');
        }

        return show(1, '查询成功', $this->request->post('detail') ? $result : []);
    }

    protected function autoVerify1($rn, $sj, $id)
    {
        if (!ConfigService::get('real_verify', 'type_1_auto_status', 0)) {
            return false;
        }
        $host = "https://pdetail.market.alicloudapi.com";
        $path = "/efficient/cellphonedetail/post";
        $method = "POST";
        $appcode = ConfigService::get('real_verify', 'type_1_auto_app_code', '');
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        array_push($headers, "Content-Type" . ":" . "application/x-www-form-urlencoded; charset=UTF-8");
        $bodys = "mobile=$sj&idCard=$id&realName=$rn";
        $url = $host . $path;
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, true);
        if (1 == strpos("$" . $host, "https://")) {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        curl_setopt($curl, CURLOPT_POSTFIELDS, $bodys);
        $response = curl_exec($curl);
        if ($response === false) {
            return false;
        }
        curl_close($curl);
        $res = json_decode($response, true);
        Log::info('个人三要素自动认证', $res ?? []);
        if (!empty($res) && $res['error_code'] == 0 && !empty($res['result']) && $res['result']['VerificationResult'] == 1) {
            return true;
        }
        return false;
    }

    protected function autoVerify2($cn, $lp, $cc)
    {
        if (!ConfigService::get('real_verify', 'type_2_auto_status', 0)) {
            return false;
        }
        $host = "https://kzcpthree.market.alicloudapi.com";
        $path = "/company_three/check";
        $method = "POST";
        $appcode = ConfigService::get('real_verify', 'type_2_auto_app_code', '');
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        array_push($headers, "Content-Type" . ":" . "application/x-www-form-urlencoded; charset=UTF-8");
        $bodys = "creditCode=$cc&companyName=$cn&legalPerson=$lp";
        $url = $host . $path;
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, true);
        if (1 == strpos("$" . $host, "https://")) {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        curl_setopt($curl, CURLOPT_POSTFIELDS, $bodys);
        $response = curl_exec($curl);
        if ($response === false) {
            return false;
        }
        curl_close($curl);
        $res = json_decode($response, true);
        // Log::info('企业三要素自动认证', $res);
        if (!empty($res) && $res['code'] == 200 && !empty($res['data']) && $res['data']['result'] == 1) {
            return true;
        }
        return false;
    }

    public function submit()
    {
        $data = (new RealVerifyValidate())->post()->goCheck('submit');

        $type = RealVerifyType::where('id', $data['type_id'])->find();
        if (!$type) {
            return show(0, '请选择认证类型');
        }

        $record = Model::where('user_id', $this->userId)
            ->where('type_id', $data['type_id'])
            ->find();

        if ($record) {
            return show(0, '请勿重复提交');
        }

        $requiredFieldIds = RealVerifyTypeField::where('real_veify_type_id', $data['type_id'])->where('require', 1)->column('id');

        foreach ($requiredFieldIds as $id) {
            $result = array_filter($data['data'], function ($v) use ($id) {
                return $v['id'] != $id;
            });

            if (empty($result)) {
                return show(0, '请填写必填项');
            }
        }

        $status = 0;

        if ($type->type == 1) {
            $rn = null;
            $sj = null;
            $id = null;

            foreach ($data['data'] as $item) {
                $field = RealVerifyTypeField::where('id', $item['id'])->find();

                if ($field['key'] === '姓名') {
                    $rn = $item['value'];
                } elseif ($field['key'] === '电话号码') {
                    $sj = $item['value'];
                } elseif ($field['key'] === '身份证号码') {
                    $id = $item['value'];
                }
            }

            if (!empty($rn) && !empty($sj) && !empty($id)) {
                if ($this->autoVerify1($rn, $sj, $id)) {
                    $status = 1;
                }
            }
        }

        if ($type->type == 2) {
            $cn = null;
            $lp = null;
            $cc = null;

            foreach ($data['data'] as $item) {
                $field = RealVerifyTypeField::where('id', $item['id'])->find();

                if ($field['key'] === '企业名称') {
                    $cn = $item['value'];
                } elseif ($field['key'] === '法人名称') {
                    $lp = $item['value'];
                } elseif ($field['key'] === '统一信用代码或注册号') {
                    $cc = $item['value'];
                }
            }

            if (!empty($cn) && !empty($lp) && !empty($cc)) {
                if ($this->autoVerify2($cn, $lp, $cc)) {
                    $status = 1;
                }
            }
        }

        $record = Model::create([
            'user_id' => $this->userId,
            'type_id' => $data['type_id'],
            'status' => $status
        ]);

        foreach ($data['data'] as $item) {
            RealVerifyField::create([
                'user_id' => $this->userId,
                'real_verify_id' => $record->id,
                'real_verify_type_field_id' => $item['id'],
                'value' => $item['value'],
            ]);
        }

        return show(1, '提交成功');
    }
}