<?php

declare(strict_types=1);

namespace app\admin\controller\goods;

use app\common\controller\Backend;
use app\admin\traits\Actions;
use think\annotation\route\Group;
use think\annotation\route\Route;
use think\facade\Db;
use app\common\model\ImportSku;
use app\common\model\ShopList;
use app\common\model\StockConfig;
use app\common\model\ShopDelivery;
use app\admin\service\JuShuiTanService;
use app\common\model\CustomerSpec;
use app\common\model\ProductConfig;
use app\common\model\ImportList as ImportListModel;
use app\common\model\ShopList as ShopListModel;
use think\facade\Cache;
#[Group("goods/import_list")]
class ImportList extends Backend
{
    //app\admin\controller\goods\ImportList
    use Actions {
        index as private _index;
        del as private _del;
    }
    private $typeList = null;
    private $tabValue = null;

    protected function _initialize()
    {
        parent::_initialize();
        $this->model = new ImportListModel();
        $this->typeList = StockConfig::where('type_id', 'variety_name')->order('sort desc')->column('title', 'id');
        $this->tabValue = array_keys($this->typeList)[0] ?? null;
        // $this->assign('shopList', ShopList::where('status', 1)->column('name', 'id'));
        $this->assign('typeList',  $this->typeList);
        $this->assign('packingList', StockConfig::where('type_id', 'packing_box')->column('title', 'id'));
    }
    // 获取店铺
    #[Route('GET,POST,JSON', 'getShopList')]
    public function getShopList()
    {
        $shopList = new ShopList();
        $sql_restul = $shopList->alias('s')
            ->join("yun_customer c", "s.customer_id = c.id", "INNER")
            ->where(['s.status' => 1, 'c.status' => 1])
            ->field(['s.id', 's.shop_id', 's.name', 'c.name' => 'nickname'])
            ->select();
        $arr = [];
        foreach ($sql_restul as $item) {
            $arr[$item['id']] = $item['name'] . '(' . '店铺id:' . $item['shop_id'] . ',客户:' . $item['nickname'] . ')';
        }

        return $this->jsonSuccess('', $arr);
    }

    /**
     * 查看
     */
    #[Route('GET,JSON', 'index')]
    public function index()
    {
        if (false === $this->request->isAjax()) {
            return $this->fetch();
        }
        if ($this->request->post('selectpage')) {
            return $this->selectpage();
        }
        [$where, $order, $limit, $with] = $this->buildparams();

        $list = $this->model
            ->withJoin($with, 'left')
            //如果没有使用operate filter过滤的情况下,推荐使用with关联，可以提高查询效率
            //->with($with)
            ->where($where)
            ->order($order)
            ->paginate($limit)
            ->each(function ($item, $key) {
                if (empty($item['type_id'])) {
                    $item['type_id'] = 0;
                }
                $trade_from_list = [];
                if ($item['type_id'] == 1) {
                    $feng_su_trade_from_list = site_config("addonsd.feng_su_trade_from_list");
                    $trade_from_list = $feng_su_trade_from_list;
                } else {
                    $ju_shui_tan_trade_from_list = site_config("addonsd.ju_shui_tan_trade_from_list");
                    $trade_from_list = $ju_shui_tan_trade_from_list;
                }


                $trade_from = $item['trade_from'];
                $trade_from = isset($trade_from_list[$trade_from]) ? $trade_from_list[$trade_from] : $item['trade_from'];
                $item['trade_from'] = $trade_from;
                // $item['trade_from']=empty($item['trade_from'])?'无':$trade_from_list[$trade_from];


                return $item;
            });

        $shops_num = $this->model
            ->where('status', 1)
            ->sum('status');
        $specs_num = $this->model
            ->where('status', 2)
            ->sum('status');

        $result = ['total' => $list->total(), 'rows' => $list->items(), 'shops_num' => $shops_num, 'specs_num' => $specs_num];
        return json($result);
    }

