package com.storlead.sales.controller.customer;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.storlead.framework.common.constant.CommonConstant;
import com.storlead.framework.common.result.Result;
import com.storlead.sales.pojo.dto.customer.*;
import com.storlead.sales.pojo.entity.customer.LiaisonEntity;
import com.storlead.sales.pojo.vo.customer.LiaisonCountVO;
import com.storlead.sales.pojo.vo.customer.LiaisonListVO;
import com.storlead.sales.service.customer.*;
import com.storlead.sales.service.impl.customer.BusinessServiceImpl;
import com.storlead.sales.service.CustomerMailBingMarkService;
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 io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
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.util.List;
import java.util.Objects;

/**
 * <p>
 * 联系人表 前端控制器
 * </p>
 *
 * @author YPZ
 * @since 2024-04-12
 */
@RestController
@RequestMapping("/liaison")
@Api(tags = "销售: 客户联系人管理相关接口")
public class LiaisonController {

    @Resource
    private LiaisonService liaisonService;
    @Resource
    private BusinessService businessService;
    @Resource
    private OperationLogService operationLogService;
    @Resource
    private CustomerMailBingMarkService customerMailBingMarkService;
    @Resource
    private CustomerService customerService;
    @Resource
    private TaskService taskService;
    @Resource
    private BusinessServiceImpl businessServiceImpl;

    @PostMapping(value = "/add")
    @ApiOperation(value = "客户联系人管理-新增/修改客户联系人", notes = "客户联系人管理-新增/修改客户联系人")
    @Transactional(rollbackFor = Throwable.class)
    public Result<?> add(@RequestBody LiaisonAddDTO locationAddDTO) {

        return liaisonService.addOrEdit(locationAddDTO);

    }

    @PostMapping(value = "/list")
    @ApiOperation(value = "客户联系人查询-列表", notes = "客户联系人查询-列表")
    @ApiResponses({
            @ApiResponse(code = 200, message = "", response = LiaisonSearchDTO.class)
    })
    public Result<?> list(@RequestBody LiaisonSearchDTO liaisonSearchDTO) {

        return liaisonService.selectListVO(liaisonSearchDTO);

    }

    @PostMapping(value = "/list-by-resource")
    @ApiOperation(value = "客户联系人查询-资源关联联系人列表", notes = "客户联系人查询-资源关联联系人列表")
    @ApiResponses({
            @ApiResponse(code = 200, message = "", response = LiaisonSearchDTO.class)
    })
    public Result<?> listByResource(@RequestBody LiaisonSearchDTO liaisonSearchDTO) {

        return liaisonService.listByResource(liaisonSearchDTO);

    }

    @PostMapping(value = "/get-primary-lialison")
    @ApiOperation(value = "客户联系人查询-通过客户id查看首要联系人", notes = "客户联系人查询-通过客户id查看首要联系人")
    @ApiResponses({
            @ApiResponse(code = 200, message = "", response = LiaisonSearchDTO.class)
    })
    public Result<?> getPrimaryLialison(@RequestBody LiaisonSearchDTO liaisonSearchDTO) {

        return liaisonService.getPrimaryLialison(liaisonSearchDTO);

    }

    @PostMapping(value = "/change-primary-lialison")
    @ApiOperation(value = "客户联系人变更-变更首要联系人", notes = "客户联系人变更-变更首要联系人")
    @ApiResponses({
            @ApiResponse(code = 200, message = "", response = LiaisonSearchDTO.class)
    })
    public Result<?> changePrimaryLialison(@RequestBody LiaisonSearchDTO liaisonSearchDTO) {

        return liaisonService.changePrimaryLialison(liaisonSearchDTO);

    }

    /**
     * 通过id查询
     *
     * @return
     */
//    @GetMapping(value = "/get-by-id")
    @PostMapping(value = "/get-by-id")
    @ApiOperation(value = "客户联系人查询-通过id查看详情", notes = "客户联系人查询-通过id查看详情")
    public Result<?> getById(CommonSearchDTO commonSearchDTO) {
        if (ObjectUtils.isEmpty(commonSearchDTO) || ObjectUtils.isEmpty(commonSearchDTO.getId())){
            return Result.error("参数异常");
        }
        LiaisonListVO liaisonListVO = liaisonService.getLiaisonById(commonSearchDTO.getId());
        return Result.result(liaisonListVO);
    }

