package cn.iocoder.yudao.module.server.controller.admin.materialinfo;

import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.server.controller.admin.materialcategory.vo.MaterialCategoryRespVO;
import cn.iocoder.yudao.module.server.controller.admin.materialdownloadlog.vo.MaterialDownloadLogSaveReqVO;
import cn.iocoder.yudao.module.server.dal.dataobject.materialcategory.MaterialCategoryDO;
import cn.iocoder.yudao.module.server.dal.dataobject.materialdownloadlog.MaterialDownloadLogDO;
import cn.iocoder.yudao.module.server.dal.dataobject.materialshareuser.MaterialShareUserDO;
import cn.iocoder.yudao.module.server.service.materialcategory.MaterialCategoryService;
import cn.iocoder.yudao.module.server.service.materialdownloadlog.MaterialDownloadLogService;
import cn.iocoder.yudao.module.server.service.materialshareuser.MaterialShareUserService;
import cn.iocoder.yudao.module.system.dal.dataobject.dept.DeptDO;
import cn.iocoder.yudao.module.system.service.dept.DeptService;
import cn.iocoder.yudao.module.system.service.permission.PermissionService;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.constraints.*;
import javax.validation.*;
import javax.servlet.http.*;
import java.time.LocalDateTime;
import java.util.*;
import java.io.IOException;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;

import cn.iocoder.yudao.module.server.controller.admin.materialinfo.vo.*;
import cn.iocoder.yudao.module.server.dal.dataobject.materialinfo.MaterialInfoDO;
import cn.iocoder.yudao.module.server.service.materialinfo.MaterialInfoService;

@Tag(name = "管理后台 - 资料库")
@RestController
@RequestMapping("/server/material-info")
@Validated
public class MaterialInfoController {

    @Resource
    private MaterialInfoService materialInfoService;
    @Resource
    private MaterialCategoryService materialCategoryService;

    @Resource
    private DeptService deptService;

    @Resource
    private PermissionService permissionService;
    @Resource
    private MaterialDownloadLogService materialDownloadLogService;

    @Resource
    private MaterialShareUserService materialShareUserService;

    @RequestMapping("/create")
    @Operation(summary = "创建资料库")
    @PreAuthorize("@ss.hasPermission('server:material-info:create')")
    public CommonResult<Long> createMaterialInfo(@Valid @RequestBody MaterialInfoSaveReqVO createReqVO) {
        Long deptId = SecurityFrameworkUtils.getLoginUserDeptId();
        if(deptId!=null){
            DeptDO dept = deptService.getDept(deptId);
            createReqVO.setDepartmentName(dept.getName());
            createReqVO.setDepartmentId(deptId);
        }
        return success(materialInfoService.createMaterialInfo(createReqVO));
    }

    @PostMapping("/update")
    @Operation(summary = "更新资料库")
    @PreAuthorize("@ss.hasPermission('server:material-info:update')")
    public CommonResult<Boolean> updateMaterialInfo(@Valid @RequestBody MaterialInfoSaveReqVO updateReqVO) {
        materialInfoService.updateMaterialInfo(updateReqVO);
        return success(true);
    }

