package jnpf.cultivate.controller.web.promotion;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.collection.CollUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import jnpf.base.ActionResult;
import jnpf.base.UserInfo;
import jnpf.base.vo.PageListVO;
import jnpf.config.ConfigValueUtil;
import jnpf.cultivate.service.FtbCultivatePromotionService;
import jnpf.database.util.TenantDataSourceUtil;
import jnpf.exception.LoginException;
import jnpf.model.cultivate.CultivatePage;
import jnpf.model.cultivate.dto.promotion.FtbCultivatePromotionCreatDto;
import jnpf.model.cultivate.dto.promotion.FtbCultivatePromotionDto;
import jnpf.model.cultivate.vo.promotion.FtbCultivatePromotionMemberVO;
import jnpf.model.cultivate.vo.promotion.FtbCultivatePromotionPostVO;
import jnpf.model.cultivate.vo.promotion.FtbCultivatePromotionVO;
import jnpf.personnels.service.FtbPersonnelsStaffEmploymentApplyService;
import jnpf.util.NoDataSourceBind;
import jnpf.util.StringUtil;
import jnpf.util.UserProvider;
import jnpf.util.data.DataSourceContextHolder;
import jnpf.util.excel.EasyExcelUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * web晋升通道管理
 * @author hao.peng
 */
@RestController
@RequestMapping("/cul_pro")
@Slf4j
public class FtbCultivatePromotionController {
    /**
     * 服务对象
     */
    @Resource
    private FtbCultivatePromotionService promotionService;

    @Resource
    private ConfigValueUtil configValueUtil;

    @Resource
    private FtbPersonnelsStaffEmploymentApplyService staffEmploymentApplyService;
    /**
     * 获取晋升通道管理列表
     * @param page 分页参数
     * @return
     */
    @Operation(summary = "获取晋升通道管理列表")
    @GetMapping("/list")
    public ActionResult<PageListVO<FtbCultivatePromotionVO>> list(FtbCultivatePromotionDto dto, CultivatePage page) {
        PageListVO<FtbCultivatePromotionVO> listVo = promotionService.getList(page,dto);
        return ActionResult.success(listVo);
    }

    /**
     * 校验该岗位是否岗位通道和岗位学习是否有值
     * @param postId 岗位id
     * @param gradeId 职等id
     * @return
     */
    @Operation(summary = "校验该岗位是否岗位通道和岗位学习是否有值")
    @GetMapping("/VerifyPromotion")
    public ActionResult<String> VerifyPromotion(@RequestParam(required = false,name = "postId") String postId,
                                                @RequestParam(required = false,name = "gradeId") String gradeId) {
        //校验办理入职列表是否有用户使用
        staffEmploymentApplyService.verifyUserBound(postId,gradeId);

        promotionService.VerifyPromotion(postId,gradeId);
        return ActionResult.success();
    }

    /**
     * 新增晋升通道
     * @param creatDto
     * @return
     */
    @Operation(summary = "新增晋升通道")
    @PostMapping("/save")
    public ActionResult<String> save(@Validated @RequestBody FtbCultivatePromotionCreatDto creatDto) {
        promotionService.add(creatDto);
        return ActionResult.success("新增成功");

    }
    /**
     * 批量新增晋升通道
     * @param creatDto
     * @return
     */
    @Operation(summary = "批量新增晋升通道")
    @PostMapping("/saveList")
    public ActionResult<String> saveList(@Validated @RequestBody List<FtbCultivatePromotionCreatDto> creatDto) {
        promotionService.addList(creatDto);
        return ActionResult.success("新增成功");

    }

    /**
     * 修改晋升通道
     * @param creatDto
     * @return
     */
    @Operation(summary = "修改晋升通道")
    @PutMapping("/update")
    public ActionResult<String> update(@RequestBody FtbCultivatePromotionCreatDto creatDto) {
        promotionService.updatePromotion(creatDto);
        return ActionResult.success("修改成功");
    }

    /**
     * 删除是需要进行成员列表获取
     * 获取启用该晋升通道的成员列表
     * @param page 分页参数
     * @return
     */
    @Operation(summary = "删除是需要进行成员列表获取,获取启用该晋升通道的成员列表")
    @GetMapping("/getPromotionMbeList")
    public ActionResult<PageListVO<FtbCultivatePromotionMemberVO>> getPromotionMbeList(FtbCultivatePromotionDto dto,
                                                                                       CultivatePage page ) {
        PageListVO<FtbCultivatePromotionMemberVO> listVo =promotionService.getPromotionMbeList(dto,page);
        return ActionResult.success(listVo);
    }

    /**
     * 删除晋升通道
     * @param id 主键ID
     * @param isTwoDelete 是否执行2次删除操作。如果`isTwoDelete`为`0`，则进行一次删除操作；如果为`1`，则执行2次删除操作。
     * @return 删除结果
     */
    @Operation(summary = "删除晋升通道")
    @DeleteMapping("/{id}/{isTwoDelete}")
    @Parameter(name = "id", description = "主键ID", required = true)
    public ActionResult<Boolean> delete(@PathVariable("id") String id,
                                        @PathVariable("isTwoDelete") int isTwoDelete) {
        boolean isDeleted = promotionService.deleteById(id, isTwoDelete == 1);
        if (!isDeleted) {
            return ActionResult.success(false);
        }
        return ActionResult.success(true);
    }

    /**
     * 导出晋升通道数据
     * @param response
     * @param tenantId
     * @throws IOException
     */
    @GetMapping("/exportPromotionChannelData")
    @SaIgnore
    @NoDataSourceBind
    public void exportPromotionChannelData(HttpServletResponse response, String tenantId) throws IOException {
        if (log.isDebugEnabled()) {
            log.debug("closeUserAccountRegularlyAfterResignation params :{}", tenantId);
        }
        // 判断是否为多租户
        if (configValueUtil.isMultiTenancy()) {
            // 判断是不是从外面直接请求
            if (StringUtil.isNotEmpty(tenantId)) {
                //切换成租户库
                try {
                    TenantDataSourceUtil.switchTenant(tenantId);
                } catch (LoginException e) {
                    throw new RuntimeException("切换租户失败");
                }
            } else {
                UserInfo userInfo = UserProvider.getUser();
                Assert.notNull(userInfo.getUserId(), "缺少租户信息");
                DataSourceContextHolder.setDatasource(userInfo.getTenantId(), userInfo.getTenantDbConnectionString(), userInfo.isAssignDataSource());
            }
        }
        CultivatePage page =new CultivatePage();
        page.setPageSize(100000);
        page.setCurrentPage(1);
        PageListVO<FtbCultivatePromotionVO> listVo = promotionService.getList(page,new FtbCultivatePromotionDto());
        List<FtbCultivatePromotionVO> list = listVo.getList();
        if (CollUtil.isNotEmpty(list)){
            list.forEach(item->{
                List<FtbCultivatePromotionPostVO> postChannelLevel = item.getPostChannelLevel();
                String collect = postChannelLevel.stream().map(FtbCultivatePromotionPostVO::getPostName).collect(Collectors.joining("<"));
                item.setPostChannelLevelName(collect);
            });
            List<FtbCultivatePromotionVO> collect = list.stream().filter(item->StringUtil.isNotEmpty(item.getChannelIniName())).sorted(Comparator.comparing(FtbCultivatePromotionVO::getChannelIniName)).collect(Collectors.toList());
            listVo.setList(collect);
        }
        EasyExcelUtils.exportExcel(response,tenantId+"晋升通道数据详情",list,FtbCultivatePromotionVO.class);
    }
}
