<?php

namespace app\youzan\logic;

use app\admin\common\User;
use app\admin\model\ActionLog;
use app\admin\model\ProcessOrder;
use app\txx\model\YzGood;
use app\youzan\model\PlatformYouzan;
use think\Exception;
use think\facade\Cache;
use think\facade\Db;

//商品处理层
class Goodup
{
    private static $offline_result_info_id = '0024';//从有赞平台下架商品的原因编码,注意环境不同,编码可能不同,生产环境是0024,测试环境是0021

    //提交商品上线
    public static function create(array $data = [])
    {

        $isonline = [];
        $i = 0;
        Db::startTrans();
        try {

            $all_list = Db::name("platform_youzan")
                ->where(["platform_id" => $data['platform_id'], "is_del" => PlatformYouzan::$del_normal])
                ->whereIn('spuCode', array_column($data['good_data'], 'spuCode'))
                ->column('id,exam_status', 'spuCode');

            $all_nake = Db::name("good_nake")
                ->where(["min_num" => 1, "is_del" => 0])
                ->whereIn('spuCode', array_column($data['good_data'], 'spuCode'))
                ->column('id', 'spuCode');

            foreach ($data['good_data'] as $value) {
//                $count = Db::name("good_nake")->where(["spuCode" => $value['spuCode'], "is_del" => 0])->count();


                //校验是否存在起订量为1的信息
                if (empty($all_nake[$value['spuCode']])) {
                    $god = Db::name("good_basic")
                        ->field('id,good_name,good_thumb_img,chargerid')
                        ->where(["spuCode" => $value['spuCode'], "is_del" => 0])
                        ->find();
                    if ($god) {
                        $tp = [];
                        $tp['spuCode'] = $value['spuCode'];
                        $tp['good_name'] = $god['good_name'];
                        $tp['good_img'] = $god['good_thumb_img'];
//                        $tp['exam_status'] = $ist['exam_status'];
                        $spec = Db::name("good_spec")->where(["spuCode" => $value['spuCode'], "is_del" => 0])->select()->toArray();
                        $speclist = [];
                        if (!empty($spec)) {
                            foreach ($spec as $val) {
                                $temp = [];
                                $temp['id'] = $val['id'];
                                $temp['spuCode'] = $val['spuCode'];
                                $temp['spec_id'] = $val['spec_id'];
                                $temp['spec_value_id'] = $val['spec_value_id'];
                                $temp['is_del'] = $val['is_del'];
                                $sp = Db::name("specs")->where(["id" => $val['spec_id']])->find();
                                $temp['spec_name'] = isset($sp["spec_name"]) ? $sp["spec_name"] : "";
                                $spv = Db::name("spec_value")->where(["id" => $val['spec_value_id']])->find();
                                $temp['spec_value'] = isset($spv["spec_value"]) ? $spv["spec_value"] : "";
                                $speclist[] = $temp;
                            }
                        }
                        $tp["speclist"] = empty($speclist) ? [] : $speclist;
                        $is_no_1[] = $tp;
                    }

                }
                if (!empty($is_no_1)) {
                    Db::rollback();
                    return app_show(1010, "存在起订量不为1的商品", $is_no_1);
                }

                //校验是否存在上线
                $ist = isset($all_list[$value['spuCode']]) ? $all_list[$value['spuCode']] : [];
                if ($ist) {
                    $god = Db::name("good_basic")
                        ->field('id,good_name,good_thumb_img,chargerid')
                        ->where(["spuCode" => $value['spuCode'], "is_del" => 0])
                        ->find();
                    if ($god) {
                        $tp = [];
                        $tp['spuCode'] = $value['spuCode'];
                        $tp['good_name'] = $god['good_name'];
                        $tp['good_img'] = $god['good_thumb_img'];
                        $tp['exam_status'] = $ist['exam_status'];
                        $spec = Db::name("good_spec")->where(["spuCode" => $value['spuCode'], "is_del" => 0])->select()->toArray();
                        $speclist = [];
                        if (!empty($spec)) {
                            foreach ($spec as $val) {
                                $temp = [];
                                $temp['id'] = $val['id'];
                                $temp['spuCode'] = $val['spuCode'];
                                $temp['spec_id'] = $val['spec_id'];
                                $temp['spec_value_id'] = $val['spec_value_id'];
                                $temp['is_del'] = $val['is_del'];
                                $sp = Db::name("specs")->where(["id" => $val['spec_id']])->find();
                                $temp['spec_name'] = isset($sp["spec_name"]) ? $sp["spec_name"] : "";
                                $spv = Db::name("spec_value")->where(["id" => $val['spec_value_id']])->find();
                                $temp['spec_value'] = isset($spv["spec_value"]) ? $spv["spec_value"] : "";
                                $speclist[] = $temp;
                            }
                        }
                        $tp["speclist"] = empty($speclist) ? [] : $speclist;
                        $isonline[] = $tp;
                    }

                }
                if (!empty($isonline)) {
                    Db::rollback();
                    return app_show(1009, "存在已上线产品", $isonline);
                }


                //改变编码规则,将原来的skuCode后两位换成序列号
                //str_pad字符串填充
                $skuCode = makeNo("SN");
                $skuCode = substr($skuCode, 0, -2) . str_pad($i, 2, '0', STR_PAD_LEFT);
                $tmp = [
                    "platform_id" => $data['platform_id'],
                    "online_reason" => $data['online_reason'],
                    "online_remark" => $data['online_remark'],
                    "spuCode" => $value['spuCode'],
                    "skuCode" => $skuCode,
                    "exam_status" => PlatformYouzan::$exam_status_0,
                    "is_del" => PlatformYouzan::$del_normal,
                    "createrid" => $data['createrid'],
                    "creater" => $data['creater'],
                    "updaterid" => $data['createrid'],
                    "updater" => $data['creater'],
                    "addtime" => date("Y-m-d H:i:s"),
                    "updatetime" => date("Y-m-d H:i:s")
                ];
                $i++;
                //修改状态,添加待办
                $create = Db::name("platform_youzan")->insert($tmp, true);
                if ($create > 0) {

                    Db::name("good_platform")->insert([
                        "spuCode" => $value['spuCode'],
                        "skuCode" => $skuCode,
                        'platform_code' => $data['platform_id'],
                        "online_reason" => $data['online_reason'],
                        "online_remark" => $data['online_remark'],
                        "exam_status" => 0,
                        'is_online' => 0,
                        "status" => 1,
                        "is_del" => 0,
                        "addtime" => date("Y-m-d H:i:s"),
                        "updatetime" => date("Y-m-d H:i:s"),
                        "creater" => $data['creater'],
                        "createrid" => $data['createrid'],
                    ]);

                    ActionLog::logAdd(['id' => $data['createrid'], 'nickname' => $data['creater']], [
                        "order_code" => $skuCode,
                        "status" => $tmp['exam_status'],//这里的status是之前的值
                        "action_remark" => '',//备注
                        "action_type" => "create"//新建create,编辑edit,更改状态status
                    ], "YZSX", $tmp['exam_status'], $tmp);

                    ProcessOrder::AddProcess(['id' => $data['createrid'], 'nickname' => $data['creater']], [
                        "order_type" => 'YZSX',
                        "order_code" => $skuCode,
                        "order_id" => $create,
                        "order_status" => $tmp['exam_status'],
                        "before_status" => $tmp['exam_status'],
                        'holder_id' => Db::name('good_basic')->where(["spuCode" => $value['spuCode'], "is_del" => 0])->value('chargerid', 0),
                    ]);
                    $iso = Db::name("good")->where(["spuCode" => $value['spuCode'], "is_del" => 0])->find();
                    if ($iso == false) {
                        unset($value['id']);
                        $value['addtime'] = date("Y-m-d H:i:s");
                        $value['updatetime'] = date("Y-m-d H:i:s");
                    } else {
                        $value['id'] = $iso['id'];
                        $value['updatetime'] = date("Y-m-d H:i:s");
                    }
                    $up = Db::name("good")->strict(false)->save($value);
                    if (!$up) {
                        Db::rollback();
                        return error_show(1004, "提交失败");
                    }
                } else {
                    Db::rollback();
                    return error_show(1004, "提交失败");
                }
            }
            Db::commit();
            return app_show(0, "提交成功");
        } catch (\Exception $e) {
            Db::rollback();
            return error_show(1004, $e->getMessage());
        }

    }