    @PostMapping("/delete")
    @Operation(summary = "删除资料库")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('server:material-info:delete')")
    public CommonResult<Boolean> deleteMaterialInfo(@RequestParam("id") Long id) {
        materialInfoService.deleteMaterialInfo(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得资料库")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('server:material-info:query')")
    public CommonResult<MaterialInfoRespVO> getMaterialInfo(@RequestParam("id") Long id) {
        MaterialInfoDO materialInfo = materialInfoService.getMaterialInfo(id);
        return success(BeanUtils.toBean(materialInfo, MaterialInfoRespVO.class));
    }

    @GetMapping("/get2")
    @Operation(summary = "获得资料库")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('server:material-info:query')")
    public CommonResult<MaterialInfoRespVO> getMaterialInfo2(@RequestParam("id") Long id) {
        MaterialInfoDO materialInfo = materialInfoService.getMaterialInfo(id);

        Long deptId = SecurityFrameworkUtils.getLoginUserDeptId();
        if(deptId!=null){
            DeptDO dept = deptService.getDept(deptId);
            MaterialDownloadLogSaveReqVO log = new MaterialDownloadLogSaveReqVO();
            log.setMaterialId(id);
            log.setMaterialName(materialInfo.getName());
            log.setUserId(deptId);
            log.setUserName(dept.getName());
            log.setDownloadTime(LocalDateTime.now());
            materialDownloadLogService.createMaterialDownloadLog(log);
        }

        MaterialInfoSaveReqVO updateReqVO =  new MaterialInfoSaveReqVO();
        updateReqVO.setId(id);
        updateReqVO.setDownloadCount(materialInfo.getDownloadCount()+1);
        materialInfoService.updateMaterialInfo(updateReqVO);
        return success(BeanUtils.toBean(materialInfo, MaterialInfoRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得资料库分页")
    @PreAuthorize("@ss.hasPermission('server:material-info:query')")
    public CommonResult<PageResult<MaterialInfoRespVO>> getMaterialInfoPage(@Valid MaterialInfoPageReqVO pageReqVO) {
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        boolean idAdmin = permissionService.hasAnyRoles(loginUser.getId(), "super_admin", "trs_material_admin");
/*        if(idAdmin){
            PageResult<MaterialInfoDO> pageResult = materialInfoService.getMaterialInfoPage(pageReqVO);
            return success(BeanUtils.toBean(pageResult, MaterialInfoRespVO.class));
        }else{
            Long deptId = SecurityFrameworkUtils.getLoginUserDeptId();
            PageResult<MaterialInfoDO> pageResult = materialInfoService.getMaterialInfoPageByUser(pageReqVO, deptId);
            return success(BeanUtils.toBean(pageResult, MaterialInfoRespVO.class));
        }*/

        PageResult<MaterialInfoDO> pageResult;
        if(idAdmin){
            pageResult = materialInfoService.getMaterialInfoPage(pageReqVO);
        } else {
            Long deptId = SecurityFrameworkUtils.getLoginUserDeptId();
            pageResult = materialInfoService.getMaterialInfoPageByUser(pageReqVO, deptId);
        }
        // 转换为 MaterialInfoRespVO 并添加共享用户信息
        List<MaterialInfoRespVO> voList = new ArrayList<>();
        for (MaterialInfoDO materialInfo : pageResult.getList()) {
            MaterialInfoRespVO respVO = convertToRespVO(materialInfo);
            voList.add(respVO);
        }
        PageResult<MaterialInfoRespVO> result = new PageResult<>(voList, pageResult.getTotal());
        return success(result);
    }

    // 私有方法：转换 DO 到 RespVO 并添加共享用户信息
    private MaterialInfoRespVO convertToRespVO(MaterialInfoDO materialInfo) {
        MaterialInfoRespVO respVO = BeanUtils.toBean(materialInfo, MaterialInfoRespVO.class);

        // 查询共享用户信息（如果是指定组织共享）
        if (materialInfo.getShareType() != null && materialInfo.getShareType() == 2) {
            List<MaterialShareUserDO> shareUsers = materialShareUserService.getMaterialShareUser(materialInfo.getId());
            if (shareUsers != null && !shareUsers.isEmpty()) {
                List<MaterialInfoRespVO.ShareUserVO> shareUserVOs = new ArrayList<>();
                for (MaterialShareUserDO shareUser : shareUsers) {
                    MaterialInfoRespVO.ShareUserVO shareUserVO = new MaterialInfoRespVO.ShareUserVO();
                    shareUserVO.setUserId(shareUser.getUserId());
                    shareUserVO.setDeptName(shareUser.getDeptName());
                    shareUserVOs.add(shareUserVO);
                }
                respVO.setShareUsers(shareUserVOs);
            }
        }

        return respVO;
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出资料库 Excel")
    @PreAuthorize("@ss.hasPermission('server:material-info:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportMaterialInfoExcel(@Valid MaterialInfoPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<MaterialInfoDO> list = materialInfoService.getMaterialInfoPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "资料库.xls", "数据", MaterialInfoRespVO.class,
                        BeanUtils.toBean(list, MaterialInfoRespVO.class));
    }

    @GetMapping("/tree")
    @PreAuthorize("@ss.hasPermission('server:material-info:query')")
    public CommonResult<List<MaterialCategoryRespVO>> getCategoryTree() {
        List<MaterialCategoryDO> categoryTree = materialCategoryService.getCategoryTree();
        return success(BeanUtils.toBean(categoryTree, MaterialCategoryRespVO.class));
    }

    @GetMapping("/userlist")
    @PreAuthorize("@ss.hasPermission('server:material-info:query')")
    public CommonResult<List<DeptDO>> userlist() {
        List<DeptDO> childDeptList = deptService.getChildDeptList(0L);
        return success(childDeptList);
    }

}