package com.storlead.sales.controller.systemrule;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.storlead.framework.common.result.Result;
import com.storlead.sales.enums.ResourceTypeEnum;
import com.storlead.sales.pojo.entity.systemrule.ApproveNodeEntity;
import com.storlead.sales.pojo.vo.systemrule.ApproveTypeVO;
import com.storlead.sales.service.systemrule.ApproveNodeService;
import com.storlead.user.pojo.entity.SubCompanyEntity;
import com.storlead.user.pojo.entity.UserEntity;
import com.storlead.user.service.ISubCompanyService;
import com.storlead.user.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import javax.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 审批节点表 前端控制器
 * </p>
 *
 * @author YPZ
 * @since 2024-07-26
 */
@RestController
@RequestMapping("/approve-node")
@Api(tags = "销售: 审核相关接口")
public class ApproveNodeController {
    @Resource
    private ApproveNodeService approveNodeService;
    @Resource
    private ISubCompanyService subCompanyService;
    @Resource
    private IUserService userService;
    /***
     * @Description: 获取审批类型列表
     * @Param:
     * @return:
     * @Author: YPZ
     * @Date: 2023/11/13 17:10
     */
    @GetMapping("/approve-type-list")
    @ApiOperation("获取审批类型列表")
    public Result approveTypeList(){
        List<ApproveTypeVO> approveTypeList = new ArrayList<>();
        for (ResourceTypeEnum approveType : ResourceTypeEnum.values()) {
            ApproveTypeVO approveTypeVO = new ApproveTypeVO();
            approveTypeVO.setType(approveType.code);
            approveTypeVO.setTypeName(approveType.desc);
            approveTypeList.add(approveTypeVO);
        }
        return Result.result(approveTypeList);
    }

    /***
     * @Description: 通过审批类型获取节点列表
     * @Param:
     * @return:
     * @Author: YPZ
     * @Date: 2023/11/13 17:10
     */
    @GetMapping("/node-list")
    @ApiOperation("通过审批类型获取节点列表")
    public Result nodeList(Integer type){
        if (ObjectUtils.isEmpty(type)){
            return Result.error("请传入节点类型");
        }
        LambdaQueryWrapper<ApproveNodeEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ApproveNodeEntity::getApproveType,type);
        wrapper.orderByAsc(ApproveNodeEntity::getSubCompanyId,ApproveNodeEntity::getNodeSort);
        List<ApproveNodeEntity> approveNodeList = approveNodeService.list(wrapper);
        return Result.result(approveNodeList);
    }

    @ApiOperation("添加/修改审批节点")
    @PostMapping("/add-node")
    public Result addNode(@RequestBody ApproveNodeEntity approveNode) {
        if (ObjectUtils.isEmpty(approveNode)){
            return Result.error("参数错误");
        }
        LambdaQueryWrapper<ApproveNodeEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ApproveNodeEntity::getApproveType,approveNode.getApproveType());
        if (ObjectUtils.isEmpty(approveNode.getSubCompanyId())){
            wrapper.eq(ApproveNodeEntity::getSubCompanyId,"");
        }else {
            wrapper.eq(ApproveNodeEntity::getSubCompanyId, approveNode.getSubCompanyId());
        }
        wrapper.eq(ApproveNodeEntity::getNodeSort,approveNode.getNodeSort());
        wrapper.last(" LIMIT 1");
        ApproveNodeEntity oldNode = approveNodeService.getOne(wrapper);
        if (Objects.nonNull(oldNode)){
            if (!oldNode.getId().equals(approveNode.getId())) {
                return Result.error("已存在当前节点");
            }
        }
        //查询分公司名称
        if(ObjectUtils.isNotEmpty(approveNode.getSubCompanyId())){
            SubCompanyEntity subCompany = subCompanyService.getById(approveNode.getSubCompanyId());
            if (ObjectUtils.isNotEmpty(subCompany)){
                approveNode.setSubCompanyName(subCompany.getName());
            }
        }
        //查询审核人姓名
        List<Long> userIdList = new ArrayList<>();
        userIdList.add(approveNode.getApproveUserId());
        //查询消息接收人姓名
        if (ObjectUtils.isNotEmpty(approveNode.getSendUserids())) {
            List<Long> sendUserIdList = Arrays.asList(approveNode.getSendUserids().split(",")).stream().map(Long::valueOf).collect(Collectors.toList());
            userIdList.addAll(sendUserIdList);
        }
        List<UserEntity> userList = userService.listByIds(userIdList);
        Map<Long,UserEntity> userMap = userList.stream().collect(Collectors.toMap(UserEntity::getId, user->user));
        approveNode.setApproveUserName(userMap.get(approveNode.getApproveUserId()).getRealName());
        if (ObjectUtils.isNotEmpty(approveNode.getSendUserids())) {
            List<Long> sendUserIdList = Arrays.asList(approveNode.getSendUserids().split(",")).stream().map(Long::valueOf).collect(Collectors.toList());
            String sendUserNames = "";
            for (Long userId :sendUserIdList){
                sendUserNames = sendUserNames+ userMap.get(userId).getRealName() + ",";
            }
            approveNode.setSendUserNames(sendUserNames.substring(0, sendUserNames.length() - 1));
        }
        boolean isOk = approveNodeService.saveOrUpdate(approveNode);
        if (!isOk){
            return Result.error("操作失败！");
        }
        return Result.result("操作成功");
    }
    @ApiOperation("删除/批量删除审批节点")
    @DeleteMapping("/delete-by-ids")
    public Result remove(@NotNull @NotEmpty String ids) {
        List<Long> idList = Arrays.asList(ids.split(",")).stream().map(Long::valueOf).collect(Collectors.toList());
        boolean isOk = approveNodeService.removeByIds(idList);
        if (!isOk){
            return Result.error("删除失败！");
        }
        return Result.result("删除成功");
    }
}