    @PostMapping(value = "/data-count")
    @ApiOperation(value = "客户联系人管理-关联数据统计", notes = "客户联系人管理-关联数据统计")
    @Transactional(rollbackFor = Throwable.class)
    public Result<LiaisonCountVO> dataCount(@RequestBody LiaisonSearchDTO liaisonDTO) {
        LiaisonCountVO liaisonCountVO  = new LiaisonCountVO();
//      操作日志
        QueryWrapper olWrapper =  new QueryWrapper<>();
        olWrapper.eq("resource_type_id", liaisonDTO.getId());
        olWrapper.eq("resource_type", 20);
        olWrapper.eq("is_delete", CommonConstant.DEL_FLAG_0);
//      系统资源
        QueryWrapper syswrapper =  new QueryWrapper<>();
        syswrapper.eq("customer_id", liaisonDTO.getCustomerId());
        syswrapper.eq("resource_type_id", liaisonDTO.getId());
        syswrapper.eq("resource_type", 20);
        syswrapper.eq("is_delete", CommonConstant.DEL_FLAG_0);
//      联系人
        QueryWrapper liaisonwrapper =  new QueryWrapper<>();
        liaisonwrapper.ne("id", liaisonDTO.getId());
        liaisonwrapper.eq("customer_id", liaisonDTO.getCustomerId());
        liaisonwrapper.eq("is_delete", CommonConstant.DEL_FLAG_0);
//      商机
        QueryWrapper wrapper =  new QueryWrapper<>();
        wrapper.eq("liaison_id", liaisonDTO.getId());
        wrapper.eq("is_delete", CommonConstant.DEL_FLAG_0);
//      邮件
        QueryWrapper emailwrapper =  new QueryWrapper<>();
        emailwrapper.apply("FIND_IN_SET({0}, liaison_ids)", liaisonDTO.getId()); // 使用参数化查询
        emailwrapper.eq("is_delete", CommonConstant.DEL_FLAG_0);
        liaisonCountVO.setBusinessCount(businessService.count(wrapper));
        liaisonCountVO.setLiaisonCount(liaisonService.count(liaisonwrapper));
        liaisonCountVO.setEmailCount(customerMailBingMarkService.count(emailwrapper));
        liaisonCountVO.setOperationCount(operationLogService.count(olWrapper));
        return Result.result(liaisonCountVO);
    }

    @ApiOperation(value = "客户联系人管理-删除", notes = "客户联系人管理-删除")
    @PostMapping("delete")
    public Result delete(@RequestBody BusinessDeleteDTO businessDeleteDTO) {
        boolean deleteOk = false;
        if(!ObjectUtils.isEmpty(businessDeleteDTO.getId())) {
            LiaisonEntity liaisonEntity = liaisonService.getById(businessDeleteDTO.getId());
            if (Objects.nonNull(liaisonEntity) && liaisonEntity.getHasPrimaryLialison()){
                return Result.error("该联系人为首要联系人，无法删除！");
            }
            deleteOk = liaisonService.lgDelete(businessDeleteDTO.getId());
        }
        if(!CollectionUtils.isEmpty(businessDeleteDTO.getIds())) {
            List<LiaisonEntity> liaisonList = liaisonService.listByIds(businessDeleteDTO.getIds());
            for (LiaisonEntity liaisonEntity : liaisonList){
                if (Objects.nonNull(liaisonEntity) && liaisonEntity.getHasPrimaryLialison()){
                    return Result.error("存在首要联系人，无法删除！");
                }
            }
            deleteOk = liaisonService.lgDelete(businessDeleteDTO.getIds());
        }
        if(!deleteOk) {
            return Result.error("删除失败");
        }
        return Result.ok();
    }
}
