<?php

namespace Api\Controller;

class CheckController extends PublicController
{
    /**
     * @description: 子类的初始化
     */
    public function _initialize()
    {
        // 调用父类的_initialize方法
        parent::_initialize();
    }
    public function index()
    {
        echo json_encode(array('status' => 1, 'msg' => '认证通过'));
    }
    /**
     * @description: 获取用户手机号 并将手机号写入数据库 并给前端返回 隐藏中间4位的手机号
     */
    public function getPhoneNumber()
    {
        // 检查 sessionKey iv 长度是否合法
        if (strlen($this->session_key) != 24 || strlen($_REQUEST['iv']) != 24) {
            echo json_encode(array('status' => 0, 'msg' => '非法操作1！'));
            exit();
        }
        // Base64 解码 sessionKey
        $aesKey = base64_decode($this->session_key);
        // Base64 解码 iv
        $aesIV = base64_decode($_REQUEST['iv']);
        // Base64 解码加密数据
        $aesCipher = base64_decode($_REQUEST['encryptedData']);
        // 使用 openssl_decrypt 函数进行解密
        $result = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, OPENSSL_RAW_DATA, $aesIV);
        // 将解密后的字符串转换为 JSON 对象
        $dataObj = json_decode($result);
        // 检查解密后的数据是否为 NULL
        if ($dataObj == NULL) {
            echo json_encode(array('status' => 0, 'msg' => '非法操作2！'));
            exit();
        }
        // 检查解密后的数据中的 appid 是否与传入的 appid 一致
        $wx_config = C('weixin');
        $appid = $wx_config['appid'];
        if ($dataObj->watermark->appid != $appid) {
            echo json_encode(array('status' => 0, 'msg' => '非法操作3！'));
            exit();
        }
        //更新数据库  录入获取到的用户手机号
        $where['openid'] = $this->openid;
        $data['tel'] = $dataObj->phoneNumber;
        $userDb = D('user');
        $userDb->where($where)->data($data)->save();
        // 返回解密后的数据对象
        $phoneNumber = $this->maskPhoneNumber($data['tel']);
        echo json_encode(array('status' => 1, 'phoneNumber' => $phoneNumber));
    }
    /**
     * @description: 提交订单
     */
    public function checkout()
    {
        //解构购物车列表 检查合法性 合成product_snapshot快照字段  totol_weight总重字段  totol_num总数量字段(即所有sku的总数)  totol_price总价格字段
        $product_snapshot = array(); //声明product_snapshot快照字段
        $total_num = 0; //声明totol_num字段
        $total_weight = 0; //声明 totol_weight总重字段
        $total_price = 0; //声明totol_price字段
        $cartList = json_decode($_REQUEST['cartList'], true);
        $spuDb = D('spu');
        $skuDb = D('sku');
        $where['shop_id'] = $_REQUEST['shop_id'];

        foreach ($cartList as $index => $cart) {
            $where['id'] = intval($cart['spu_id']);
            $spu = $spuDb->where($where)->find();
            $product_snapshot[$index]['spu_id'] = $spu['id'];
            $product_snapshot[$index]['spu_name'] = $spu['name'];
            $product_snapshot[$index]['spu_number'] = $spu['spu_number'];
            // 确保 spu_photo 是 JSON 数组
            $product_snapshot[$index]['spu_photo'] = json_decode($spu['photo'], true);

            foreach ($cart['skuG'] as $key => $value) {
                $where['id'] = $value;
                $sku = $skuDb->where($where)->find();
                $product_snapshot[$index]['sku_arr'][$key]['arr_name'] = json_decode($spu['bind_sku'], true)[$key]['tit'];
                $product_snapshot[$index]['sku_arr'][$key]['sku_id'] = $sku['id'];
                $product_snapshot[$index]['sku_arr'][$key]['sku_name'] = $sku['name'];
                $product_snapshot[$index]['sku_arr'][$key]['sku_number'] = $sku['sku_number'];
                $product_snapshot[$index]['sku_arr'][$key]['sku_weight'] = $sku['weight']; //重量
                $product_snapshot[$index]['sku_arr'][$key]['sku_price'] = $sku['price']; //单价
                $product_snapshot[$index]['sku_arr'][$key]['sku_totol'] = $cart['countG'][$key]; //数量
                $product_snapshot[$index]['sku_arr'][$key]['sku_unit'] = $sku['unit'];
                // 确保 sku_photo 是 JSON 数组
                $product_snapshot[$index]['sku_arr'][$key]['sku_photo'] = json_decode($sku['photo'], true);
                $product_snapshot[$index]['sku_arr'][$key]['sku_purchase_channel'] = $sku['purchase_channel'];
                //累计重量 价格 数量
                $total_num += $cart['countG'][$key];
                $total_weight += $cart['countG'][$key] * $sku['weight'];
                $total_price += $cart['countG'][$key] * $sku['price'];
            }
        }

        //后台校验总价格 和 前端总价格
        if ($total_price != $_REQUEST['total']) {
            echo json_encode(array('status' => 1, 'msg' => '价格不符！'));
            exit(); //有问题跳出
        }

        // 创建订单
        $data['shop_id'] = $_REQUEST['shop_id'];
        $data['order_sn'] = date('ymdHi') . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT);
        $data['total_weight'] = $total_weight;
        $data['total_price'] = $total_price;
        $data['total_num'] = $total_num;
        $data['openid'] = $this->openid;

        $userDb = D('user');
        $whereUser['openid'] = $this->openid;
        $user = $userDb->where($whereUser)->find();
        $data['receiver'] = $user['name'];
        $data['tel'] = $user['tel'];

        // 再次校验手机号
        if ($user['tel'] == null || $user['tel'] == "") {
            echo json_encode(array('status' => 0, 'msg' => '用户手机号未填'));
            exit(); //没有电话 有问题跳出
        }

        $siteDb = D('receive_site');
        $whereSite['id'] = $_REQUEST['site_id'];
        $whereSite['shop_id'] = $_REQUEST['shop_id'];
        $site = $siteDb->where($whereSite)->find();
        $data['receive_site_id'] = $_REQUEST['site_id'];
        $data['receive_site_name'] = $site['sitename'];
        $data['product_snapshot'] = json_encode($product_snapshot, JSON_UNESCAPED_UNICODE);
        $data['remark'] = $_REQUEST['remark'];
        $data['addtime'] = time();

        $orderDb = D('order');
        $isAdd = $orderDb->data($data)->add();
        // 返回订单信息
        if ($isAdd) {
            echo json_encode(array('status' => 1, 'order_sn' => $data['order_sn']));
        } else {
            echo json_encode(array('status' => 0, 'msg' => '订单添加失败'));
        }
    }
}
