package com.ruoyi.web.controller.app;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.ArticleClassify;
import com.ruoyi.common.core.domain.entity.User;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.ServiceUtil;
import com.ruoyi.common.utils.onenet.Token;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.ss.article.service.IArticleService;
import com.ruoyi.ss.articleClassify.service.IArticleClassifyService;
import com.ruoyi.ss.carousel.domain.CarouselQuery;
import com.ruoyi.ss.carousel.domain.CarouselVO;
import com.ruoyi.ss.carousel.service.CarouselService;
import com.ruoyi.ss.city.domain.City;
import com.ruoyi.ss.city.domain.CityQuery;
import com.ruoyi.ss.city.service.ICityService;
import com.ruoyi.ss.article.domain.Article;
import com.ruoyi.ss.feeRule.service.IFeeRuleService;
import com.ruoyi.ss.product.domain.ProductQuery;
import com.ruoyi.ss.product.domain.ProductVO;
import com.ruoyi.ss.product.service.IProductService;
import com.ruoyi.ss.room.service.IRoomService;
import com.ruoyi.ss.store.domain.StoreQuery;
import com.ruoyi.ss.intention.domain.Intention;
import com.ruoyi.ss.intention.service.IIntentionService;
import com.ruoyi.ss.model.service.IModelService;
import com.ruoyi.ss.order.service.IOrderService;
import com.ruoyi.ss.store.domain.StoreVO;
import com.ruoyi.ss.store.service.IStoreAssembler;
import com.ruoyi.ss.store.service.impl.StoreAssemblerImpl;
import com.ruoyi.ss.user.service.IUserService;
import com.ruoyi.system.service.*;
import com.ruoyi.ss.store.service.IStoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.List;

/**
 * app接口（不需要登录的）
 *  校验
 * @author ruoyi
 */
@RestController
@RequestMapping("/app")
public class AppController extends BaseController
{

    @Autowired
    private ISysDictDataService dictDataService;

    @Resource
    public IRoomService roomService;

    @Resource
    private IOrderService orderService;

    @Autowired
    private IArticleService asArticleService;

    @Autowired
    private IArticleClassifyService asArticleClassifyService;

    @Resource
    private IUserService userService;

    @Autowired
    private SysLoginService loginService;

    @Resource
    private ICityService cityService;

    @Autowired
    private IStoreService storeService;

    @Autowired
    private IIntentionService intentionService;

    @Autowired
    private IStoreAssembler storeAssembler;

    @Autowired
    private CarouselService carouselService;

    @Autowired
    private IProductService productService;