    //审核并将商品推送到有赞平台
    public static function youzanGoodUpOnline(int $platform_youzan_id = 0, array $data = [],int $uid=0,string $uname='')
    {

        Db::startTrans();
        try {

            $db = new PlatformYouzan();

            $rs = $db
                ->field('a.id,a.platform_id,a.spuCode,a.skuCode,a.exam_status,gb.good_name,gb.weight,gb.good_img,gb.cat_id,gb.good_info_img,gb.chargerid')
                ->alias('a')
                ->where(['a.id' => $platform_youzan_id, 'a.is_del' => $db::$del_normal])
                ->leftJoin('good_basic gb', 'gb.spuCode=a.spuCode')
                ->findOrEmpty();

            if ($rs->isEmpty()) throw new Exception('该商品上线记录不存在');
            if ($rs->exam_status != $db::$exam_status_0) throw new Exception('该商品并不是待审核状态');

            $old_exam_status = $rs->exam_status;

//            $userinfo = GetUserInfo($data['token']);

            //platform_youzan 更新信息
            $update_data = [
                'exam_status' => $data['exam_status'],
                'updaterid' => $uid,//isset($userinfo['data']['id']) ? $userinfo['data']['id'] : 0,
                'updater' => $uname,//isset($userinfo['data']['nickname']) ? $userinfo['data']['nickname'] : '',
                'updatetime' => date('Y-m-d H:i:s'),
                'distribution'=>implode(',',$data['distribution']),
            ];

            //good_platform 更新信息
            $update_good_platform_data = ['updatetime' => date('Y-m-d H:i:s')];

            $res = true;

            //审核通过
            if ($data['exam_status'] == $db::$exam_status_1) {

//                $ladder_info = Db::name('good_ladder')
//                    ->field('id,cost_fee')
//                    ->where('id', $data['good_ladder_id'])
//                    ->where('is_del', 0)
//                    ->find();
//
//                if (empty($ladder_info)) throw new Exception('该商品阶梯记录不存在');

                //运费,单位分,整数
                $nake_info = Db::name('good_nake')
//                    ->where(['spuCode' => $rs->spuCode, 'is_del' => 0])
//                    ->where('min_num', '<=', $data['start_sale_num'])
                    ->field('id,delivery_fee,cost_fee')
                    ->where('id', $data['good_ladder_id'])
                    ->findOrEmpty();

                $post_fee = isset($nake_info['delivery_fee']) ? $nake_info['delivery_fee'] : 0;

                $desc = explode(',', $rs->good_info_img);
                $desc_string = [];
                foreach ($desc as $value) {
                    $desc_string[] = "<img src='$value' />";
                }

                //计算系统售价
                $sale_price = self::getSalePrice([
                    'spuCode' => $rs->spuCode,
                    'platform_id' => $rs->platform_id,
                    'min_num' => $data['start_sale_num'],
                    'relaComNo' => $data['relaComNo'],
//                    'platform_id' => $rs->platform_id
                ]);

                $update_data = array_merge($update_data, [
                    'yz_cat_id' => $data['yz_cat_id'],
                    'is_support_barter' => $data['is_support_barter'],
                    'sale_price' => $sale_price,
                    'cost_fee' => $nake_info['cost_fee'] ?? 0,
                    'final_price' => $data['final_price'],
                    'start_sale_num' => $data['start_sale_num'],
                    'reject_reason' => '',
                    'post_fee' => $post_fee,
                    'desc' => implode('', $desc_string),//商品描述
                    'good_ladder_id' => $data['good_ladder_id'],
                    'tags' => implode(',', $data['tags']),
                ]);

                //调有赞项目的接口,从有赞平台上线该商品
                $curl_data = [
                    'item_no' => $rs->skuCode,//商品自定义编码 skuCode
                    'item_type' => $data['item_type'],//0实物商品
                    'title' => $rs->good_name,//商品标题
                    'is_support_barter' => $data['is_support_barter'],//是否支持换货。1:支持;0:不支持
                    'desc' => implode('', $desc_string),//商品描述
                    'item_weight' => $rs->weight,
                    'category_id' => $rs->cat_id,
                    'auto_listing_time' => $data['auto_listing_time'],//0立即售出,传值表示定时(要大于当前时间戳)
                    'stock_deduct_mode' => 0,//0拍下减库存
                    'is_display' => 1,//1上架商品
//                    'quantity' => '1111111111',//库存数,库存数不管,用户自己去有赞平台调整这个数
                    'hide_stock' => 0,//0显示库存,1不显示库存
                    'origin' => $data['origin'],//系统售价
                    'price' => $data['final_price'],//最后售价
                    'uid' => $uid,//isset($userinfo['data']['id']) ? $userinfo['data']['id'] : 0,
                    'nickname' => $uname,//isset($userinfo['data']['nickname']) ? $userinfo['data']['nickname'] : '',
                    'good_img' => $rs->good_img,//图片集合
                    'post_fee' => $post_fee,//运费,单位分,整数
                    'sell_point' => '',//商品卖点信息
                    'yz_cat_id' => $data['yz_cat_id'],//有赞类目id
                    'start_sale_num' => $data['start_sale_num'],//商品起售数,默认为1
                    'tags' => implode(',', $data['tags']),//标签id,多个以,分割
                    'distribution'=>$data['distribution'],
                ];
                $host = config('app.yz_domain');
                $response = curl_request($host . 'api/yz_goodup', $curl_data);
                $response = json_decode($response, true);

                if ($response['code'] != 0) {
                    //上架失败
                    $res = false;
                    $update_data = array_merge($update_data, ['exam_status' => $db::$exam_status_7, 'offline_fail_reason' => $response['message']]);
//                    $update_good_platform_data = array_merge($update_good_platform_data,[]);
                } else {
                    //上架成功
                    $update_data = array_merge($update_data, ['exam_status' => $db::$exam_status_6, 'offline_fail_reason' => '', 'online_time' => date('Y-m-d H:i:s')]);
                    if ($response['data']['plat_code'] != '') {
                        $update_data['plat_code'] = $response['data']['plat_code'];
                        $update_good_platform_data = array_merge($update_good_platform_data, ['plat_code' => $response['data']['plat_code']]);
                    }

                    $update_good_platform_data = array_merge($update_good_platform_data, ['exam_status' =>3, 'online_time' => date('Y-m-d H:i:s'), 'is_online' => 1]);
                }

            } else {

                $update_data['reject_reason'] = $data['reject_reason'];
                $update_good_platform_data['exam_status'] = 5;
            }

            //更新
            $db->where('id', $platform_youzan_id)
                ->where('exam_status', '=', $db::$exam_status_0)
                ->save($update_data);

            Db::name('good_platform')
                ->where(['is_del' => 0, 'spuCode' => $rs->spuCode, 'skuCode' => $rs->skuCode, 'platform_code' => $rs->platform_id, 'exam_status' => 0])
                ->update($update_good_platform_data);

            //添加审核记录
            ActionLog::logAdd([
                'id' => $uid,//isset($userinfo['data']['id']) ? $userinfo['data']['id'] : 0,
                'nickname' => $uname//isset($userinfo['data']['nickname']) ? $userinfo['data']['nickname'] : ''
            ], [
                "order_code" => $rs->skuCode,//编号
                "status" => $old_exam_status,
                "action_remark" => '',//备注
                "action_type" => "status"//新建create,编辑edit,更改状态status
            ], 'YZSX', $update_data['exam_status'], $update_data);

            ProcessOrder::AddProcess([
                'id' => $uid,//isset($userinfo['data']['id']) ? $userinfo['data']['id'] : 0,
                'nickname' => $uname,//isset($userinfo['data']['nickname']) ? $userinfo['data']['nickname'] : ''
            ], [
                "order_type" => 'YZSX',
                "order_code" => $rs->skuCode,//咨询单详情编号
                "order_id" => $rs->id,
                "order_status" => $update_data['exam_status'],
                "before_status" => $old_exam_status,
                'holder_id' => $rs->chargerid,
            ]);

            if ($res) {
                Db::commit();
                return app_show(0, '操作成功');
            } else throw new Exception('上架失败,' . $response['message']);

        } catch (Exception $exception) {
            Db::rollback();
            return error_show(1005, $exception->getMessage());
        }
    }

