package com.storlead.sales.controller.customer;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.storlead.framework.common.constant.CommonConstant;
import com.storlead.framework.common.util.MD5Util;
import com.storlead.framework.util.LoginUserUtil;
import com.storlead.framework.common.result.Result;
import com.storlead.framework.redis.RedisService;
import com.storlead.sales.pojo.dto.customer.*;
import com.storlead.sales.pojo.entity.customer.BusinessEntity;
import com.storlead.sales.pojo.entity.customer.CustomerFollowUpEntity;
import com.storlead.sales.pojo.entity.customer.OrderFormEntity;
import com.storlead.sales.pojo.vo.customer.*;
import com.storlead.sales.enums.ResourceTypeEnum;
import com.storlead.sales.pojo.entity.sku.QuotationEntity;
import com.storlead.sales.service.customer.*;
import com.storlead.sales.service.sku.QuotationService;
import com.storlead.sales.service.sku.SsdSkuService;
import com.storlead.sales.service.systemrule.OperationLogService;
import com.storlead.sales.service.task.TaskService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import javax.annotation.Resource;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

/**
 * <p>
 * 商机表 前端控制器
 * </p>
 *
 * @author YPZ
 * @since 2024-05-10
 */
@RestController
@RequestMapping("/business")
@Api(tags = "销售: 商机管理相关接口")
@Log4j2
public class BusinessController {

    @Resource
    private BusinessService businessService;
    @Resource
    private MessageAssembleService assembleService;
    @Resource
    private CustomerFollowUpService customerFollowUpService;
    @Resource
    private SysResourceService resourceService;
    @Resource
    private TaskService taskService;
    @Resource
    private OrderFormService orderFormService;
    @Resource
    private SendRecordService sendRecordService;
    @Resource
    private QuotationService quotationService;
    @Resource
    private LiaisonService liaisonService;
    @Resource
    private LiaisonResourceService liaisonResourceService;
    @Resource
    private OperationLogService operationLogService;
    @Resource
    private SsdSkuService ssdSkuService ;
    @Resource
    private RedisService redisService;
    @PostMapping(value = "/add")
    @ApiOperation(value = "商机管理-新增/修改商机", notes = "商机管理-新增/修改商机")
    public Result<?> add(@RequestBody BusinessAddDTO businessAddDTO) {
        return businessService.addBusiness(businessAddDTO);
    }


    @PostMapping(value = "/list")
    @ApiOperation(value = "商机管理查询-列表", notes = "商机管理查询-列表")
    public Result<IPage<BusinessListVO>> list(@RequestBody BusinessSearchDTO businessSearchDTO) {
        Result result = businessService.selectListVO(businessSearchDTO);
        return result;
    }

//    @PostMapping(value = "/collaborator")
//    @ApiOperation(value = "商机管理查询-添加协作", notes = "商机管理查询-添加协作")
//    public Result<?> collaborator(@RequestBody BusinessCollaboratorDTO businessCollaboratorDTO) {
//        return businessService.collaborator(businessCollaboratorDTO);
//    }

    @PostMapping(value = "/change-stage")
    @ApiOperation(value = "商机管理-更改商机阶段", notes = "商机管理-更改商机阶段")
    public Result<?> changeStage(@RequestBody BusinessChangeStageDTO businessChangeStage) {
        return businessService.changeStage(businessChangeStage);
    }

    @PostMapping(value = "/change-loss")
    @ApiOperation(value = "商机管理-更改商机流失状态", notes = "商机管理-更改商机流失状态")
    public Result<?> changeLoss(@RequestBody BusinessLossDTO businessLossDTO) {
        return businessService.businessLoss(businessLossDTO);
    }

    /**
     * 通过id查询
     *
     * @return
     */
    @PostMapping(value = "/get-by-id")
    @ApiOperation(value = "商机管理查询-通过id查看详情", notes = "商机管理查询-通过id查看详情")
    public Result<?> getById(@RequestBody CommonSearchDTO commonSearchDTO) {
        if (ObjectUtils.isEmpty(commonSearchDTO) || ObjectUtils.isEmpty(commonSearchDTO.getId())){
            return Result.error("参数异常");
        }
        BusinessDetailVO businessDetailVO = businessService.getBusinessVOById(commonSearchDTO.getId());
        return Result.result(businessDetailVO);
    }

//    @GetMapping(value = "/get-all-by-id")
    @PostMapping(value = "/get-all-by-id")
    @ApiOperation(value = "商机管理查询-通过id查看全部概况信息", notes = "商机管理查询-通过id查看全部概况信息")
    public Result<?> getAllById(@RequestBody CommonSearchDTO commonSearchDTO) {
        if (ObjectUtils.isEmpty(commonSearchDTO) || ObjectUtils.isEmpty(commonSearchDTO.getId())){
            return Result.error("参数异常");
        }
        BusinessAllDetailVO businessAllDetailVO = businessService.getBusinessAllVOById(commonSearchDTO.getId());
        return Result.result(businessAllDetailVO);
    }

    @PostMapping(value = "/get-pre-nex-by-id")
    @ApiOperation(value = "商机管理查询-通过id查看商机资料详情", notes = "商机管理查询-通过id查看商机资料详情")
    public Result<?> getAllByIdlist(@RequestBody CommonSearchDTO commonSearchDTO) {
        String jsonKey = JSON.toJSONString(commonSearchDTO.getPreNextScopeMenuId()+"_"+ LoginUserUtil.getCurrentUserId());
        log.error("jsonKey 2= "+jsonKey);
        String preNexKey = MD5Util.MD5Encode(jsonKey,"UTF-8");
        BusinessAllDetailVO businessAllDetailVO = businessService.getBusinessAllVOById(commonSearchDTO.getId());
        Object ids = redisService.getCacheObject(preNexKey);
        findNeighbors(ids,businessAllDetailVO);
        return Result.result(businessAllDetailVO);
    }

