package com.dsk.system.service.impl;

import cn.hutool.core.bean.BeanException;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.dsk.common.core.domain.R;
import com.dsk.common.exception.ServiceException;
import com.dsk.common.utils.SecurityUtils;
import com.dsk.system.domain.customer.Customer;
import com.dsk.system.domain.customer.CustomerUser;
import com.dsk.system.domain.customer.dto.CustomerBusinessSearchDto;
import com.dsk.system.domain.customer.dto.CustomerSearchDto;
import com.dsk.system.domain.customer.vo.*;
import com.dsk.system.dskService.EnterpriseService;
import com.dsk.system.mapper.CustomerMapper;
import com.dsk.system.mapper.CustomerUserMapper;
import com.dsk.system.service.IBusinessInfoService;
import com.dsk.system.service.ICustomerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * 客户信息表(Customer)表服务实现类
 *
 * @author makejava
 * @since 2023-05-16 09:27:57
 */
@Slf4j
@Service
public class CustomerServiceImpl implements ICustomerService {

    @Resource
    private CustomerMapper baseMapper;
    @Resource
    private CustomerUserMapper customerUserMapper;
    @Autowired
    private IBusinessInfoService businessInfoService;
    @Autowired
    private EnterpriseService enterpriseService;

    @Override
    public List<CustomerListVo> selectList(CustomerSearchDto dto) {
        dto.setUserId(SecurityUtils.getUserId());
        dto.setStatus(ObjectUtils.isEmpty(dto.getStatus()) ? 0 : dto.getStatus());
        return baseMapper.selectList(dto);
    }

    @Override
    public CustomerVo info(String customerId) {
        CustomerVo vo = new CustomerVo();
        BeanUtil.copyProperties(baseMapper.selectById(customerId), vo);
        CustomerUser customerUser = customerUserMapper.selectOne(Wrappers.<CustomerUser>lambdaQuery()
                .eq(CustomerUser::getCustomerId, customerId));
        vo.setUserId(customerUser.getUserId());
        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean add(Customer customer) {
        if (ObjectUtils.isEmpty(customer.getUipId())) {
            try {
                R res = enterpriseService.getUipId(customer.getCompanyName());
                if (!ObjectUtils.isEmpty(res.getData())) {
                    customer.setUipId(MapUtil.getStr(BeanUtil.beanToMap(res.getData()), "uipId"));
                }
            } catch (Exception e) {
                log.error("获取城投平台企业id错误！error：{}", e.getMessage());
            }
        }
        Long userId = SecurityUtils.getUserId();
        customer.setCreateId(userId);
        customer.setUpdateId(userId);
        //查重
        Customer verifyCustomer = baseMapper.selectByCompanyNameAndUserId(customer.getCompanyName(), userId);
        if (!ObjectUtils.isEmpty(verifyCustomer)) {
            throw new ServiceException("当前客户信息已存在，请勿重复添加！");
        }

        int i = baseMapper.insert(customer);
        if (i == 0) throw new ServiceException("客户信息添加错误！");

        int ui = customerUserMapper.insert(new CustomerUser(customer.getCustomerId(), userId));
        if (ui == 0) throw new ServiceException("客户跟进人信息添加错误！");

        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean edit(Customer customer) {
        if (ObjectUtils.isEmpty(customer.getCustomerId())) throw new BeanException("客户id不能为空");
        customer.setUpdateId(SecurityUtils.getUserId());
        int u = baseMapper.updateById(customer);
        return u != 0;
    }

    @Override
    public List<Customer> selectUserList() {
        return baseMapper.selectUserList(SecurityUtils.getUserId());
    }

    @Override
    public List<CustomerBusinessListVo> selectBusinessList(CustomerBusinessSearchDto dto) {
        if (ObjectUtils.isEmpty(dto.getCustomerId())) throw new BeanException("客户id不能为空");
        dto.setUserId(SecurityUtils.getUserId());
        return businessInfoService.selectCustomerBusinessList(dto);
    }

    @Override
    public List<CustomerStatusListVo> selectStatusList(List<String> uipIds) {
        return baseMapper.selectStatusList(uipIds, SecurityUtils.getUserId());
    }

    @Override
    public List<CustomerStatusListVo> selectStatusListByCompanyName(List<String> companyNames) {
        return baseMapper.selectStatusListByCompanyName(companyNames, SecurityUtils.getUserId());
    }


//    @Override
//    public List<String> selectUipIdList(List<String> uipIds) {
//        return baseMapper.selectUipIdList(uipIds, SecurityUtils.getUserId());
//    }

    @Override
    public Integer status(String companyName) {
        Customer cus = baseMapper.selectByCompanyNameAndUserId(companyName, SecurityUtils.getUserId());
        if (ObjectUtils.isEmpty(cus)) {
            return null;
        }
        CustomerUser customerUser = customerUserMapper.selectByCustomerIdAndUserId(cus.getCustomerId(), SecurityUtils.getUserId());
        if (ObjectUtils.isEmpty(customerUser)) {
            throw new ServiceException("数据错误！");
        }
        return customerUser.getStatus();
    }

    @Override
    public boolean cancelClaim(String companyName) {
        return updateClaimStatus(companyName, 1);
    }

    @Override
    public boolean historyClaim(String companyName) {
        return updateClaimStatus(companyName, 0);
    }

    //修改客户认领状态
    private boolean updateClaimStatus(String companyName, Integer status) {
        Customer cus = baseMapper.selectByCompanyNameAndUserId(companyName, SecurityUtils.getUserId());
        if (ObjectUtils.isEmpty(cus)) {
            throw new ServiceException("数据错误！");
        }
        CustomerUser customerUser = customerUserMapper.selectByCustomerIdAndUserId(cus.getCustomerId(), SecurityUtils.getUserId());
        if (ObjectUtils.isEmpty(customerUser)) {
            throw new ServiceException("数据错误！");
        }
        customerUser.setStatus(status);
        return customerUserMapper.updateById(customerUser) == 1;
    }


}