    //计算系统售价
    private static function getSalePrice(array $data = [])
    {
        $spuCode = $data['spuCode'];

        $platid = $data['platform_id'];

        $platform = Db::name("platform")->where(["id" => $platid, "is_del" => 0])->find();

        $num = $data['min_num'];
        if ($platform['platform_type'] != 1) throw new Exception('平台为非对接平台');

        $good = Db::name("good_basic")->where(["spuCode" => $spuCode, "is_del" => 0])->find();
        if ($good == false) throw new Exception('商品数据未找到');

        $nakelist = Db::name("good_nake")
            ->where(['spuCode' => $spuCode, "is_del" => 0])
            ->where("min_num", "<=", $num)
            ->order("min_num desc")
            ->find();
        if ($nakelist == false) {
            $nakelist = Db::name("good_nake")->where(['spuCode' => $spuCode, "is_del" => 0])->order("min_num asc")->find();

            //非库存品的话,继续校验最小起订量
            //库存品的话,不足采购起订量的时候,取采购最小起订量
            if ($good['is_stock'] == 0) throw new Exception("起订量不足{$nakelist['min_num']}");
        }

        //计算毛利率
        $budget = get_budget($good['cat_id'], $data['relaComNo'], $data['platform_id']);

        $top_cat_id = made($good['cat_id']);//获取所有分类
        $top_cat_id = isset($top_cat_id[0]['id']) ? $top_cat_id[0]['id'] : 0;//获取顶级分类id

        $sale_cost_fee = 0;
        if ($good['is_gold_price'] == 1 && $top_cat_id == 6) {
//            $saleprice =  $good['noble_weight']*$good["cgd_gold_price"] + $nakelist['cost_fee']/(1-$budget)*$good['noble_weight']+$nakelist['mark_fee']+$nakelist['package_fee']+$nakelist['cert_fee']+$nakelist['nake_fee']+$nakelist['delivery_fee'];

            //系统售价=(贵金属重量*供应商采购金价 + 工艺费*贵金属重量+加标费+包装费+证书费+成本裸价+运费+其他费用)/(1-成本售价/100)
            $saleprice = ($good['noble_weight'] * $good["cgd_gold_price"] + $nakelist['cost_fee'] * $good['noble_weight'] + $nakelist['mark_fee'] + $nakelist['package_fee'] + $nakelist['cert_fee'] + $nakelist['nake_fee'] + $nakelist['delivery_fee'] + $nakelist['other_fee']) / (1 - $budget);

            //计算工艺费
            //销售工艺费=(( 商品重量* 供应商采购金价 + 采购成本工艺费* 商品重量+包装费+加标费+证书费+产品裸价+其他费用)/(1-成本售价/100)-(包装费+加标费+证书费+产品裸价0+运费+其他费用) )/商品重量-供应商采购金价
            $sale_cost_fee = (($good['noble_weight'] * $good["cgd_gold_price"] + $nakelist['cost_fee'] * $good['noble_weight'] + $nakelist['package_fee'] + $nakelist['mark_fee'] + $nakelist['cert_fee'] + $nakelist['nake_fee'] + $nakelist['other_fee'] + $nakelist['delivery_fee']) / (1 - $budget) - ($nakelist['package_fee'] + $nakelist['mark_fee'] + $nakelist['cert_fee'] + $nakelist['nake_fee'] + $nakelist['delivery_fee'] + $nakelist['other_fee'])) / $good['noble_weight'] - $good["cgd_gold_price"];
        } else {
//            $saleprice = ($nakelist['mark_fee'] + $nakelist['package_fee'] + $nakelist['cert_fee'] + $nakelist['delivery_fee'] + $nakelist['nake_fee']) / (1 - $budget);
//            (加标费+包装费+证书费+成本裸价+运费)/(1-成本售价/100)=系统售价
//            $saleprice = (加标费 + 包装费 + 证书费 + 运费 + 成本裸价+其他费用) / (1 - $budget);
            $saleprice = $nakelist['nake_total'] / (1 - $budget);
        }
        return round($saleprice, 2);
    }


