<?php

namespace app\admin\service\setting;

use app\admin\service\AdminBaseService;
use app\model\StockIndexModel;

class StockIndexService extends AdminBaseService
{


    public function index()
    {
        try {
            $list = StockIndexModel::order('sort', 'desc')->order('id', 'desc')->select();
            $rows = [];
            if(!$list->isEmpty()){
                $rows = $list->toArray();
            }

            return $this->toData('0', 'SUCCESS', ['list' => $rows, 'total' => count($rows)]);
        }catch (\Exception $exception){
            return $this->toData('1', '系统繁忙', []);
        }

    }

    public function update($param)
    {
        try {
            if(empty($param['id']) || !is_numeric($param['id'])){
                return $this->toData('1', '参数错误1', []);
            }

            if(!isset($param['sort']) || !is_numeric($param['sort'])){
                return $this->toData('1', '参数错误2', []);
            }

            if(empty($param['status']) || !in_array($param['status'], [1,2])){
                return $this->toData('1', '参数错误3', []);
            }

            $stockIndex = StockIndexModel::where('id', $param['id'])->find();
            if(empty($stockIndex)){
                return $this->toData('1', '目标不存在', []);
            }

            $stockIndex->sort = ceil($param['sort']);
            $stockIndex->status = ceil($param['status']);
            $stockIndex->update_time = date('Y-m-d H:i:s');
            $stockIndex->save();

            // 通知go
            $bool = $this->sendStockIndexToGo($stockIndex->code, $stockIndex->country, $stockIndex->sort, $stockIndex->status);
            if(!$bool){
                return $this->toData('1', '通知行情失败 请重新设置数据', []);
            }
            return $this->toData('0', 'SUCCESS');


        }catch (\Exception $exception){
            return $this->toData('1', '系统繁忙', [$exception->getMessage()]);
        }
    }
}