package com.ruoyi.web.controller.app;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.annotation.Log;
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.SysDictData;
import com.ruoyi.common.core.domain.entity.User;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServiceUtil;
import com.ruoyi.common.utils.verify.vo.IDResponse;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.ss.article.domain.Article;
import com.ruoyi.ss.article.service.IArticleService;
import com.ruoyi.ss.articleClassify.service.IArticleClassifyService;
import com.ruoyi.ss.channelWithdraw.domain.ChannelWithdrawQuery;
import com.ruoyi.ss.channelWithdraw.domain.ChannelWithdrawVO;
import com.ruoyi.ss.channelWithdraw.service.ChannelWithdrawService;
import com.ruoyi.ss.feeRule.domain.FeeRule;
import com.ruoyi.ss.feeRule.service.IFeeRuleService;
import com.ruoyi.ss.feedback.domain.Feedback;
import com.ruoyi.ss.feedback.service.IFeedbackService;
import com.ruoyi.ss.order.domain.OrderQuery;
import com.ruoyi.ss.order.domain.OrderVO;
import com.ruoyi.ss.order.service.IOrderService;
import com.ruoyi.ss.user.service.IUserService;
import com.ruoyi.ss.withdraw.service.IWithdrawService;
import com.ruoyi.system.domain.query.AuthenticationQuery;
import com.ruoyi.system.domain.query.IndexChartQuery;
import com.ruoyi.system.domain.vo.IndexIncomeList;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysDictDataService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;


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

    @Resource
    private IUserService userService;

    @Resource
    private IOrderService orderService;

    @Autowired
    private IWithdrawService withdrawService;

    @Autowired
    private TokenService tokenService;

    @Resource
    private IFeedbackService feedbackService;

    @Autowired
    private ChannelWithdrawService etChannelWithdrawService;

    @Autowired
    private ISysDictDataService dictDataService;

    @Autowired
    private IFeeRuleService feeRuleService;

    @Autowired
    private IArticleService articleService;

    @Autowired
    private IArticleClassifyService articleClassifyService;

    @Autowired
    private ISysConfigService configService;

    /**
     * 首页统计
     */
    @GetMapping(value = {  "/index" })
    public AjaxResult index()
    {
        logger.info("【首页统计/index】参数");
        return success(orderService.indexStatistics());
    }