    public static void findNeighbors(Object ids, BusinessAllDetailVO businessAllDetailVO) {
        try {
            List<Long> list =  (List)ids;
            Long target = businessAllDetailVO.getId();
            if (CollectionUtils.isEmpty(list) || Objects.isNull(target)) {
                return;
            }
            int index = list.indexOf(target);
            if (index == -1) {
                return;
            }
            // 查找上一个元素
            if (index > 0) {
                businessAllDetailVO.setPreviousId(list.get(index - 1));
            }
            // 查找下一个元素
            if (index < list.size() - 1) {
                businessAllDetailVO.setNextId(list.get(index + 1));
            }
        }catch (Exception e) {
            log.error("findNeighbors -- error",e);
        }
    }

    @PostMapping(value = "/data-count")
    @ApiOperation(value = "商机管理-关联数据统计", notes = "商机管理-关联数据统计")
    @Transactional(rollbackFor = Throwable.class)
    public Result<BusinessCountVO> dataCount(@RequestBody BusinessSearchDTO businessDTO) {
        BusinessCountVO businessCountVO  = new BusinessCountVO();
//        操作日志、联系人关联
        QueryWrapper olWrapper =  new QueryWrapper<>();
        olWrapper.eq("resource_type_id", businessDTO.getId());
        olWrapper.eq("resource_type", 30);
        olWrapper.eq("is_delete", CommonConstant.DEL_FLAG_0);
//        系统资源、寄样、跟进记录
        QueryWrapper customerWrapper =  new QueryWrapper<>();
        customerWrapper.eq("resource_type_id", businessDTO.getId());
        customerWrapper.eq("customer_id", businessDTO.getCustomerId());
        customerWrapper.eq("resource_type", 30);
        customerWrapper.eq("is_delete", CommonConstant.DEL_FLAG_0);
//        订单关联
        QueryWrapper wrapper =  new QueryWrapper<>();
        wrapper.eq("business_id", businessDTO.getId());
        wrapper.eq("is_delete", CommonConstant.DEL_FLAG_0);
        businessCountVO.setOrderFormCount(orderFormService.count(wrapper));
        businessCountVO.setSendRecordCount(sendRecordService.count(customerWrapper));
        businessCountVO.setLisionCount(liaisonResourceService.count(olWrapper));
        businessCountVO.setFollowUpCount(customerFollowUpService.count(customerWrapper));
        LambdaQueryWrapper<QuotationEntity> quotatiomWrapper = new LambdaQueryWrapper<>();
        quotatiomWrapper.eq(QuotationEntity::getBusinessId, businessDTO.getId());
        quotatiomWrapper.eq(QuotationEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        List<QuotationEntity> quotationEntities = quotationService.list(quotatiomWrapper);
        BigDecimal totalOrderAmt = BigDecimal.ZERO;
        if (!quotationEntities.isEmpty()) {
            QuotationEntity quotationEntity = quotationEntities.get(0);
            totalOrderAmt = quotationEntity.getTotalOrderAmt();
        }
        businessCountVO.setQuotationCount(totalOrderAmt);
        businessCountVO.setAttachmentCount(resourceService.count(customerWrapper));
        businessCountVO.setOperationCount(operationLogService.count(olWrapper));

        return Result.result(businessCountVO);
    }


    @ApiOperation(value = "商机管理查询-删除商机", notes = "商机管理查询-删除商机")
    @PostMapping("delete")
    public Result delete(@RequestBody BusinessDeleteDTO businessDeleteDTO) {
        BusinessEntity business = businessService.getById(businessDeleteDTO.getId());
        Integer orderCount = orderFormService.count(new LambdaQueryWrapper<OrderFormEntity>().eq(OrderFormEntity::getBusinessId,business.getId()).eq(OrderFormEntity::getIsDelete, CommonConstant.DEL_FLAG_0));
        if (orderCount > 0) {
            return Result.error("商机下有订单，无法删除");
        }
        businessService.lgDelete(businessDeleteDTO.getId());
        //发送消息
        assembleService.sendBusinessEventMessages(business.getId(),"DELETE_OPPORTUNITY");

        Long id = businessDeleteDTO.getId();
        List<CustomerFollowUpEntity> followUpls = customerFollowUpService.listByResourceId(ResourceTypeEnum.BUSINESS.code,id);
        if (!CollectionUtils.isEmpty(followUpls)) {
            List<Long> followUpIds = followUpls.stream().map(CustomerFollowUpEntity::getId).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(followUpIds)) {
                resourceService.deleteByResourceIds(ResourceTypeEnum.FOLLOW_UP.code,followUpIds);
            }
        }
        //删除任务
        taskService.deleteByResourceId(ResourceTypeEnum.BUSINESS.code, id);
        customerFollowUpService.deleteByResourceId(ResourceTypeEnum.BUSINESS.code, id);
        resourceService.deleteByResourceId(ResourceTypeEnum.BUSINESS.code,id);
        LambdaUpdateWrapper<QuotationEntity> quotationWrapper = new LambdaUpdateWrapper<>();
        quotationWrapper.eq(QuotationEntity::getBusinessId,id);
        quotationWrapper.set(QuotationEntity::getBusinessId,0);
        quotationService.update(quotationWrapper);
        //对全部未关联商机及订单的报价单，清除客户关联
        quotationService.deleteCustomerId();
        return Result.ok();
    }
}
