<?php

namespace app\youzan\logic;

use app\admin\model\ActionLog;
use app\admin\model\ProcessOrder;
use app\youzan\model\PlatformYouzan;
use think\Exception;
use think\facade\Cache;
use think\facade\Db;

//商品处理层
class Goodup
{

    //提交商品上线
    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');

            foreach ($data['good_data'] as $value) {
//                $count = Db::name("good_nake")->where(["spuCode" => $value['spuCode'], "is_del" => 0])->count();
                $ist = isset($all_list[$value['spuCode']]) ? $all_list[$value['spuCode']] : [];
                if ($ist) {
                    $god = Db::name("good_basic")
                        ->field('id,good_name,good_thumb_img')
                        ->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)) {
                    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) {
                    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']
                    ]);
                    $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")->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 = [])
    {

        Db::startTrans();
        try {

            $db = new PlatformYouzan();

            $rs = $db
                ->field('a.id,a.spuCode,a.skuCode,a.exam_status,gb.good_name,gb.weight,gb.good_img,gb.cat_id,gb.good_remark')
                ->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']);

            $update_data = [
                'exam_status' => $data['exam_status'],
                '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'),
            ];

            $res = true;

            if ($data['exam_status'] == $db::$exam_status_1) {

                $ladder_info = Db::name('good_ladder')
                    ->field('id,min_num,sale_price,cost_fee')
                    ->where('id', $data['good_ladder_id'])
                    ->where('is_del', 0)
                    ->find();

                if (empty($ladder_info)) throw new Exception('该商品阶梯记录不存在');

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

                //审核通过
                $update_data = array_merge($update_data, [
                    'yz_cat_id' => $data['yz_cat_id'],
                    'is_support_barter' => $data['is_support_barter'],
                    'sale_price' => $ladder_info['sale_price'],
                    'cost_fee' => $ladder_info['cost_fee'],
                    'final_price' => $data['final_price'],
                    'start_sale_num' => $data['start_sale_num'],
                    'reject_reason' => '',
                    'post_fee' => $post_fee,
                    'desc' => $rs->good_remark,//商品描述
                    'good_ladder_id' => $data['good_ladder_id'],
                    'tags' => implode(',', $data['tags']),
                ]);

                //调有赞项目的接口,从有赞平台下线该商品
                $curl_data = [
                    'item_no' => $rs->skuCode,//商品自定义编码 skuCode
                    'item_type' => 0,//0实物商品
                    'title' => $rs->good_name,//商品标题
                    'is_support_barter' => $data['is_support_barter'],//是否支持换货。1:支持;0:不支持
                    'desc' => $rs->good_remark,//商品描述
                    'item_weight' => $rs->weight,
                    'category_id' => $rs->cat_id,
                    'auto_listing_time' => '0',//0立即售出,传值表示定时(要大于当前时间戳)
                    'stock_deduct_mode' => 0,//0拍下减库存
                    'is_display' => 1,//1上架商品
                    'quantity' => '1111111111',//库存数,先随便写个数,待 @戴 确定
                    'hide_stock' => 0,//0显示库存,1不显示库存
                    'origin' => $ladder_info['sale_price'],//系统售价
                    'price' => $data['final_price'],//最后售价
                    'uid' => isset($userinfo['data']['id']) ? $userinfo['data']['id'] : 0,
                    'nickname' => 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,多个以,分割
                ];
                $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']]);
                } else {
                    //上架成功
                    $update_data = array_merge($update_data, ['exam_status' => $db::$exam_status_6, 'offline_fail_reason' => '']);
                    if ($response['data']['plat_code'] != '') $update_data['plat_code'] = $response['data']['plat_code'];
                }

            } else  $update_data['reject_reason'] = $data['reject_reason'];


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

            //添加审核记录
            //修改状态,添加待办
//            'id' => isset($userinfo['data']['id']) ? $userinfo['data']['id'] : 0,
//                'nickname' => isset($userinfo['data']['nickname']) ? $userinfo['data']['nickname'] : '',

            ActionLog::logAdd([
                'id' => isset($userinfo['data']['id']) ? $userinfo['data']['id'] : 0,
                'nickname' => 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' => isset($userinfo['data']['id']) ? $userinfo['data']['id'] : 0,
                'nickname' => 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
            ]);

            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());
        }
    }


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

        $db = new PlatformYouzan();

        $rs = $db
            ->field('id')
            ->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);

        //更新
        $res = $db->where('id', $platform_youzan_id)
            ->save([
                'exam_status' => $db::$exam_status_0,
                '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'),
            ]);

        return $res ? app_show(0, '操作成功') : error_show(1005, '重新发起上线失败');

    }


    //商品上线详情
    public static function getYzGoodupInfo(int $platform_youzan_id = 0)
    {
        $data = Db::name('platform_youzan')
            ->where('id', $platform_youzan_id)
            ->find();

        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']])
            ->find();
        if ($good_data == false) 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();
        $data['supplierName'] = isset($supplier['name']) ? $supplier['name'] : "";
//        $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'] = 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'];

        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,skuCode,exam_status')
                ->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']);

            $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::commit();

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

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

    }

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

        $count = Db::name('platform_youzan')
            ->alias('pyz')
            ->leftJoin('good g', 'g.spuCode=pyz.spuCode')
            ->where($where)
            ->count('pyz.id');

        $list = PlatformYouzan::field('pyz.id,pyz.id platform_youzan_id,pyz.spuCode,g.good_name,pyz.updater,pyz.updatetime')
            ->alias('pyz')
            ->leftJoin('good g', 'g.spuCode=pyz.spuCode')
            ->where($where)
            ->order('pyz.addtime', 'desc')
            ->page($data['page'], $data['size'])
            ->select()
            ->toArray();

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

    }

    //有赞下线商品详情
    public static function youzanOfflineDetail(int $platform_youzan_id = 0)
    {
        $info = PlatformYouzan::where('pyz.id', $platform_youzan_id)
            ->field('pyz.*,g.good_name,r.result,p.platform_name')
            ->alias('pyz')
            ->leftJoin('good g', 'g.spuCode=pyz.spuCode')
            ->leftJoin('result_info r', 'r.result_code=pyz.offline_reason_id')
            ->leftJoin('platform p', 'p.id=pyz.platform_id')
            ->findOrEmpty();

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

    }


}