    //有赞商品重新上线(上线失败的、下线后又重新上线的)
    public static function goodupOnlineAgain(int $platform_youzan_id = 0, string $token = '')
    {

        Db::startTrans();

        try {

            $db = new PlatformYouzan();

            $rs = $db
                ->field('id,spuCode,skuCode,platform_id,exam_status')
                ->where(['id' => $platform_youzan_id, 'is_del' => $db::$del_normal])
                ->whereIn('exam_status', [$db::$exam_status_7, $db::$exam_status_8])
                ->findOrEmpty();

            if ($rs->isEmpty()) return error_show(1005, '该商品上线记录不存在或不允许重新上线');

            $userinfo = GetUserInfo($token);
            $uid = isset($userinfo['data']['id']) ? $userinfo['data']['id'] : 0;
            $nickname = isset($userinfo['data']['nickname']) ? $userinfo['data']['nickname'] : '';

            $old_status = $rs->exam_status;

            //更新
            $db
                ->where('id', $platform_youzan_id)
                ->save([
                    'exam_status' => $db::$exam_status_0,
                    'updaterid' => $uid,
                    'updater' => $nickname,
                    'updatetime' => date('Y-m-d H:i:s'),
                ]);

            //更新
            Db::name('good_platform')
                ->where(['is_del' => 0, 'spuCode' => $rs->spuCode, 'skuCode' => $rs->skuCode, 'platform_code' => $rs->platform_id])
                ->where('exam_status', '<>', 0)
                ->update(['exam_status' => 0, 'updatetime' => date('Y-m-d H:i:s')]);

            $stn = ["order_code" => $rs->skuCode, "status" => $old_status, "action_remark" => '', "action_type" => "status"];
            ActionLog::logAdd(['id' => $uid, 'nickname' => $nickname], $stn, "YZSX", $db::$exam_status_0, ['id' => $platform_youzan_id]);

            $process = ["order_code" => $rs->skuCode, "order_id" => $rs->id, "order_status" => $db::$exam_status_0, "order_type" => 'YZSX', "before_status" => $old_status, 'holder_id' => $uid];
            ProcessOrder::AddProcess(['id' => $uid, 'nickname' => $nickname], $process);

            Db::commit();

            return app_show(0, '操作成功');

        } catch (Exception $exception) {

            Db::rollback();

            return error_show(1005, $exception->getMessage());
        }

    }