    /**
     * 验证码登录
     */
    @PostMapping("/appCodeLogin")
    public AjaxResult appCodeLogin(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.appCodeLogin(loginBody);
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 获取字典类型列表
     */
    @GetMapping("/getDictData")
    public AjaxResult cityList(String dictType)
    {
        SysDictData sysDictData = new SysDictData();
        sysDictData.setDictType(dictType);
        List<SysDictData> list = dictDataService.selectDictDataList(sysDictData);
        return success(list);
    }

    /**
     * 查询已开通城市列表
     */
    @GetMapping("/city/list")
    public AjaxResult cityList(CityQuery city)
    {
        logger.info("查询城市列表：【city={}】", city);
        city.setIsOpen(true);
        List<City> list = cityService.selectRlCityList(city);
        return success(list);
    }

    /**
     * 查询所有地级市城市列表
     */
    @GetMapping("/allCity/list")
    public AjaxResult allCityList(String cityName)
    {
        logger.info("查询所有地级市城市列表：【cityName={}】", cityName);
        List<City> list = cityService.selectAllCity(cityName);
        return success(list);
    }

    /**
     * 根据定位获取哪个城市
     */
    @GetMapping("/getCity")
    public AjaxResult getCity(String lon,String lat)
    {
        logger.info("根据定位获取哪个城市：【lon={},lat={}】", lon, lat);
        AjaxResult ajax = AjaxResult.success();
        City city = cityService.getCityByLocation(lon, lat);
        ajax.put(AjaxResult.DATA_TAG, city);
        return ajax;
    }

    /**
      * 根据定位获取附近店铺列表
      */
    @PostMapping("/getStoreListByLocation")
    public TableDataInfo getStoreListByLocation(@RequestBody StoreQuery query)
    {
        logger.info("根据定位获取附近店铺列表：【StoreQuery={}】", JSON.toJSONString(query));
        Long cityId = query.getCityId();
        if(ObjectUtil.isNull(cityId)){
            if(StrUtil.isBlank(query.getPhoneLon())){
                ServiceUtil.assertion(false, "经度[phoneLon]未传");
            }
            if(StrUtil.isBlank(query.getPhoneLat())){
                ServiceUtil.assertion(false, "纬度[phoneLat]未传");
            }
            query.setCityId(cityService.getCityIdByLocation(query.getPhoneLon(), query.getPhoneLat()));
        }
        if(query.getType() !=null && "0".equals(query.getType())){
            query.setType(null);
        }

        startPage();
        List<StoreVO> storeListByCityId = storeService.selectEStoreList(query);
        storeAssembler.assembleDistance(storeListByCityId, query.getPhoneLon(), query.getPhoneLat());
        return getDataTable(storeListByCityId);
    }

    /**
     * 提交加盟合作
     */
    @Log(title = "合作意向", businessType = BusinessType.INSERT)
    @PostMapping("/intention")
    public AjaxResult add(@RequestBody Intention eIntention)
    {
        logger.info("提交加盟合作：【EIntention={}】", JSON.toJSONString(eIntention));
        return toAjax(intentionService.insertEIntention(eIntention));
    }


    /**
     * 根据车型id获取详情
     */
    @GetMapping("/getModelById")
    public AjaxResult getModelById(Long modelId)
    {
        logger.info("根据车型id获取详情：【modelId="+modelId+"】");
        if(modelId==null){
            return error("车型id[modelId]未传");
        }
        return success();
    }

    /**
     * 查询文章列表
     */
    @GetMapping("/article/list")
    public TableDataInfo articleList(Article etArticle)
    {
        startPage();
        List<Article> list = asArticleService.selectAsArticleListByApp(etArticle);
        return getDataTable(list);
    }

    /**
     * 获取文章详细信息
     */
    @GetMapping(value = "/article/{articleId}")
    public AjaxResult getArticleInfo(@PathVariable("articleId") Long articleId)
    {
        return success(asArticleService.selectAsArticleByArticleId(articleId));
    }

    /**
     * 根据查询文章分类列表
     */
    @GetMapping("/classify/list")
    public AjaxResult classifyList(ArticleClassify asArticleClassify)
    {
        logger.info("查询分类列表：【asArticleClassify={}】", asArticleClassify);
        List<ArticleClassify> asArticleClassifies = asArticleClassifyService.selectClassifyList(asArticleClassify);
        return success(asArticleClassifies);
    }

    /**
     * 修改用户类型
     */
    @PostMapping("/changeUserType")
    public AjaxResult changeUserType(Long userId, String userType)
    {
        User user = new User();
        user.setUserId(userId);
        user.setUserType(userType);
        return toAjax(userService.updateUser(user));
    }

    /**
     * 分享订单信息
     */
    @GetMapping("/shareOrder")
    public AjaxResult shareOrder(String orderNo)
    {
        logger.info("分享订单信息：orderNo=【{}】", JSON.toJSON(orderNo));
        return success(orderService.selectRlOrderByOrderNo(orderNo));
    }

    /**
     * 查询轮播图列表
     */
    @GetMapping("/carouselList")
    public TableDataInfo list(CarouselQuery query)
    {
        startPage();
        startOrderBy();
        List<CarouselVO> list = carouselService.selectSsCarouselList(query);
        return getDataTable(list);
    }

    /**
     * 根据店铺id查询商品列表
     */
    @GetMapping("/productList")
    public TableDataInfo productList(ProductQuery query)
    {
        startPage();
        startOrderBy();
        List<ProductVO> list = productService.selectProductList(query);
        return getDataTable(list);
    }

    /**
     * code交换id
     */
    @GetMapping(value = "/getId")
    public AjaxResult getAvailableStores(String storeCode, String roomCode)
    {
        if(StrUtil.isNotBlank(roomCode)){
            return success(roomService.getId(roomCode));
        }else{
            return success(storeService.getId(storeCode));
        }
    }

    /**
     * 获取token
     */
    @GetMapping("/getToken")
    public AjaxResult getToken()
    {
        return success(Token.getToken());
    }


}