    /**
     * 关联店铺
     */
    #[Route('GET,POST', 'shops')]
    public function shops()
    {
        if (false === $this->request->isPost()) {
            $ids = $this->request->get('ids/s', '');
            $shopList = new ShopList();
            $sql_restul = $shopList->alias('s')
                ->join("yun_customer c", "s.customer_id = c.id", "INNER")
                ->where(['s.status' => 1, 'c.status' => 1])
                ->field(['s.id', 's.shop_id', 's.name', 'c.name' => 'nickname'])
                ->select();
            $arr = [];
            foreach ($sql_restul as $item) {
                $arr[$item['id']] = $item['name'] . '(' . '店铺id:' . $item['shop_id'] . ',客户:' . $item['nickname'] . ')';
            }

            $this->assign('shopList', $arr);
            return $this->fetch();
        }
        $params = array_merge($this->request->post("row/a"), $this->postParams);
        if (empty($params)) {
            $this->error(__('提交的参数不能为空'));
        }
        // if (!$this->request->checkToken('__token__', ['__token__' => $this->request->post('__token__')])) {
        //     $this->error(__('token错误，请刷新页面重试'));
        // }
        foreach ($params as &$value) {
            if (is_array($value)) {
                $value = implode(',', $value);
            }
            if ($value === '') {
                $value = null;
            }
        }
        $ids = $this->request->get('ids/s', '');
        if (empty($params['shop_id'])) $this->error(__('请选择店铺'));
        $result = false;
        Db::startTrans();
        try {
            //更新店铺
            ShopList::where('id', $params['shop_id'])->update(['shop_id' => $ids]);
            //更新状态
            $result = $this->model->where('shop_id', $ids)->update(['status' => 2]);
            if ($this->callback) {
                $callback = $this->callback;
                $callback($this->model);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('没有新增任何数据'));
        }
        $this->success();
    }

