<?php
/**
 * 易优CMS
 * ============================================================================
 * 版权所有 2016-2028 海南赞赞网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.eyoucms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 小虎哥 <1105415366@qq.com>
 * Date: 2018-4-3
 */

namespace weapp\Verify\logic;

use think\Db;

/**
 * 业务逻辑
 */

load_trait('controller/Jump');
class VerifyLogic
{
    use \traits\controller\Jump;

    // 添加订单表字段处理
    public function addShopOrderTableHandle($prefix = '')
    {
        if (!empty($prefix)) {
            // 订单表字段
            $shopOrderTableField = Db::query("SHOW COLUMNS FROM {$prefix}shop_order");
            $shopOrderTableField = get_arr_column($shopOrderTableField, 'Field');

            // 核销记录表ID(weapp_verify表)
            if (!empty($shopOrderTableField) && !in_array('verify_id', $shopOrderTableField)) {
                $sql = "ALTER TABLE `{$prefix}shop_order` ADD COLUMN `verify_id`  int(11) unsigned NOT NULL DEFAULT '0' COMMENT '核销记录表ID(weapp_verify表)' AFTER `coupon_price`";
                @Db::execute($sql);
            }
            // 订单物流类型(1:快递发货; 2:到店核销;)
            if (!empty($shopOrderTableField) && !in_array('logistics_type', $shopOrderTableField)) {
                $sql = "ALTER TABLE `{$prefix}shop_order` ADD COLUMN `logistics_type`  int(11) unsigned NOT NULL DEFAULT '1' COMMENT '订单物流类型(1:快递发货; 2:到店核销;)' AFTER `verify_id`";
                @Db::execute($sql);
            }

            schemaTable('shop_order');
        }
    }

    // 添加文档表字段处理
    public function addArchivesTableHandle($prefix = '')
    {
        if (!empty($prefix)) {
            // 文档表字段
            $archivesTableField = Db::query("SHOW COLUMNS FROM {$prefix}archives");
            $archivesTableField = get_arr_column($archivesTableField, 'Field');

            // 商品物流支持类型
            if (!empty($archivesTableField) && !in_array('logistics_type', $archivesTableField)) {
                $sql = "ALTER TABLE `{$prefix}archives` ADD COLUMN `logistics_type`  varchar(100) DEFAULT '' COMMENT '商品物流支持类型(1: 物流配送; 2: 到店核销)' AFTER `prom_type`";
                @Db::execute($sql);
            }

            schemaTable('archives');
        }
    }

    // 删除订单表字段处理 -- 目前废弃，后续新版本再去掉
    public function delShopOrderTableHandle($prefix = '')
    {
        // if (!empty($prefix)) {
        //     // 订单表字段
        //     $shopOrderTableField = Db::query("SHOW COLUMNS FROM {$prefix}shop_order");
        //     $shopOrderTableField = get_arr_column($shopOrderTableField, 'Field');

        //     // 核销记录表ID(weapp_verify表)
        //     if (!empty($shopOrderTableField) && in_array('verify_id', $shopOrderTableField)) {
        //         $sql = "ALTER TABLE `{$prefix}shop_order` DROP COLUMN `verify_id`";
        //         @Db::execute($sql);
        //     }
        //     // 订单物流类型(1:快递发货; 2:到店核销;)
        //     if (!empty($shopOrderTableField) && in_array('logistics_type', $shopOrderTableField)) {
        //         $sql = "ALTER TABLE `{$prefix}shop_order` DROP COLUMN `logistics_type`";
        //         @Db::execute($sql);
        //     }

        //     schemaTable('shop_order');
        // }
    }

    // 删除文档表字段处理 -- 目前废弃，后续新版本再去掉
    public function delArchivesTableHandle($prefix = '')
    {
        // if (!empty($prefix)) {
        //     // 文档表字段
        //     $archivesTableField = Db::query("SHOW COLUMNS FROM {$prefix}archives");
        //     $archivesTableField = get_arr_column($archivesTableField, 'Field');

        //     // 商品物流支持类型
        //     if (!empty($archivesTableField) && in_array('logistics_type', $archivesTableField)) {
        //         $sql = "ALTER TABLE `{$prefix}archives` DROP COLUMN `logistics_type`";
        //         @Db::execute($sql);
        //     }

        //     schemaTable('archives');
        // }
    }

