package com.casic.missiles.service.Impl.customer;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.casic.missiles.core.base.service.IBaseExportService;
import com.casic.missiles.core.model.auth.AuthUser;
import com.casic.missiles.core.shiro.ShiroKit;
import com.casic.missiles.dto.ReturnDTO;
import com.casic.missiles.dto.ReturnUtil;
import com.casic.missiles.dto.customer.advice.CustomerAdviceListRequest;
import com.casic.missiles.enums.BusinessExceptionEnum;
import com.casic.missiles.enums.ExportEnum;
import com.casic.missiles.enums.PrefixCodeEnum;
import com.casic.missiles.exception.BusinessException;
import com.casic.missiles.mapper.customer.CustomerAdviceMapper;
import com.casic.missiles.mapper.customer.CustomerMapper;
import com.casic.missiles.model.customer.CustomerAdviceInfo;
import com.casic.missiles.model.customer.CustomerInfo;
import com.casic.missiles.service.customer.CustomerAdviceService;
import com.casic.missiles.utils.DictCodeUtils;
import com.casic.missiles.utils.NumberGeneratorUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author cz
 */
@Service
@Slf4j
@AllArgsConstructor
public class CustomerAdviceServiceImpl implements CustomerAdviceService,PrefixCodeEnum {

    private final CustomerAdviceMapper customerAdviceMapper;
    private final IBaseExportService iBaseExportService;
    private final CustomerMapper customerMapper;

    @Override
    public Page<CustomerAdviceInfo> adviceListPage(Page<CustomerAdviceInfo> page, CustomerAdviceListRequest customerAdviceListRequest) throws Exception {
        QueryWrapper<CustomerAdviceInfo> wrapper = listParamWrapper(customerAdviceListRequest);
        Page<CustomerAdviceInfo> resultPage = customerAdviceMapper.selectPage(page, wrapper);
        for (CustomerAdviceInfo customerAdviceInfo : resultPage.getRecords()) {
            doCustomerAdviceInfoPopulation(customerAdviceInfo);
            DictCodeUtils.convertDictCodeToName(customerAdviceInfo);
        }
        return resultPage;
    }

    @Override
    public CustomerAdviceInfo adviceDetail(Long id) throws Exception{
        CustomerAdviceInfo customerAdviceInfo = customerAdviceMapper.selectById(id);
        doCustomerAdviceInfoPopulation(customerAdviceInfo);
        DictCodeUtils.convertDictCodeToName(customerAdviceInfo);
        return customerAdviceInfo;
    }

    @Override
    public ReturnDTO deleteAdvice(Long id) {
        int deleteFlag = customerAdviceMapper.deleteById(id);
        if (deleteFlag > 0) {
            return ReturnUtil.success();
        }
        throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
    }

    @Override
    public ReturnDTO updateAdvice(CustomerAdviceInfo customerAdviceInfo) {
        int updateFlag = customerAdviceMapper.updateById(customerAdviceInfo);
        if (updateFlag > 0) {
            return ReturnUtil.success();
        }
        throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
    }

    @Override
    public ReturnDTO addAdvice(CustomerAdviceInfo customerAdviceInfo) {
        initCustomerAdviceInfo(customerAdviceInfo);
        int addFlag = customerAdviceMapper.insert(customerAdviceInfo);
        if (addFlag > 0) {
            return ReturnUtil.success();
        }
        throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
    }

    @Override
    public void adviceExport(CustomerAdviceListRequest request, HttpServletResponse response) {
        try {
            List<CustomerAdviceInfo> customerAdviceList;
            if (!CollectionUtils.isEmpty(request.getIds())) {
                customerAdviceList = customerAdviceMapper.selectBatchIds(request.getIds());
            } else {
                QueryWrapper<CustomerAdviceInfo> wrapper = listParamWrapper(request);
                customerAdviceList = customerAdviceMapper.selectList(wrapper);
            }
            for (CustomerAdviceInfo customerAdviceInfo : customerAdviceList) {
                doCustomerAdviceInfoPopulation(customerAdviceInfo);
                DictCodeUtils.convertDictCodeToName(customerAdviceInfo);
            }
            iBaseExportService.exportExcel(response, CustomerAdviceInfo.class, customerAdviceList, ExportEnum.ADVICE_EXPORT.getSheetName());
        } catch (Exception e) {
            log.error("客户投诉导出出现异常，异常信息为{}", e);
        }
    }

    private QueryWrapper<CustomerAdviceInfo> listParamWrapper(CustomerAdviceListRequest request) {
        QueryWrapper<CustomerAdviceInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(request.getAdviceNo()), "advice_no", request.getAdviceNo());
        queryWrapper.like(StringUtils.isNotBlank(request.getCustomerName()), "customer_name", request.getCustomerName());
        queryWrapper.like(StringUtils.isNotBlank(request.getCustomerNo()), "customer_no", request.getCustomerNo());
        queryWrapper.apply(StringUtils.isNotBlank(request.getStartTime()),
                "{0}  <=DATE_FORMAT(advice_time,'%Y-%m-%d')", request.getStartTime());
        queryWrapper.apply(StringUtils.isNotBlank(request.getEndTime()),
                "{0} >= DATE_FORMAT(advice_time,'%Y-%m-%d')", request.getEndTime());
        queryWrapper.orderByDesc("create_time");
        return queryWrapper;
    }

    private void initCustomerAdviceInfo(CustomerAdviceInfo customerAdviceInfo) {
        Long maxNo = customerAdviceMapper.selectMaxAdviceNo();
        String adviceNo = NumberGeneratorUtil.getContactNo(CUSTOMER_ADVICE_PREFIX, maxNo);
        AuthUser authUser = ShiroKit.getUser();
        customerAdviceInfo.setCreateUser(authUser.getId());
        customerAdviceInfo.setUpdateUser(authUser.getId());
        customerAdviceInfo.setAdviceNo(adviceNo);
    }

    private void doCustomerAdviceInfoPopulation(CustomerAdviceInfo customerAdviceInfo) {
        CustomerInfo customerInfo  =customerMapper.selectById(customerAdviceInfo.getCustomerId());
        if(!ObjectUtils.isEmpty(customerInfo)){
            customerAdviceInfo.setCompanySize(customerInfo.getCompanySize());
            customerAdviceInfo.setBusinessSize(customerInfo.getBusinessSize());
            customerAdviceInfo.setEvaluation(customerInfo.getEvaluation());
            customerAdviceInfo.setGrade(customerInfo.getGrade());
        }
    }
}