    /**
     * 关联规格
     */
    #[Route('GET,POST', 'specs')]
    public function specs(mixed $row = null)
    {
        $ids = $this->request->param('ids');
        $importSku = new ImportSku();
        if (!$row || is_array($row)) {
            $row = $this->model->find($ids);
        }
        if (!$row) {
            $this->error(__('没有找到记录'));
        }
        if (count($this->volidateFields) > 0) {
            foreach ($this->volidateFields as $field => $value) {
                if ($row[$field] != $value) {
                    $this->error(__('没有操作权限'));
                }
            }
        }
        if (false === $this->request->isPost()) {
            $shop_id = $row['shop_id'];
            $shopListModel = new ShopListModel();

            $rows = $shopListModel::where('shop_id', $shop_id)->where('status', 1)->find();

            //修改规格
            $importSku = new ImportSku();
            $sql_data = $importSku->where(['shop_id' => $row['shop_id'], 'sku_id' => $row['sku_id']])->find();
            $spec_id = 0;
            if (!empty($sql_data)) {
                $this->tabValue = $sql_data['variety_id'];
                $spec_id = $sql_data['spec_id'];
            }
            $this->assign('tabValue', $this->tabValue . '');
            $this->assign('spec_id', $spec_id);
            $this->assign('rows', $rows->type_spec ?? '');
            $this->assign('row', $row);

            return $this->fetch();
        }
        $params = $this->request->post("");
        if (empty($params['all_data'])) $this->error(__('请选择规格'));
        $count = 0;
        Db::startTrans();
        try {

            $status = $row['status'];
            $time = time();

            $shopList = new ShopList();
            $productConfig = new ProductConfig();
            $shopDelivery = new ShopDelivery();
            $customerSpec = new CustomerSpec();

            $shopDelivery_list = [];
            $import_list = [];

            $shopDelivery_updata_list = [];
            $todayStart = date('Y-m-d', $time);
            $todayStart = $todayStart . ' 00:00:00';
            switch ($status) {
                case 2:
                    //插入规格
                    ImportSku::insertSpecs($row['shop_id'], $row['sku_id'], (int)$params['all_data'][0]['type_id'], (int)$params['all_data'][0]['id']);

                    //查看有多少规格
                    $list = $this->model::where('shop_id', $row['shop_id'])->where('sku_id', $row['sku_id'])->where('status', 2)->select();

                    foreach ($list as $item) {
                        //插入发货数据
                        $res = JuShuiTanService::setAdditionalPrice(
                            $importSku,
                            $shopList,
                            $productConfig,
                            $shopDelivery,
                            $customerSpec,
                            $item['shop_id'],
                            $item['sku_id'],
                            $params['all_data'][0]['type_id'],
                            $params['all_data'][0]['id'],
                            $params['all_data'][0]['name'],
                            $item
                        );
                        $getPackSpecsFee = $res['getPackSpecsFee'];
                        $shopDelivery_list[] = $res['shopDelivery'];
                        $import_list_item = [
                            'id' => $item['id'],
                            'specs_name'        => $getPackSpecsFee['data']['title'],
                            'pack_specs_id' => $getPackSpecsFee['data']['id'],
                            'labor_cost_money' => $getPackSpecsFee['data']['labor_cost_money'],
                            'one_surcharge_money' => $getPackSpecsFee['one_surcharge_money'],
                            'two_surcharge_money' => $getPackSpecsFee['two_surcharge_money'],
                            'status' => 3
                        ];
                        $import_list[] = $import_list_item;
                        $count++;
                    }
                    $this->model->saveAll($import_list);
                    $shopDelivery->saveAll($shopDelivery_list);
                    break;
                case 3:
                    //修改规格
                    $importSku = new ImportSku();
                    $sql_data = $importSku->where(['shop_id' => $row['shop_id'], 'sku_id' => $row['sku_id']])->find();

                    $result = $sql_data->save([
                        'variety_id'    => (int)$params['all_data'][0]['type_id'],
                        'spec_id'    => (int)$params['all_data'][0]['id']
                    ]);
                    if (!$result) $this->error(__('没有数据被更新'));
                    //查看有多少规格
                    $where = [];
                    $where[] = ['shop_id', '=', $row['shop_id']];
                    $where[] = ['sku_id', '=', $row['sku_id']];
                    $where[] = ['consign_time', '>=', $todayStart];

                    $whereOr = [];
                    $whereOr[] = ['shop_id', '=', $row['shop_id']];
                    $whereOr[] = ['sku_id', '=', $row['sku_id']];
                    $whereOr[] = ['status', '=', 2];

                    $list = $this->model::where($where)->whereOr($whereOr)->select();

                    foreach ($list as $item) {
                        //插入发货数据
                        $res = JuShuiTanService::setAdditionalPrice(
                            $importSku,
                            $shopList,
                            $productConfig,
                            $shopDelivery,
                            $customerSpec,
                            $item['shop_id'],
                            $item['sku_id'],
                            $params['all_data'][0]['type_id'],
                            $params['all_data'][0]['id'],
                            $params['all_data'][0]['name'],
                            $item
                        );
                        $getPackSpecsFee = $res['getPackSpecsFee'];


                        if ($item['status'] == 2) {
                            $shopDelivery_list[] = $res['shopDelivery'];
                        } else if ($item['status'] == 3) {
                            $waybill_no = $res['shopDelivery']['waybill_no'];
                            $shopDelivery_id = JuShuiTanService::get_shopDelivery_id($waybill_no);
                            if ($shopDelivery_id > 0) {
                                $res['shopDelivery']['id'] = $shopDelivery_id;
                                $res['shopDelivery']['updatetime'] = $time;
                                $shopDelivery_updata_list[] = $res['shopDelivery'];
                            }
                        }
                        
                        $import_list_item = [
                            'id' => $item['id'],
                            'specs_name'        => $getPackSpecsFee['data']['title'],
                            'pack_specs_id' => $getPackSpecsFee['data']['id'],
                            'labor_cost_money' => $getPackSpecsFee['data']['labor_cost_money'],
                            'one_surcharge_money' => $getPackSpecsFee['one_surcharge_money'],
                            'two_surcharge_money' => $getPackSpecsFee['two_surcharge_money'],
                            'status' => 3
                        ];

                        $import_list[] = $import_list_item;
                        $count++;
                    }
                    $this->model->saveAll($import_list);
                    $shopDelivery->saveAll($shopDelivery_list);
                    $shopDelivery->saveAll($shopDelivery_updata_list);

                    break;
                default:
                    # code...
                    break;
            }

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        if ($count) {
            return resp_json(200, '操作成功');
        }
        $this->error(__('没有数据被更新'));
    }


    //删除
    #[Route("GET,POST", "del")]
    public function del()
    {
        //通过定义callback回调函数来执行删除后的操作
        $this->callback = function ($ids) {};
        return $this->_del();
    }

    /**
     * 聚水潭同步数据设置
     */
    #[Route('GET,POST,JSON', 'set_jushuitan')]
    public function set_jushuitan()
    {
        if (false === $this->request->isPost()) {
            $row=[];
            $startTime=null;
            $jushuitan=Cache::get('jushuitan');
            if(!empty($jushuitan)||$jushuitan!=null){
                $startTime=$jushuitan['startTime'];
                $startTime=date('Y-m-d H:i:s', $startTime);
            }
            $this->assign('row', $row);
            $this->assign('startTime', $startTime);
            return $this->fetch();
        }

        $params = $this->request->post("");
        if (empty($params['startTime'])) $this->error(__('请选择开始时间'));

        //时间间隔
        $start_end_space_time=10*60;
        //下一次时间间隔
        $next_time_space=7*60;


        //将查询分为，"2026-01-05 00:00:00~2026-01-05 00:05:00",查询该区间的订单，但是该时间区间单独数量可能超过50条，为了性能又不能一次性查询太多，从而进行分页查询，
        //查询不到数据,就往下一个时间区间查询

        $startTime_stamp = strtotime($params['startTime']);
        $endTime_stamp=$startTime_stamp+$start_end_space_time;
        $pageNum=1;

        $jushuitan=[
            'startTime'=>$startTime_stamp,
            'endTime'=>$endTime_stamp,
            'pageNum'=>$pageNum,
            'next_time_space'=>$next_time_space
        ];
        $jushuitan=[
            'startTime'=>$startTime_stamp,
            'endTime'=>$endTime_stamp,
            'pageNum'=>$pageNum,
            'next_time_space'=>$next_time_space
        ];
        $result=Cache::set('jushuitan',$jushuitan);
        if($result) return $this->jsonSuccess('设置成功');
        return $this->jsonError('设置失败');
    }
   
    /**
     * 风速同步数据设置
     */
    #[Route('GET,POST,JSON', 'set_fengsu')]
    public function set_fengsu()
    {
        if (false === $this->request->isPost()) {
            $row=[];
            $startTime=null;
            $fengsu=Cache::get('fengsu');
            if(!empty($fengsu)||$fengsu!=null){
                $startTime=$fengsu['startTime'];
                $startTime=date('Y-m-d H:i:s', $startTime);
            }
            $this->assign('row', $row);
            $this->assign('startTime', $startTime);
            return $this->fetch();
        }

        $params = $this->request->post("");
        if (empty($params['startTime'])) $this->error(__('请选择开始时间'));

        //时间间隔
        $start_end_space_time=10*60;
        //下一次时间间隔
        $next_time_space=7*60;


        //将查询分为，"2026-01-05 00:00:00~2026-01-05 00:05:00",查询该区间的订单，但是该时间区间单独数量可能超过50条，为了性能又不能一次性查询太多，从而进行分页查询，
        //查询不到数据,就往下一个时间区间查询

        $startTime_stamp = strtotime($params['startTime']);
        $endTime_stamp=$startTime_stamp+$start_end_space_time;
        $pageNum=1;

        $fengsu=[
            'startTime'=>$startTime_stamp,
            'endTime'=>$endTime_stamp,
            'pageNum'=>$pageNum,
            'next_time_space'=>$next_time_space
        ];
        $fengsu=[
            'startTime'=>$startTime_stamp,
            'endTime'=>$endTime_stamp,
            'pageNum'=>$pageNum,
            'next_time_space'=>$next_time_space
        ];
        $result=Cache::set('fengsu',$fengsu);
        if($result) return $this->jsonSuccess('设置成功');
        return $this->jsonError('设置失败');
    }
}
