package jnpf.cultivate.controller.web.certificate;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import jnpf.base.ActionResult;
import jnpf.base.vo.PageListVO;
import jnpf.base.vo.PaginationVO;
import jnpf.cultivate.service.FtbCultivateCertificateService;
import jnpf.cultivate.service.FtbCultivateCertificateUserService;
import jnpf.cultivate.utils.CultivateImUtil;
import jnpf.cultivate.utils.UserApiV2Util;
import jnpf.model.cultivate.dto.certificate.FtbCertificateUserForm;
import jnpf.model.cultivate.entiy.BaseEntity;
import jnpf.model.cultivate.po.certificate.CertificateUserPagination;
import jnpf.model.cultivate.po.certificate.FtbCertificateEntity;
import jnpf.model.cultivate.po.certificate.FtbCertificateUserEntity;
import jnpf.model.cultivate.vo.certificate.FtbCertificateUserAppListVO;
import jnpf.model.cultivate.vo.certificate.FtbCertificateUserInfoVO;
import jnpf.model.cultivate.vo.certificate.FtbCertificateUserListVO;
import jnpf.permission.vo.v2.organzie.OrganizeGeneralDetailVO;
import jnpf.permission.vo.v2.position.PositionVO;
import jnpf.permission.vo.v2.user.UserBoundVO;
import jnpf.util.JsonUtil;
import jnpf.util.NoDataSourceBind;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * web员工证书模块
 *
 * @author hao.peng
 */
@RestController
@RequestMapping("/certificate_user/new")
public class FtbCultivateCertificateUserController {
    /**
     * 服务对象
     */
    @Resource
    private FtbCultivateCertificateUserService userService;


    @Autowired
    private UserApiV2Util userApiV2Util;


    @Autowired
    CultivateImUtil cultivateImUtil;

    /**
     * 服务对象
     */
    @Resource
    private FtbCultivateCertificateService service;

    /**
     * 获取列表
     *
     * @param pagination
     * @param certificateId
     * @return
     */
    @Operation(summary = "获取列表")
    @GetMapping("/{certificateId}/list")
    @Parameters({
            @Parameter(name = "certificateId", description = "证书ID", required = true),
    })
    public ActionResult<PageListVO<FtbCertificateUserListVO>> list(CertificateUserPagination pagination, @PathVariable String certificateId) {
        pagination.setCertificateId(certificateId);
        List<FtbCertificateUserEntity> entity = userService.getList(pagination);
        List<FtbCertificateUserListVO> listVo = JsonUtil.getJsonToList(JsonUtil.getObjectToString(entity), FtbCertificateUserListVO.class);
        PaginationVO vo = JsonUtil.getJsonToBean(pagination, PaginationVO.class);
        List<String> userIds = listVo.stream().map(FtbCertificateUserListVO::getUserId).collect(Collectors.toList());
        Map<String, UserBoundVO> userPrimaryBoundBatch = userApiV2Util.getUserPrimaryBoundBatch(userIds, null);
        LambdaQueryWrapper<FtbCertificateEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(BaseEntity::getId, pagination.getCertificateId());
        FtbCertificateEntity one = service.getOne(wrapper);
        for (FtbCertificateUserListVO certificateUser : listVo) {
//            if (Objects.nonNull(certificateUser.getOrganizeId())) {
////                OrganizeEntity organizeEntity = organizeApi.getInfoById(certificateUser.getOrganizeId());
//                OrganizeGeneralDetailVO organizeEntity = userApiV2Util.organizeInfoById(certificateUser.getOrganizeId(), null);
//                if(organizeEntity!=null){
//                    certificateUser.setOrganizeName(organizeEntity.getName());
//                }
//            }
//            if (Objects.nonNull(certificateUser.getPositionId())) {
////                PositionEntity positionEntity = positionApi.queryInfoById(certificateUser.getPositionId());
//                PositionVO positionEntity = userApiV2Util.infoPosition(certificateUser.getPositionId(), null);
//                if (positionEntity != null) {
//                    certificateUser.setPositionName(positionEntity.getFullName());
//                }
//            }

            UserBoundVO userPrimaryBoundVO = userPrimaryBoundBatch.get(certificateUser.getUserId());
            if (userPrimaryBoundVO != null) {
                certificateUser.setUserName(userPrimaryBoundVO.getUserName());
                certificateUser.setOrganizeName(userPrimaryBoundVO.getOrganizeName());
                certificateUser.setPositionName(userPrimaryBoundVO.getPositionName());
            }
            // 证书模版地址
            if (ObjectUtil.isNotEmpty(one)) {
                certificateUser.setPoints(one.getPoints());
                certificateUser.setTemplate(one.getTemplate());
                certificateUser.setCompanyName(one.getCompanyName());
                certificateUser.setReason(one.getReason());
                if (StringUtils.isNotEmpty(one.getMotivational())) {
                    certificateUser.setMotivational(one.getMotivational());
                }
            }
        }
        return ActionResult.page(listVo, vo);
    }