//    /**
//     * 后台首页统计
//     */
//    @GetMapping(value = {  "/adminIndex" })
//    public AjaxResult adminIndex()
//    {
//        logger.info("【后台首页统计/adminIndex】参数");
//        return success(orderService.adminIndexStatistics());
//    }
//
//    /**
//     * 后台首页图表数据
//     */
//    @GetMapping(value = {  "/adminIndexChartData" })
//    public AjaxResult adminIndexChartData(IndexChartQuery query)
//    {
//        logger.info("【后台首页统计/adminIndexChartData】参数：{}",JSON.toJSONString(query));
//        return success(orderService.adminIndexChartData(query));
//    }


    /**
     * 获取首页营收统计列表
     */
    @GetMapping(value = {  "/getIndexInComeList" })
    public AjaxResult getIndexInComeList(String timeLimit)
    {
        logger.info("【首页统计/index】参数：timeLimit={}", timeLimit);
        IndexIncomeList indexIncomeList = orderService.getIndexInComeList(timeLimit);
        return success(indexIncomeList);
    }

    /**
     * 实名认证
     */
    @Log(title = "实名认证", businessType = BusinessType.AUTHENTICATION)
    @GetMapping("/user/authentication")
    public AjaxResult authentication(AuthenticationQuery authenticationQuery)
    {
        logger.info("【实名认证】请求参数：authenticationQuery={}", JSON.toJSON(authenticationQuery));
        Object authentication = userService.authentication(authenticationQuery);
        //判断o是否是字符串
        if(authentication instanceof String){
            return AjaxResult.error((String) authentication);
        }else{
            IDResponse.Result result = (IDResponse.Result)authentication;
            if(result.getIsok()){
                //保存身份信息
                // 更新用户并更新缓存
                LoginUser loginUser = SecurityUtils.getLoginUser();
                User asUser = new User();
                asUser.setUserId(authenticationQuery.getUserId());
                asUser.setRealName(authenticationQuery.getRealName());
                asUser.setIdCard(authenticationQuery.getIdCard());
                asUser.setIsAuthentication(true);
                asUser.setPhonenumber(authenticationQuery.getPhone());
                int updateUser = userService.updateUser(asUser);
                if (updateUser>0)
                {
                    logger.info("【实名认证】保存身份信息成功");
                    // 更新缓存用户信息
                    tokenService.setLoginUser(loginUser);
                }
            }
            return AjaxResult.success(authentication);
        }
    }

    /**
     * 订单列表
     */
    @GetMapping("/orderList")
    public TableDataInfo orderList(OrderQuery order)
    {
        logger.info("订单列表请求：order=【{}】", JSON.toJSONString(order));
        startPage();
        List<OrderVO> rlOrderVOS = orderService.selectRlOrderList(order);
        return getDataTable(rlOrderVOS);
    }

    /**
     * 订单信息（用户）
     */
    @GetMapping("/orderInfo")
    public AjaxResult orderInfo(String orderNo)
    {
        logger.info("订单信息：order=【{}】", JSON.toJSON(orderNo));
        OrderVO rlOrder = orderService.getOrderInfoByOrderNo(orderNo);
        return success(rlOrder);
    }

    /**
     * 获取提现记录详细信息
     */
    @GetMapping(value = "/withdraw/{id}")
    public AjaxResult withdrawInfo(@PathVariable("id") Long id)
    {
        return success(withdrawService.selectRlWithdrawById(id));
    }

    /**
     * 我的账户
     */
    @GetMapping(value = {  "/myAccountInfo" })
    public AjaxResult myAccountInfo()
    {
        AjaxResult ajax = AjaxResult.success();
        User rlUser = userService.myAccountInfoByUserId(getUserId());
        ajax.put(AjaxResult.DATA_TAG, rlUser);
        return ajax;
    }

    /**
     * 新增反馈意见
     */
    @Log(title = "反馈意见", businessType = BusinessType.INSERT)
    @PostMapping("/feedback")
    public AjaxResult add(@RequestBody Feedback asFeedback)
    {
        logger.info("【新增反馈意见】：【{}】", JSON.toJSONString(asFeedback));
        //校验请求参数
        if(StrUtil.isBlank(asFeedback.getType())){
            return error("类型不能为空");
        }
        if(StrUtil.isBlank(asFeedback.getIssueDescription())){
            return error("问题描述不能为空");
        }
        if(StrUtil.isBlank(asFeedback.getContactInfo())){
            return error("联系方式不能为空");
        }
        return toAjax(feedbackService.insertAsFeedback(asFeedback));
    }

    /**
     * 修改手机号
     */
    @Log(title = "修改手机号", businessType = BusinessType.UPDATE)
    @PostMapping("/edit/phone")
    public AjaxResult editPhone(String phone)
    {
        logger.info("修改手机号：【phone={}】", phone);
        User updateUser = new User();
        updateUser.setUserId(getUserId());
        updateUser.setPhonenumber(phone);
        int i = userService.updateUser(updateUser);
        if(i == 0) return AjaxResult.warn("修改手机号失败");
        return toAjax(i);
    }

    /**
     * 查询全局提现渠道列表
     */
    @GetMapping("/withdrawList")
    public AjaxResult withdrawList(ChannelWithdrawQuery query)
    {
        List<ChannelWithdrawVO> list = etChannelWithdrawService.selectChannelWithdrawList(query);
        return success(list);
    }

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

    @ApiOperation("获取全局配置")
    @GetMapping("/getConfig")
    public AjaxResult getConfig(@RequestParam(required = false)String key) {
        AjaxResult ajax = AjaxResult.success();
        logger.info("获取全局配置：【{}】", key);
        String configValue = configService.selectConfigByKey(key);
        ajax.put(AjaxResult.DATA_TAG, configValue);
        return ajax;
    }

    /**
     * 新增收费模板
     */
    @Log(title = "收费模板", businessType = BusinessType.INSERT)
    @PostMapping("/rule")
    public AjaxResult addRule(@RequestBody FeeRule rlFeeRule)
    {
        logger.info("新增收费模板：【{}】", JSON.toJSONString(rlFeeRule));
        return toAjax(feeRuleService.insertEFeeRule(rlFeeRule));
    }

    /**
     * 修改收费模板
     */
    @Log(title = "收费模板", businessType = BusinessType.UPDATE)
    @PutMapping("/rule")
    public AjaxResult editRule(@RequestBody FeeRule rlFeeRule)
    {
        logger.info("修改收费模板：【{}】", JSON.toJSONString(rlFeeRule));
        return toAjax(feeRuleService.updateEFeeRule(rlFeeRule));
    }

    /**
     * 删除收费模板(逻辑删除)
     */
    @Log(title = "收费模板", businessType = BusinessType.DELETE)
    @DeleteMapping("/rule/{ruleIds}")
    public AjaxResult removeRule(@PathVariable Long[] ruleIds)
    {
        logger.info("删除收费模板：【{}】", JSON.toJSONString(ruleIds));
        for (Long ruleId : ruleIds){
            FeeRule eFeeRule = new FeeRule();
            eFeeRule.setDeleted(true);
            eFeeRule.setRuleId(ruleId);
            int i = feeRuleService.updateEFeeRule(eFeeRule);
            ServiceUtil.assertion(i == 0, "【收费模板】删除失败");
        }
        return toAjax(1);
    }

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

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

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

}