    // 核销订单添加和更新处理
    public function verifyOrderCreateHandle($orderData = [], $userInfo = [], $post = [], $weappInfo = [])
    {
        // 核销功能开启则执行
        if (!empty($weappInfo['data']['openVerify']) && 1 === intval($weappInfo['data']['openVerify'])) {
            // 核销订单添加核销表信息
            if (empty($orderData['prom_type']) && !empty($post['store_id']) && !empty($post['verifyShow'])) {
                $insert = [
                    'users_id' => intval($userInfo['users_id']),
                    'order_id' => intval($orderData['order_id']),
                    'store_id' => intval($post['store_id']),
                    'verify_code' => $this->createVerifyCode(12),
                    'buyer' => $post['buyer'],
                    'phone' => $post['phone'],
                    'add_time' => getTime(),
                    'update_time' => getTime()
                ];
                $verify_id = Db::name('weapp_verify')->insertGetId($insert);
                if (!empty($verify_id)) {
                    $orderData['verify_id'] = intval($verify_id);
                    // 更新核销订单信息
                    $update = [
                        'logistics_type' => 2,
                        'mobile' => $post['phone'],
                        'consignee' => $post['buyer'],
                        'verify_id' => intval($verify_id),
                        'update_time' => getTime(),
                    ];
                    Db::name('shop_order')->where('order_id', $orderData['order_id'])->update($update);
                }
            }
        }

        // 返回数据
        return $orderData;
    }

    // 核销订单确认核销后续处理
    public function verifyOrderConfirmHandle($post = [], $weappInfo = [])
    {
        if (empty($weappInfo['data']['openVerify'])) $this->error('请先开启核销功能');

        // 查询核销订单记录
        $where = [
            'order_id' => intval($post['order_id']),
            'users_id' => intval($post['users_id']),
        ];
        if (!empty($weappInfo['data']['openSecondVerify'])) {
            if (empty($post['verify_code'])) $this->error('请输入订单核销码');
            // 去除空格
            $searchString = " ";
            $replaceString = "";
            $post['verify_code'] = str_replace($searchString, $replaceString, $post['verify_code']);
            $where['verify_code'] = $post['verify_code'];
        }
        $weappVerifyLog = Db::name('weapp_verify')->where($where)->find();
        if (empty($weappVerifyLog)) $this->error('未查询到核销码订单');
        if (1 === intval($weappVerifyLog['verify_status'])) $this->error('订单已核销');

        // 查询订单主表信息
        $where = [
            'logistics_type' => 2,
            'order_id' => intval($post['order_id']),
            'verify_id' => intval($weappVerifyLog['verify_id']),
        ];
        $orderData = Db::name('shop_order')->where($where)->find();
        if (empty($orderData) || 1 !== intval($orderData['order_status'])) $this->error('订单不允许核销');

        // 更新订单主表信息
        $update = [
            'order_status' => 3,
            'update_time' => getTime(),
            'confirm_time' => getTime()
        ];
        $result = Db::name('shop_order')->where($where)->update($update);
        if (!empty($result)) {
            // 更新核销订单记录
            $update = [
                'verify_status' => 1,
                'admin_id' => session('admin_id'),
                'verify_time' => getTime(),
                'update_time' => getTime()
            ];
            $result = Db::name('weapp_verify')->where('verify_id', $weappVerifyLog['verify_id'])->update($update);
            if (!empty($result)) {
                // 核销完成
                AddOrderAction($post['order_id'], 0, session('admin_id'), 3, 1, 1, '核销成功', '管理员确认订单核销');
                $this->success('核销成功');
            } else {
                // 订单退回待核销状态
                $update = [
                    'order_status' => 1,
                    'update_time' => getTime()
                ];
                Db::name('shop_order')->where($where)->update($update);
            }
        }
        $this->error('核销失败');
    }

    // 核销订单显示核销信息处理
    public function verifyOrderShowHandle($usersID = 0, $orderData = [], $weappInfo = [])
    {
        $where = [
            'a.users_id' => $usersID,
            'a.order_id' => $orderData['order_id'],
        ];
        $field = 'b.*, a.*';
        $result = Db::name('weapp_verify')->alias('a')->field($field)->where($where)->join('__WEAPP_VERIFY_STORE__ b', 'a.store_id = b.store_id')->find();
        $result['store_city'] = !empty($result['store_city']) ? get_city_name($result['store_city']) : '';
        $result['store_area'] = !empty($result['store_area']) ? get_area_name($result['store_area']) : '';
        $result['store_logo'] = !empty($result['store_logo']) ? get_default_pic($result['store_logo']) : '';
        $result['verify_code'] = !empty($result['verify_code']) ? wordwrap($result['verify_code'], 4, ' ', true) : '';
        $result['store_coverpic'] = !empty($result['store_coverpic']) ? get_default_pic($result['store_coverpic']) : '';
        $result['store_province'] = !empty($result['store_province']) ? get_province_name($result['store_province']) : '';
        $result['store_address'] = $result['store_province'] . ' ' . $result['store_city'] . ' ' . $result['store_area'] . ' ' . $result['store_address'];
        // dump($result);exit;
        return $result;
    }

    // 生成核销码
    private function createVerifyCode($length = 12)
    {
        $chars = "0123456789";
        $char_len = strlen($chars);
        $verify_code = '';
        for ($i = 0; $i < $length; $i++) {
            $loop = mt_rand(0, ($char_len - 1));
            $verify_code .= $chars[$loop];
        }
        $isCount = Db::name('weapp_verify')->where('verify_code', $verify_code)->count();
        if (!empty($isCount)) $verify_code = $this->createVerifyCode(12);

        // 返回数据
        return $verify_code;
    }
}
