package org.dromara.zhishu.controller;

import java.util.List;
import java.util.Map;

import cn.dev33.satoken.annotation.SaIgnore;
import com.pdd.pop.sdk.common.util.JsonUtil;
import lombok.RequiredArgsConstructor;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.dromara.common.core.utils.DateUtils;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.zhishu.domain.Violation;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.web.core.BaseController;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.zhishu.domain.vo.ViolationVo;
import org.dromara.zhishu.domain.bo.ViolationBo;
import org.dromara.zhishu.service.IViolationService;
import org.dromara.common.mybatis.core.page.TableDataInfo;

/**
 * 违规
 *
 * @author yxy
 * @date 2025-06-23
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/zhishu/violation")
public class ViolationController extends BaseController {

    private final IViolationService violationService;

    /**
     * 查询违规列表
     */
    @SaCheckPermission("zhishu:violation:list")
    @GetMapping("/list")
    public TableDataInfo<ViolationVo> list(ViolationBo bo, PageQuery pageQuery) {
        return violationService.queryPageList(bo, pageQuery);
    }


    @SaIgnore
    @PostMapping("/newList")
    public TableDataInfo<ViolationVo> newList(@RequestBody Map<String, Object> map){
        // 安全地解析分页参数
        Integer pageSize = map.get("pageSize") != null ? 
            Integer.parseInt(map.get("pageSize").toString()) : 10;
        Integer pageNum = map.get("pageNum") != null ? 
            Integer.parseInt(map.get("pageNum").toString()) : 1;

        PageQuery pageQuery = new PageQuery(pageSize, pageNum);

        // 安全地解析查询参数
        String type = map.get("type") != null ? map.get("type").toString() : "";
        String name = map.get("name") != null ? map.get("name").toString() : "";
        String review = map.get("review") != null ? map.get("review").toString() : "";
        String status = map.get("status") != null ? map.get("status").toString() : "";

        ViolationBo bo = new ViolationBo();
        bo.setType(type);
        bo.setName(name);
        bo.setReview(review);
        bo.setStatus(status);

        // 直接返回 TableDataInfo，包含完整的分页信息
        return violationService.queryPageList(bo, pageQuery);
    }

    @SaIgnore
    @PostMapping("/errorSubmit")
    public void errorSubmit(@RequestBody Map map){
        String[] ids = map.get("ids").toString().split(",");
        String remark = map.get("remark") == null ? "" : map.get("remark").toString();
        String review = map.get("review") == null ? "" : map.get("review").toString();

        for (String id : ids){
            ViolationBo bo = new ViolationBo();
            bo.setId(Long.parseLong(id));
            bo.setRemark(remark);
            bo.setReview(review);
            violationService.updateByBo(bo);
        }
    }

    @SaIgnore
    @PostMapping("/successSubmit")
    public void successSubmit(@RequestBody Map map){
        String[] ids = map.get("ids").toString().split(",");
        String review = map.get("review") == null ? "" : map.get("review").toString();
        for (String id : ids){
            ViolationBo bo = new ViolationBo();
            bo.setId(Long.parseLong(id));
            bo.setReview(review);
            violationService.updateByBo(bo);
        }
    }

    @SaIgnore
    @PostMapping("/removeSubmit")
    public void removeSubmit(@RequestBody Map map){
        String[] ids = map.get("ids").toString().split(",");

        Long[] idsArr = new Long[ids.length];
        for(int i=0;i<ids.length; i++){
            idsArr[i] = Long.parseLong(ids[i]);
        }
        violationService.deleteWithValidByIds(List.of(idsArr), true);
    }

    @SaIgnore
    @PostMapping("/editSubmit")
    public void editSubmit(@RequestBody Map map){
        String id = map.get("id").toString();
        String sort =  map.get("sort").toString();

        ViolationBo bo = new ViolationBo();
        bo.setId(Long.parseLong(id));
        bo.setSort(sort);
        violationService.updateByBo(bo);
    }


    /**
     * 提交审核接口
     * @param id
     * @return
     */
    @SaCheckPermission("zhishu:violation:editType")
    @PostMapping("/editType")
    public R<Void> editType(@RequestBody Map map){

        List<String> ids = (List<String>) map.get("ids");
        String type = map.get("type").toString();

        for(String id : ids){
            ViolationBo bo = new ViolationBo();
            bo.setId(Long.parseLong(id));
            bo.setReview(type);
            violationService.updateByBo(bo);
        }
        return R.ok();
    }

    /**
     * 导出违规列表
     */
    @SaCheckPermission("zhishu:violation:export")
    @Log(title = "违规", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(ViolationBo bo, HttpServletResponse response) {
        List<ViolationVo> list = violationService.queryList(bo);
        ExcelUtil.exportExcel(list, "违规", ViolationVo.class, response);
    }

    /**
     * 获取违规详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("zhishu:violation:query")
    @GetMapping("/{id}")
    public R<ViolationVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long id) {
        return R.ok(violationService.queryById(id));
    }

    /**
     * 新增违规
     */
    @SaCheckPermission("zhishu:violation:add")
    @Log(title = "违规", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody ViolationBo bo) {
        //未审核状态
        bo.setReview("0");
        //发起人
        bo.setUserid(LoginHelper.getUserId());
        //创建人为管理员
        bo.setCreateBy(1L);
        bo.setCreateTime(DateUtils.parseDate(DateUtils.getTime()));
        return toAjax(violationService.insertByBo(bo));
    }

    /**
     * 修改违规
     */
    @SaCheckPermission("zhishu:violation:edit")
    @Log(title = "违规", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody ViolationBo bo) {
        return toAjax(violationService.updateByBo(bo));
    }

    /**
     * 删除违规
     *
     * @param ids 主键串
     */
    @SaCheckPermission("zhishu:violation:remove")
    @Log(title = "违规", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(violationService.deleteWithValidByIds(List.of(ids), true));
    }
}