    //商品上线详情
    public static function getYzGoodupInfo(array $param = [])
    {
        $data = Db::name('platform_youzan')
            ->where('id', $param['platform_youzan_id'])
            ->whereOr('skuCode', $param['skuCode'])
            ->findOrEmpty();

        if (empty($data)) return error_show(1005, '查询不到该记录');


        $good_data = Db::name("good_basic")
            ->withoutField('createrid,creater,is_del,addtime,updatetime')
            ->where(["is_del" => 0, "spuCode" => $data['spuCode']])
            ->findOrEmpty();
        if (empty($good_data)) return error_show(1004, "未找到商品数据");

        $data = array_merge($data, $good_data);

        $plat = Db::name("platform")->where(["id" => $data['platform_id']])->find();
//        $data['skuCode'] = $data['skuCode'];
        $data['platform_code'] = $data['platform_id'];
        $data['platform_code_en'] = isset($plat['platform_code']) ? $plat['platform_code'] : "";
        $data['platform_name'] = isset($plat['platform_name']) ? $plat['platform_name'] : "";
//        $data['online_reason'] = $good_platform['online_reason'];
//        $data['online_time'] = $data['online_time'];
//        $data['online_remark'] = $good_platform['online_remark'];
//        $data['exam_status'] = $good_platform['exam_status'];
//        $data['is_online'] = $good_platform['is_online'];
//        $data['plat_code'] = $data['plat_code'];
//        $data['exclusive'] = makeExcluse($data['is_exclusive']);
        $unit = Db::name("unit")->where(["id" => $data['good_unit']])->find();
        $data['unit'] = isset($unit['unit']) ? $unit['unit'] : '';
        $data['cat_info'] = made($data['cat_id'], []);
        $data['yz_cat_info'] = made_youzan($data['yz_cat_id'], []);
        $spec = Db::name("good_spec")->where(["spuCode" => $data['spuCode'], "is_del" => 0])->select()->toArray();
//        $supplier = Db::name("supplier")->where(["code" => $data['supplierNo']])->find();

        $names = User::getIns()->handle('getCodeAndName',['code'=>[$data['supplierNo'],$data['companyNo']]]);

        $data['supplierName'] = $names['data'][$data['supplierNo']]??'';
//        $data['noble_name'] = isset($data['noble_metal']) && $data['noble_metal'] != 0 ? $this->noble[$data['noble_metal']] : "";
//        $company = Db::name("business")->where(["companyNo" => $data['companyNo']])->find();
        $data['company'] = $names['data'][$data['companyNo']]??'';//isset($company['company']) ? $company['company'] : "";
        if ($data['brand_id'] != 0) {
            $brand = Db::name("brand")->where(["id" => $data['brand_id']])->find();
            $data["brand_name"] = isset($brand['brand_name']) ? $brand['brand_name'] : "";
        } else {
            $data["brand_name"] = "";
            $data["brand_id"] = "";
        }
        $data['origin_place_cn'] = "";
        $data['delivery_place_cn'] = "";
        if ($data['delivery_place'] !== "") {
            $place = ["provice_code" => "", "city_code" => "", "area_code" => ""];
            list($place['provice_code'], $place['city_code'], $place['area_code']) = explode(",", $data['delivery_place']);
            $data['delivery_place_cn'] = GetAddr(json_encode($place));
        }
        if ($data['origin_place'] !== "") {
            $place = ["provice_code" => "", "city_code" => "", "area_code" => ""];
            list($place['provice_code'], $place['city_code'], $place['area_code']) = explode(",", $data['origin_place']);
            $data['origin_place_cn'] = GetAddr(json_encode($place));
        }
        $excluse = makeExcluse($data['is_exclusive']);
        $data['exclusive'] = $excluse;
        $data["good_info_img"] = $data['good_info_img'] != "" ? $data['good_info_img'] : [];
        $data["good_img"] = $data['good_img'] != "" ? $data['good_img'] : [];
        $speclist = [];
        if (!empty($spec)) {
            foreach ($spec as $value) {
                $temp = [];
                $temp['id'] = $value['id'];
                $temp['spuCode'] = $value['spuCode'];
                $temp['spec_id'] = $value['spec_id'];
                $temp['spec_value_id'] = $value['spec_value_id'];
                $temp['is_del'] = $value['is_del'];
                $sp = Db::name("specs")->where(["id" => $value['spec_id']])->find();
                $temp['spec_name'] = isset($sp["spec_name"]) ? $sp["spec_name"] : "";
                $spv = Db::name("spec_value")->where(["id" => $value['spec_value_id']])->find();
                $temp['spec_value'] = isset($spv["spec_value"]) ? $spv["spec_value"] : "";
                $speclist[] = $temp;
            }
        }
        $data["speclist"] = empty($speclist) ? [] : $speclist;
        $ladder = Db::name("good_ladder")->where(['skuCode' => $data['skuCode'], "is_del" => 0])->select()->toArray();
        $data["ladderlist"] = !empty($ladder) ? $ladder : [];
        $nakelist = Db::name("good_nake")->where(['spuCode' => $data['spuCode'], "is_del" => 0])->select()->toArray();
//        $catinfo = Db::name("cat")->where(["id"=>$data['cat_id']])->find();

//        $cat_top_list = $data['yz_cat_info'];
//        $cat_top_id = isset($cat_top_list[0]['id']) ? $cat_top_list[0]['id'] : 0;
        // $budget = isset($catinfo['order_rate']) ? $catinfo['order_rate']/100:0;
        $gold_price = 0;
        if ($data['is_gold_price'] == 1 && $data['cost_fee'] != 0 && $data['good_price'] == 0) {
            $gold_price = Db::name("gold_price1")->where(["type" => $data['noble_metal'], "status" => 1, "is_del" => 0])->order("addtime desc")->value('price', 0);
        }
        $data['gold_price'] = $gold_price;
        $nakearry = [];
        if (!empty($nakelist)) {

            //实时金价
            foreach ($nakelist as $value) {
                $value['sale_price'] = $value['nake_total'];

                //计算最终售价
                if ($data['is_gold_price'] == 1 && $data['cost_fee'] != 0 && $data['good_price'] == 0) {
                    //普通商品:直接用财务提交的售价字段;
                    //贵金属( 商品重量* 最新金价 + 工艺费(财务定价提交的)* 商品重量+包装费+加标费+证书费+产品裸价+其他费用)=商品库商品直接下单的售价
                    $value['sale_price'] = ($data['weight'] * $gold_price + $value['cost_fee'] * $data['weight'] + $value['package_fee'] + $value['mark_fee'] + $value['cert_fee'] + $value['nake_fee'] + $value['other_fee']);
                }
                $nakearry[] = $value;
            }
        }
        $proof = Db::name("good_proof")->where(["spuCode" => $data['spuCode'], "is_del" => 0])->order("updatetime desc")->field("id,proof_type,proof_url")->find();
        $data['proof'] = isset($proof) && $proof != false ? $proof : [];
        $data["nakelist"] = $nakearry;

        //补充采购员字段
        //成本表里的创建人,也是线上商品的采购人,为了防止混淆,给creater取个别名
        $temp_basic_info = Db::name('good_basic')
            ->field('id,createrid purchase_id,creater purchase')
            ->where(['spuCode' => $data['spuCode'], 'is_del' => 0])
            ->find();
        $data['purchase_id'] = $temp_basic_info['purchase_id'];
        $data['purchase'] = $temp_basic_info['purchase'];

        //补充商品详情链接字段
        $data['detail_url'] = YzGood::where(['is_del' => 0, 'item_no' => $data['skuCode']])
            ->value('detail_url', '');

        //格式化配送方式
        $data['distribution'] = explode(',', $data['distribution']);

        return app_show(0, "获取成功", $data);
    }


