package com.gxwebsoft.pwl.controller;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gxwebsoft.cms.entity.CmsArticle;
import com.gxwebsoft.cms.entity.CmsArticleContent;
import com.gxwebsoft.cms.param.CmsArticleImportParam;
import com.gxwebsoft.common.core.utils.CommonUtil;
import com.gxwebsoft.common.core.utils.JSONUtil;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.system.entity.Role;
import com.gxwebsoft.common.system.service.UserService;
import com.gxwebsoft.project.entity.ProjectUser;
import com.gxwebsoft.pwl.param.PwlProjectImportParam;
import com.gxwebsoft.pwl.service.PwlProjectService;
import com.gxwebsoft.pwl.entity.PwlProject;
import com.gxwebsoft.pwl.param.PwlProjectParam;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.core.web.PageParam;
import com.gxwebsoft.common.core.web.BatchParam;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.system.entity.User;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 卫兰的项目项目系统控制器
 *
 * @author 科技小王子
 * @since 2025-03-22 14:34:35
 */
@Tag(name = "卫兰的项目项目系统管理")
@RestController
@RequestMapping("/api/pwl/pwl-project")
public class PwlProjectController extends BaseController {
  @Resource
  private PwlProjectService pwlProjectService;

  @PreAuthorize("hasAuthority('pwl:pwlProject:list')")
  @Operation(summary = "分页查询卫兰的项目项目系统")
  @GetMapping("/page")
  public ApiResult<PageResult<PwlProject>> page(PwlProjectParam param) {
    final User loginUser = getLoginUser();
    if (loginUser != null) {
      param.setLoginUserId(loginUser.getUserId());
      final List<Role> roles = loginUser.getRoles();
      if (!CommonUtil.hasRole(roles, "admin") && !CommonUtil.hasRole(roles, "superAdmin")) {
        final List<PwlProject> projectUsers = pwlProjectService.list(new LambdaQueryWrapper<PwlProject>()
          .like(PwlProject::getUserIds, loginUser.getUserId())
          .or()
          .eq(PwlProject::getUserId, loginUser.getUserId())
        );
        if (!CollectionUtils.isEmpty(projectUsers)) {
          final Set<Integer> appIds = projectUsers.stream().map(PwlProject::getId).collect(Collectors.toSet());
          param.setProjectIds(appIds);
        } else {
          param.setUserId(loginUser.getUserId());
        }
      }
    }
    return success(pwlProjectService.pageRel(param));
  }

  @PreAuthorize("hasAuthority('pwl:pwlProject:list')")
  @Operation(summary = "查询全部卫兰的项目项目系统")
  @GetMapping()
  public ApiResult<List<PwlProject>> list(PwlProjectParam param) {
    // 使用关联查询
    return success(pwlProjectService.listRel(param));
  }

  @PreAuthorize("hasAuthority('pwl:pwlProject:list')")
  @Operation(summary = "根据id查询卫兰的项目项目系统")
  @GetMapping("/{id}")
  public ApiResult<PwlProject> get(@PathVariable("id") Integer id) {
    // 使用关联查询
    return success(pwlProjectService.getByIdRel(id));
  }

  @PreAuthorize("hasAuthority('pwl:pwlProject:save')")
  @OperationLog
  @Operation(summary = "添加卫兰的项目项目系统")
  @PostMapping()
  public ApiResult<?> save(@RequestBody PwlProject pwlProject) {
    // 记录当前登录用户id
    User loginUser = getLoginUser();
    if (loginUser != null) {
      pwlProject.setUserId(loginUser.getUserId());
    }
    if (pwlProject.getCode() != null) {
      final PwlProject one = pwlProjectService.getOne(new LambdaQueryWrapper<PwlProject>().eq(PwlProject::getCode, pwlProject.getCode()));
      if (ObjectUtil.isNotEmpty(one)) {
        return fail("报告编号不能重复");
      }
    }
    if (pwlProjectService.save(pwlProject)) {
      return success("添加成功");
    }
    return fail("添加失败");
  }

  @PreAuthorize("hasAuthority('pwl:pwlProject:update')")
  @OperationLog
  @Operation(summary = "修改卫兰的项目项目系统")
  @PutMapping()
  public ApiResult<?> update(@RequestBody PwlProject pwlProject) {
    if (pwlProjectService.updateById(pwlProject)) {
      return success("修改成功");
    }
    return fail("修改失败");
  }

