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.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("/order-form")
@Api(tags = "销售: 订单管理相关接口")
@Log4j2
public class OrderFormController {

    @Resource
    private OrderFormService orderFormService;
    @Resource
    private MessageAssembleService assembleService;
    @Resource
    private SysResourceService resourceService;
    @Resource
    private TaskService taskService;
    @Resource
    private CustomerFollowUpService customerFollowUpService;
    @Resource
    private QuotationService quotationService;
    @Resource
    private BusinessService businessService;
    @Resource
    private SendRecordService sendRecordService;
    @Resource
    private OperationLogService operationLogService;
    @Resource
    private RedisService redisService;

    @PostMapping(value = "/add")
    @ApiOperation(value = "订单管理-新增订单", notes = "订单管理-新增订单")
    @Transactional(rollbackFor = Throwable.class)
    public Result<?> add(@RequestBody OrderFormAddDTO orderFormAddDTO) {
        return orderFormService.addOrderForm(orderFormAddDTO);
    }
    @PostMapping(value = "/edit")
    @ApiOperation(value = "订单管理-编辑订单", notes = "订单管理-编辑订单")
    @Transactional(rollbackFor = Throwable.class)
    public Result<?> edit(@RequestBody OrderFormAddDTO orderFormAddDTO) {
        return orderFormService.editOrderForm(orderFormAddDTO);
    }


    @PostMapping(value = "/list")
    @ApiOperation(value = "订单管理查询-列表", notes = "订单管理查询-列表")
    public Result<IPage<OrderFormListVO>> list(@RequestBody OrderFormSearchDTO orderFormSearchDTO) {

        return orderFormService.selectListVO(orderFormSearchDTO);
    }

    /**
     * 通过id查询
     *
     * @return
     */
//    @GetMapping(value = "/get-by-id")
    @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("参数异常");
        }
        OrderFormDetailVO orderFormDetailVO = orderFormService.getOrderFormVOById(commonSearchDTO.getId());
        return Result.result(orderFormDetailVO);
    }

    @PostMapping(value = "/data-count")
    @ApiOperation(value = "订单管理-关联数据统计", notes = "订单管理-关联数据统计")
    @Transactional(rollbackFor = Throwable.class)
    public Result<OrderCountVO> dataCount(@RequestBody OrderFormSearchDTO orderFormSearchDTO) {
        OrderCountVO orderCountVO  = new OrderCountVO();
//      操作日志
        QueryWrapper olWrapper =  new QueryWrapper<>();
        olWrapper.eq("resource_type_id", orderFormSearchDTO.getId());
        olWrapper.eq("resource_type", 40);
        olWrapper.eq("is_delete", CommonConstant.DEL_FLAG_0);
//        系统资源、寄样、跟进记录
        QueryWrapper customerwrapper =  new QueryWrapper<>();
        customerwrapper.eq("customer_id", orderFormSearchDTO.getCustomerId());
        customerwrapper.eq("resource_type_id", orderFormSearchDTO.getId());
        customerwrapper.eq("resource_type", 40);
        customerwrapper.eq("is_delete", CommonConstant.DEL_FLAG_0);

        orderCountVO.setSendRecordCount(sendRecordService.count(customerwrapper));
        orderCountVO.setFollowUpCount(customerFollowUpService.count(customerwrapper));
        LambdaQueryWrapper<QuotationEntity> quotatiomWrapper = new LambdaQueryWrapper<>();
        quotatiomWrapper.eq(QuotationEntity::getOrderFormId, orderFormSearchDTO.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();
        }
        orderCountVO.setQuotationCount(totalOrderAmt);
        orderCountVO.setAttachmentCount(resourceService.count(customerwrapper));
        orderCountVO.setOperationCount(operationLogService.count(olWrapper));
        return Result.result(orderCountVO);
    }

    @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");
        OrderFormDetailVO orderFormDetailVO = orderFormService.getOrderFormVOById(commonSearchDTO.getId());
        Object ids = redisService.getCacheObject(preNexKey);
        findNeighbors(ids,orderFormDetailVO);
        return Result.result(orderFormDetailVO);
    }

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

    @ApiOperation(value = "订单管理-删除客户", notes = "订单管理-删除客户")
    @PostMapping("delete")
    public Result delete(@RequestBody BusinessDeleteDTO businessDeleteDTO) {

        boolean deleteOk = false;
        if(!ObjectUtils.isEmpty(businessDeleteDTO.getId())) {
            OrderFormEntity orderFormOld = orderFormService.getById(businessDeleteDTO.getId());
//            deleteOk = orderFormService.lgDelete(businessDeleteDTO.getId());
            OrderFormEntity orderForm = new OrderFormEntity();
            orderForm.setId(businessDeleteDTO.getId());
            orderForm.setBusinessId(null);
            LambdaUpdateWrapper<OrderFormEntity> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(OrderFormEntity::getId,businessDeleteDTO.getId());
            updateWrapper.set(OrderFormEntity::getBusinessId,0);
            updateWrapper.set(OrderFormEntity::getQuotationId,0);
            updateWrapper.set(OrderFormEntity::getIsDelete, CommonConstant.DEL_FLAG_1);
            deleteOk = orderFormService.update(updateWrapper);

            if (!ObjectUtils.isEmpty(orderFormOld.getBusinessId())){
                LambdaUpdateWrapper<BusinessEntity> businessUpdateWrapper = new LambdaUpdateWrapper<>();
                businessUpdateWrapper.eq(BusinessEntity::getId, orderFormOld.getBusinessId());
                businessUpdateWrapper.set(BusinessEntity::getStage, "3");
                businessService.update(businessUpdateWrapper);
            }

            LambdaUpdateWrapper<QuotationEntity> quotationUpdateWrapper = new LambdaUpdateWrapper<>();
            quotationUpdateWrapper.eq(QuotationEntity::getOrderFormId,businessDeleteDTO.getId());
            quotationUpdateWrapper.set(QuotationEntity::getOrderFormId,0);
            quotationService.update(quotationUpdateWrapper);

            assembleService.sendOrderEventMessages(orderFormOld.getId(),"DELETE_ORDER");
        }
        if(!CollectionUtils.isEmpty(businessDeleteDTO.getIds())) {
            deleteOk = orderFormService.lgDelete(businessDeleteDTO.getIds());
        }
        if(!deleteOk) {
            return Result.error("删除失败");
        }

        Long id = businessDeleteDTO.getId();
        List<CustomerFollowUpEntity> followUpls = customerFollowUpService.listByResourceId(ResourceTypeEnum.ORDER_FORM.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.ORDER_FORM.code, id);
        customerFollowUpService.deleteByResourceId(ResourceTypeEnum.ORDER_FORM.code, id);
        resourceService.deleteByResourceId(ResourceTypeEnum.ORDER_FORM.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();
    }

}