    /**
     * 用户证书列表（移动端）
     *
     * @param userId
     * @return
     */
    @Operation(summary = "用户证书列表（移动端）")
    @GetMapping("/{userId}/certList")
    @Parameters({
            @Parameter(name = "userId", description = "用户ID", required = true),
    })
    public ActionResult<FtbCertificateUserAppListVO> userList(@PathVariable String userId) {
        if (StringUtils.isEmpty(userId)) {
            ActionResult.fail("用户ID为空");
        }
        List<FtbCertificateUserEntity> entity = userService.userList(userId);
        List<String> strings = entity.stream().map(FtbCertificateUserEntity::getCertificateId).collect(Collectors.toList());
        Map<String, FtbCertificateEntity> entityMap = new HashMap<>();
        if (CollUtil.isNotEmpty(strings)) {
            LambdaQueryWrapper<FtbCertificateEntity> wrapper = Wrappers.lambdaQuery();
            wrapper.in(BaseEntity::getId, strings);
            List<FtbCertificateEntity> list = service.list(wrapper);
            entityMap = list.stream().collect(Collectors.toMap(FtbCertificateEntity::getId, a -> a, (k1, k2) -> k1));
        }
        List<FtbCertificateUserListVO> listVo = JsonUtil.getJsonToList(JsonUtil.getObjectToString(entity), FtbCertificateUserListVO.class);
        FtbCertificateUserAppListVO userAppListVO = new FtbCertificateUserAppListVO();
        Map<String, FtbCertificateEntity> finalEntityMap = entityMap;
//        ActionResult<UserInfoVO> info = userApi.getInfo(userId);
        UserBoundVO info = userApiV2Util.getUserPrimaryBoundOne(userId, null);
        String realName;
        if (info != null) {
            realName = info.getUserName();
        } else {
            realName = "";
        }
        listVo.forEach(item -> {
            if (finalEntityMap.containsKey(item.getCertificateId())) {
                FtbCertificateEntity ftbCertificate = finalEntityMap.get(item.getCertificateId());
                if (StringUtils.isNotEmpty(ftbCertificate.getTemplate()))
                    item.setTemplate(ftbCertificate.getTemplate());
                item.setCompanyName(ftbCertificate.getCompanyName());
                item.setReason(ftbCertificate.getReason());
                item.setPoints(ftbCertificate.getPoints());
                if (StringUtils.isNotEmpty(ftbCertificate.getMotivational()))
                    item.setMotivational(ftbCertificate.getMotivational());
            }
            if (StringUtils.isNotEmpty(realName)) item.setUserName(realName);
        });
        userAppListVO.setCertList(listVo);
        userAppListVO.setCertNumber(listVo.size());
        return ActionResult.success(userAppListVO);
    }

    /**
     * 获取详情
     *
     * @param id
     * @return
     */
    @Operation(summary = "获取详情")
    @GetMapping("/{id}")
    @Parameters({
            @Parameter(name = "id", description = "主键", required = true),
    })
    public ActionResult<FtbCertificateUserInfoVO> info(@PathVariable("id") String id) {
        FtbCertificateUserEntity entity = userService.getInfo(id);
        FtbCertificateUserInfoVO vo = JsonUtil.getJsonToBean(entity, FtbCertificateUserInfoVO.class);
        return ActionResult.success(vo);
    }

    /**
     * 颁发
     *
     * @param FtbCertificateUserForm
     * @return
     */
    @Operation(summary = "颁发")
    @PostMapping
    //@SaCheckPermission("certificateMgrs::btn_issue")
    public ActionResult<List<FtbCertificateUserEntity>> create(@RequestBody @Valid FtbCertificateUserForm FtbCertificateUserForm) {
        userService.create(FtbCertificateUserForm);
        return ActionResult.success();
    }

    /**
     * 批量上传用户证书图片
     *
     * @param certUserList
     * @return
     */
    @Operation(summary = "批量上传用户证书图片")
    @PutMapping("/batchUploadImage")
    public ActionResult<String> batchUploadImage(@RequestBody @Valid List<FtbCertificateUserEntity> certUserList) {
        userService.updateBatchById(certUserList);
        return ActionResult.success("上传成功");
    }

    /**
     * 修改
     *
     * @param id
     * @param FtbCertificateUserForm
     * @return
     */
    @Operation(summary = "修改")
    @PutMapping("/{id}")
    @Parameters({
            @Parameter(name = "id", description = "主键", required = true),
    })
    public ActionResult<String> update(@PathVariable("id") String id, @RequestBody @Valid FtbCertificateUserForm FtbCertificateUserForm) {
        FtbCertificateUserEntity entity = JsonUtil.getJsonToBean(FtbCertificateUserForm, FtbCertificateUserEntity.class);
        userService.update(id, entity);
        return ActionResult.success("修改成功");
    }

    /**
     * 删除(吊销)
     *
     * @param id
     * @return
     */
    @Operation(summary = "删除(吊销)")
    @DeleteMapping("/{id}")
    @Parameters({
            @Parameter(name = "id", description = "主键", required = true),
    })
    public ActionResult<String> delete(@PathVariable("id") String id) {
        if (userService.delete(id)) {
            return ActionResult.success("吊销成功");
        }
        return ActionResult.fail("已吊销或已失效");
    }

    /**
     * 测试im通知
     *
     * @param userId
     * @return
     */
    @GetMapping("/testIm")
    @NoDataSourceBind
    @SaIgnore
    public ActionResult<String> test(@RequestParam("userId") String userId,
                                     @RequestParam("tenantId") String tenantId) {
        cultivateImUtil.sendMessage(List.of(userId), tenantId, "");
        return ActionResult.success("测试成功");
    }
}
