package com.ruoyi.web.controller.system;

import java.util.List;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.ClewMaterial;
import com.ruoyi.system.service.IClewMaterialService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.system.mapper.MaterialStatsDailyMapper;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * 素材Controller
 *
 * @author ruoyi
 * @date 2023-10-07
 */
@Controller
@RequestMapping("/system/material")
public class ClewMaterialController extends BaseController
{
    private String prefix = "system/material";

    @Autowired
    private IClewMaterialService clewMaterialService;

    @Autowired
    private MaterialStatsDailyMapper materialStatsDailyMapper;

    @RequiresPermissions("system:material:view")
    @GetMapping()
    public String material()
    {
        return prefix + "/material";
    }

    /**
     * 查询素材列表
     */
    @RequiresPermissions("system:material:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(ClewMaterial clewMaterial)
    {
        startPage();
        List<ClewMaterial> list = clewMaterialService.selectClewMaterialList(clewMaterial);
        return getDataTable(list);
    }

    @PostMapping("/app/list")
    @ResponseBody
    public TableDataInfo appList(@RequestParam(value = "sourceApp", required = false) Long sourceApp, ClewMaterial clewMaterial)
    {
        startPage();
        if(sourceApp == null){
            clewMaterial.setSourceApp(1L);
        }
        List<ClewMaterial> list = clewMaterialService.selectClewMaterialList(clewMaterial);
        return getDataTable(list);
    }

    /**
     * 导出素材列表
     */
    @RequiresPermissions("system:material:export")
    @Log(title = "素材", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(ClewMaterial clewMaterial)
    {
        List<ClewMaterial> list = clewMaterialService.selectClewMaterialList(clewMaterial);
        ExcelUtil<ClewMaterial> util = new ExcelUtil<ClewMaterial>(ClewMaterial.class);
        return util.exportExcel(list, "素材数据");
    }

    /**
     * 新增素材
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存素材
     */
    @RequiresPermissions("system:material:add")
    @Log(title = "素材", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(ClewMaterial clewMaterial)
    {
        return toAjax(clewMaterialService.insertClewMaterial(clewMaterial));
    }

    /**
     * 修改素材
     */
    @RequiresPermissions("system:material:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        ClewMaterial clewMaterial = clewMaterialService.selectClewMaterialById(id);
        mmap.put("clewMaterial", clewMaterial);
        return prefix + "/edit";
    }

    /**
     * 修改保存素材
     */
    @RequiresPermissions("system:material:edit")
    @Log(title = "素材", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(ClewMaterial clewMaterial)
    {
        return toAjax(clewMaterialService.updateClewMaterial(clewMaterial));
    }

    /**
     * 删除素材
     */
    @RequiresPermissions("system:material:remove")
    @Log(title = "素材", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(clewMaterialService.deleteClewMaterialByIds(ids));
    }

    /**
     * 素材点击统计（APP端调用，无需权限校验）
     */
    @PostMapping("/app/click/{id}")
    @ResponseBody
    public AjaxResult incrementClickCount(@PathVariable("id") Long id, HttpServletRequest request)
    {
        System.out.println("点击统计接口被调用，素材ID: " + id);
        String appName = "黑猫搞定逾期";
        String statDate = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        ClewMaterial material = clewMaterialService.selectClewMaterialById(id);
        String title = material != null ? material.getTitle() : null;
        String labels = material != null ? material.getLabels() : null;
        String appSource = material != null && material.getSourceApp() != null ? String.valueOf(material.getSourceApp()) : "unknown";
        materialStatsDailyMapper.incrClick(id, appName, appSource, statDate, title, labels);
        int result = clewMaterialService.incrementClickCount(id);
        System.out.println("点击统计结果: " + result);
        return toAjax(result);
    }

    /**
     * 素材提交统计（APP端调用，无需权限校验）
     */
    @PostMapping("/app/submit/{id}")
    @ResponseBody
    public AjaxResult incrementSubmitCount(@PathVariable("id") Long id, HttpServletRequest request)
    {
        System.out.println("提交统计接口被调用，素材ID: " + id);
        String appName = "黑猫搞定逾期";
        String statDate = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        ClewMaterial material = clewMaterialService.selectClewMaterialById(id);
        String title = material != null ? material.getTitle() : null;
        String labels = material != null ? material.getLabels() : null;
        String appSource = material != null && material.getSourceApp() != null ? String.valueOf(material.getSourceApp()) : "unknown";
        materialStatsDailyMapper.incrSubmit(id, appName, appSource, statDate, title, labels);
        int result = clewMaterialService.incrementSubmitCount(id);
        System.out.println("提交统计结果: " + result);
        return toAjax(result);
    }

    private String defaultString(String val, String def) {
        return (val == null || val.trim().isEmpty()) ? def : val.trim();
    }
}