    //有赞商品下线
    public static function youzanGoodOffline(int $platform_youzan_id = 0, array $data = [])
    {

        Db::startTrans();

        try {

            $db = new PlatformYouzan();

            $rs = $db
                ->field('id,spuCode,skuCode,exam_status,platform_id')
                ->where(['id' => $platform_youzan_id, 'is_del' => $db::$del_normal])
                ->findOrEmpty();

            if ($rs->isEmpty()) throw new Exception('该记录不存在');
            if ($rs->exam_status == $db::$exam_status_8) throw new Exception('该商品已下线,无法重复下线');

            $userinfo = GetUserInfo($data['token']);

            $old_status = $rs->exam_status;

            $curl_data = [
                'item_no' => $rs->skuCode,//商品自定义编码 skuCode
                'uid' => isset($userinfo['data']['id']) ? $userinfo['data']['id'] : 0,
                'nickname' => isset($userinfo['data']['nickname']) ? $userinfo['data']['nickname'] : '',
            ];

            if ($rs->exam_status == $db::$exam_status_6) {
                //已上线的要调用有赞接口下线
                //调有赞项目的接口,从有赞平台下线该商品
                $host = config('app.yz_domain');
                $response = curl_request($host . 'api/yz_goodup_offline', $curl_data);

                $response = json_decode($response, true);

                if ($response['code'] != 0) throw new Exception($response['message']);
            }

            $db::where('id', $platform_youzan_id)
                ->update([
                    'exam_status' => $db::$exam_status_8,
                    'offline_reason_id' => $data['offline_reason_id'],
                    'offline_remark' => $data['offline_remark'],
                    'updaterid' => isset($userinfo['data']['id']) ? $userinfo['data']['id'] : 0,
                    'updater' => isset($userinfo['data']['nickname']) ? $userinfo['data']['nickname'] : '',
                    'updatetime' => date('Y-m-d H:i:s')
                ]);

            //更新
            Db::name('good_platform')
                ->where(['is_del' => 0, 'spuCode' => $rs->spuCode, 'skuCode' => $rs->skuCode, 'platform_code' => $rs->platform_id])
                ->where('exam_status', '<>', 5)
                ->update(['exam_status' => 5, 'updatetime' => date('Y-m-d H:i:s')]);

            //下线记录表增加记录
            Db::name('good_offline_log_youzan')
                ->insert([
                    'spuCode' => $rs->spuCode,
                    'skuCodes' => $rs->skuCode,
                    'good_name' => Db::name("good_basic")->where('spuCode', $rs->spuCode)->value('good_name', ''),
                    'offline_reason' => $data['offline_reason_id'],
                    'offline_remark' => $data['offline_remark'],
                    'createrid' => isset($userinfo['data']['id']) ? $userinfo['data']['id'] : 0,
                    'creater' => isset($userinfo['data']['nickname']) ? $userinfo['data']['nickname'] : '',
                    'addtime' => date('Y-m-d H:i:s')
                ]);

            $stn = ["order_code" => $rs->skuCode, "status" => $old_status, "action_remark" => '', "action_type" => "status"];
            ActionLog::logAdd(['id' => $curl_data['uid'], ['nickname' => $curl_data['nickname']]], $stn, "YZSX", $db::$exam_status_8, $data);

            $process = ["order_code" => $rs->skuCode, "order_id" => $rs->id, "order_status" => $db::$exam_status_8, "order_type" => 'YZSX', "before_status" => $old_status, 'holder_id' => $curl_data['uid']];
            ProcessOrder::AddProcess(['id' => $curl_data['uid'], ['nickname' => $curl_data['nickname']]], $process);

            Db::commit();

            return app_show(0, '操作成功');

        } catch (Exception $exception) {
            Db::rollback();
            return error_show(1005, $exception->getMessage());
        }

    }