  @PreAuthorize("hasAuthority('pwl:pwlProject:remove')")
  @OperationLog
  @Operation(summary = "删除卫兰的项目项目系统")
  @DeleteMapping("/{id}")
  public ApiResult<?> remove(@PathVariable("id") Integer id) {
    if (pwlProjectService.removeById(id)) {
      return success("删除成功");
    }
    return fail("删除失败");
  }

  @PreAuthorize("hasAuthority('pwl:pwlProject:save')")
  @OperationLog
  @Operation(summary = "批量添加卫兰的项目项目系统")
  @PostMapping("/batch")
  public ApiResult<?> saveBatch(@RequestBody List<PwlProject> list) {
    if (pwlProjectService.saveBatch(list)) {
      return success("添加成功");
    }
    return fail("添加失败");
  }

  @PreAuthorize("hasAuthority('pwl:pwlProject:update')")
  @OperationLog
  @Operation(summary = "批量修改卫兰的项目项目系统")
  @PutMapping("/batch")
  public ApiResult<?> removeBatch(@RequestBody BatchParam<PwlProject> batchParam) {
    if (batchParam.update(pwlProjectService, "id")) {
      return success("修改成功");
    }
    return fail("修改失败");
  }

  @PreAuthorize("hasAuthority('pwl:pwlProject:remove')")
  @OperationLog
  @Operation(summary = "批量删除卫兰的项目项目系统")
  @DeleteMapping("/batch")
  public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
    if (pwlProjectService.removeByIds(ids)) {
      return success("删除成功");
    }
    return fail("删除失败");
  }

  @PreAuthorize("hasAuthority('pwl:pwlProject:save')")
  @Operation(summary = "批量导入项目")
  @Transactional(rollbackFor = {Exception.class})
  @PostMapping("/import")
  public ApiResult<List<String>> importBatch(MultipartFile file) {
    ImportParams importParams = new ImportParams();
    importParams.setHeadRows(2);
    importParams.setTitleRows(1);
    importParams.setSheetNum(1);
    try {
      List<PwlProjectImportParam> list = ExcelImportUtil.importExcel(file.getInputStream(), PwlProjectImportParam.class, importParams);
      list.forEach(d -> {
        PwlProject item = JSONUtil.parseObject(JSONUtil.toJSONString(d), PwlProject.class);
        assert item != null;
        if (ObjectUtil.isNotEmpty(item)) {
          if (item.getStatus() == null) {
            item.setStatus(0);
            item.setUserId(getLoginUserId());
          }
          if (item.getName() != null) {
            pwlProjectService.save(item);
          }
        }
      });
      return success("成功导入" + list.size() + "条", null);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return fail("导入失败", null);
  }

  @Operation(summary = "统计项目完成情况")
  @GetMapping("/count")
  public ApiResult<?> count() {
    final User loginUser = getLoginUser();
    if (loginUser != null) {
      final List<User> list = pwlProjectService.listByCount();
      list.forEach(d -> {
        // 已完成项目数量
        final long completed = pwlProjectService.count(new LambdaQueryWrapper<PwlProject>()
          .like(PwlProject::getDraftUserId, d.getUserId())
          .and(
            i -> i.eq(PwlProject::getStatus, 0)
              .isNotNull(PwlProject::getDraftUserId)
          )
        );
        d.setBalance(new BigDecimal(completed));
        // 未完成项目数量
        final long incomplete = pwlProjectService.count(new LambdaQueryWrapper<PwlProject>()
          .like(PwlProject::getDraftUserId, d.getUserId())
          .and(
            i -> i.eq(PwlProject::getStatus, 1)
              .isNotNull(PwlProject::getDraftUserId)
          )
        );
        // 签字会计数量
        final long signUsers = pwlProjectService.count(new LambdaQueryWrapper<PwlProject>()
          .like(PwlProject::getSignUserId, d.getUserId())
          .and(
            i -> i.eq(PwlProject::getStatus, 1)
              .isNotNull(PwlProject::getSignUserId)
          )
        );
        d.setPoints(Math.toIntExact(incomplete));
        d.setFans(Math.toIntExact(signUsers));
      });
      return success(list);
    }
    return fail("没有找到结果", null);
  }

}