    //有赞下线商品列表
    public static function youzanOfflineList(array $data = [])
    {
        $where = [];
        if ($data['start_date'] != '' && $data['end_date'] != '') $where[] = ['addtime', 'between', [$data['start_date'], $data['end_date']]];
        if ($data['creater'] != '') $where[] = ['creater', 'like', '%' . $data['creater'] . '%'];

        $count = Db::name('good_offline_log_youzan')->where($where)->count('id');

        $list = Db::name('good_offline_log_youzan')
            ->field('id,spuCode,good_name,creater,addtime')
            ->where($where)
            ->order('addtime', 'desc')
            ->page($data['page'], $data['size'])
            ->select()
            ->toArray();

        return app_show(0, "获取成功", ['list' => $list, 'count' => $count]);

    }

    //有赞下线商品详情
    public static function youzanOfflineDetail(int $id = 0)
    {

        $res = Db::name('good_offline_log_youzan')
            ->alias('gol')
            ->field('gol.*,ri.result')
            ->where('gol.id', $id)
            ->leftJoin('result_info ri', 'ri.result_code=gol.offline_reason')
            ->find();

        $res['children_list'] = Db::name('platform_youzan')
            ->alias('gp')
            ->field('gp.id,gp.skuCode,p.platform_name,g.creater purchease,gp.creater')
            ->where(['gp.spuCode' => $res['spuCode']])
            ->whereIn('gp.skuCode', $res['skuCodes'])
            ->leftJoin('platform p', 'p.id=gp.platform_id')
            ->leftJoin('good g', 'g.spuCode=gp.spuCode')
            ->select()
            ->toArray();

        return app_show(0, "获取成功", $res);

    }


    //商品下架(有赞平台操作)
    public static function goodOffLineByYouzan(string $item_no = '')
    {

        Db::startTrans();

        try {

            Db::table('wsm_good_platform')
                ->where(['is_del' => 0, 'skuCode' => $item_no])
                ->update([
                    'exam_status' => 5,
                    'is_online' => 0,
                    'updatetime' => date('Y-m-d H:i:s'),
                ]);

            $good_info = Db::table('wsm_platform_youzan')
                ->alias('py')
                ->field('py.id,py.spuCode,gb.good_name')
                ->leftJoin('good_basic gb', 'gb.spuCode=py.spuCode')
                ->where(['py.is_del' => 0, 'py.exam_status' => 6, 'py.skuCode' => $item_no])
                ->find();

            if (!empty($good_info)) {

                //更新采销上线记录表
                Db::table('wsm_platform_youzan')
                    ->where('id', $good_info['id'])
                    ->update([
                        'exam_status' => 8,
                        'offline_remark' => '有赞平台操作下架',
                        'offline_reason_id' => self::$offline_result_info_id,
                        'updaterid' => 0,
                        'updater' => 'youzan',
                        'updatetime' => date('Y-m-d H:i:s'),
                    ]);

                //下线记录
                Db::table('wsm_good_offline_log_youzan')
                    ->insert([
                        'spuCode' => isset($good_info['spuCode']) ? $good_info['spuCode'] : '',
                        'skuCodes' => $item_no,
                        'good_name' => isset($good_info['good_name']) ? $good_info['good_name'] : '',
                        'offline_reason' => self::$offline_result_info_id,
                        'offline_remark' => '有赞平台操作下架',
                        'createrid' => 0,
                        'creater' => 'youzan',
                        'addtime' => date('Y-m-d H:i:s'),
                    ]);
            }

            Db::commit();
            return app_show(0, '操作成功');

        } catch (Exception $exception) {

            Db::rollback();
            return error_show(0, '操作失败,' . $exception->getMessage());

        }
    }

    //商品删除(有赞平台操作)
    public static function goodDeleteByYouzan(string $item_no = '')
    {

        Db::startTrans();

        try {
            Db::table('wsm_good_platform')
                ->where(['is_del' => 0, 'skuCode' => $item_no])
                ->update([
                    'is_del' => 1,//是否删除,0未删除,1删除
                    'updatetime' => date('Y-m-d H:i:s'),
                ]);

            //更新采销上线记录表
            Db::table('wsm_platform_youzan')
                ->where(['is_del' => 0, 'skuCode' => $item_no])
                ->update([
                    'is_del' => 1,//是否删除,0未删除,1删除
                    'updaterid' => 0,
                    'updater' => 'youzan',
                    'updatetime' => date('Y-m-d H:i:s'),
                ]);

            Db::commit();

            return app_show(0, '操作成功');

        } catch (Exception $exception) {

            Db::rollback();
            return error_show(1005, '操作失败,' . $exception->getMessage());

        }

    }


}