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.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.casic.missiles.core.base.service.IBaseExportService;
import com.casic.missiles.core.model.auth.AuthUser;
import com.casic.missiles.core.page.PageFactory;
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.CertificationResponse;
import com.casic.missiles.dto.customer.Info.*;
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.CustomerMapper;
import com.casic.missiles.mapper.customer.CustomerUserMapper;
import com.casic.missiles.mapper.customer.customize.CustomerInfoResponseMapper;
import com.casic.missiles.mapper.customer.customize.SampleRecordsResponseMapper;
import com.casic.missiles.model.customer.CustomerInfo;
import com.casic.missiles.model.customer.CustomerSampleInfo;
import com.casic.missiles.model.customer.CustomerUserInfo;
import com.casic.missiles.service.customer.CustomerService;
import com.casic.missiles.utils.DictCodeUtils;
import com.casic.missiles.utils.NumberGeneratorUtil;
import liquibase.pro.packaged.E;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import java.util.List;
import java.util.Set;

@Service
@Slf4j
@AllArgsConstructor
public class CustomerServiceImpl extends ServiceImpl<CustomerMapper, CustomerInfo> implements CustomerService,PrefixCodeEnum {

    private final SampleRecordsResponseMapper sampleRecordsResponseMapper;
    private final CustomerUserMapper customerUserMapper;
    private final IBaseExportService iBaseExportService;
    private final CustomerInfoResponseMapper customerInfoResponseMapper;

    @Override
    public Page<CustomerInfoResponse> listPage(Page<CustomerInfoResponse> page, CustomerListRequest request) throws Exception {
        QueryWrapper<CustomerInfoResponse> wrapper = listParamWrapper(request);
        Page<CustomerInfoResponse> resultPage = customerInfoResponseMapper.selectPage(page, wrapper);
        for (CustomerInfoResponse customerInfo : resultPage.getRecords()) {
            DictCodeUtils.convertDictCodeToName(customerInfo);
        }
        return resultPage;
    }

    @Override
    public List<CustomerInfoResponse> customerList( CustomerListRequest request) throws Exception {
        QueryWrapper<CustomerInfoResponse> wrapper = listParamWrapper(request);
        List<CustomerInfoResponse> resultList = customerInfoResponseMapper.selectList(wrapper);
        for (CustomerInfoResponse customerInfo : resultList) {
            DictCodeUtils.convertDictCodeToName(customerInfo);
        }
        return resultList;
    }

    @Override
    @Transactional
    public ReturnDTO addCustomer(CustomerInfo customerInfo) throws Exception {
        DictCodeUtils.validDictCode(customerInfo);
        initCustomerInfo(customerInfo);
        int addFlag = this.baseMapper.insert(customerInfo);
        Boolean userAddFlag = userInfoListCreator(customerInfo.getCustomerUserList(), customerInfo.getId());
        if (addFlag > 0 && userAddFlag) {
            return ReturnUtil.success();
        }
        throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
    }

    @Override
    @Transactional
    public ReturnDTO addCustomerList(List<CustomerInfo> list) throws Exception {
        //用于存储验证后的错误信息
        Long maxNo = this.baseMapper.selectMaxCustomerNo();
        for (CustomerInfo item : list) {
            Set<ConstraintViolation<CustomerInfo>> validate = Validation.buildDefaultValidatorFactory().getValidator().validate(item);
            if (!CollectionUtils.isEmpty(validate)) {
                return ReturnUtil.failed(validate.iterator().next().getMessage());
            }
            DictCodeUtils.validDictCode(item);
            //生成编号
            String customerNo = NumberGeneratorUtil.getContactNo(CUSTOMER_PREFIX, maxNo);
            item.setCustomerNo(customerNo);
            maxNo++;
        }
        super.saveBatch(list);
        return ReturnUtil.success();
    }

    @Override
    @Transactional
    public ReturnDTO updateCustomer(CustomerInfo customerInfo) {
        AuthUser authUser = ShiroKit.getUser();
        customerInfo.setUpdateUser(authUser.getId());
        userInfoListDeletor(customerInfo.getId());
        int updateFlag = this.baseMapper.updateById(customerInfo);
        Boolean userUpdateFlag = userInfoListCreator(customerInfo.getCustomerUserList(),customerInfo.getId());
        if (updateFlag > 0 && userUpdateFlag) {
            return ReturnUtil.success();
        }
        throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
    }

    @Override
    public CustomerInfo customerDetail(Long id) {
        CustomerInfo customerInfo = this.baseMapper.selectById(id);
        customerInfo.setCustomerUserList(customerUserDetail(id));
        return customerInfo;
    }

    @Override
    public ReturnDTO deleteCustomer(Long id) {
        CustomerInfo customerInfo = this.baseMapper.selectById(id);
        int deleteFlag = this.baseMapper.deleteById(id);
        userInfoListDeletor(customerInfo.getId());
        if (deleteFlag > 0) {
            return ReturnUtil.success();
        }
        throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
    }

    @Override
    public Page<SampleRecordsResponse> sampleRecordsByCustomerId(Long customerId) {
        Page<SampleRecordsResponse> page = PageFactory.defaultPage();
        QueryWrapper<SampleRecordsResponse> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("customer_id", customerId);
        queryWrapper.orderByDesc("create_time");
        return sampleRecordsResponseMapper.selectPage(page, queryWrapper);
    }


    @Override//暂定不做
    public Page<ContractRecordsResponse> contractRecordsByCustomerId(Long customerId) {
        Page<ContractRecordsResponse> contractRecordsResponsePage = PageFactory.defaultPage();
        return contractRecordsResponsePage;
    }

    @Override
    public Page<CertificationResponse> certificationByCustomerId(Long customerId) {
        return null;
    }

    @Override
    public void customerExport(CustomerListRequest request, HttpServletResponse response) {
        try {
            List<CustomerInfoResponse> customerInfoList;
            if (!CollectionUtils.isEmpty(request.getIds())) {
                customerInfoList = customerInfoResponseMapper.selectBatchIds(request.getIds());
            } else {
                QueryWrapper<CustomerInfoResponse> wrapper = listParamWrapper(request);
                customerInfoList = customerInfoResponseMapper.selectList(wrapper);
            }
            for (CustomerInfoResponse customerInfo : customerInfoList) {
                DictCodeUtils.convertDictCodeToName(customerInfo);
            }
            iBaseExportService.exportExcel(response, CustomerInfoResponse.class, customerInfoList, ExportEnum.CUSTOMER_EXPORT.getSheetName());
        } catch (Exception e) {
            log.error("客户导出出现异常，异常信息为{}", e);
        }
    }

    private QueryWrapper<CustomerInfoResponse> listParamWrapper(CustomerListRequest request) {
        QueryWrapper<CustomerInfoResponse> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(request.getCustomerNo()), "customer_no", request.getCustomerNo());
        queryWrapper.like(StringUtils.isNotBlank(request.getCustomerName()), "customer_name", request.getCustomerName());
        queryWrapper.like(StringUtils.isNotBlank(request.getBusinessSize()), "business_size", request.getBusinessSize());
        queryWrapper.like(StringUtils.isNotBlank(request.getGrade()), "grade", request.getGrade());
        queryWrapper.eq("is_del", 0);
        return queryWrapper;
    }

    private void initCustomerInfo(CustomerInfo customerInfo) {
        Long maxNo = this.baseMapper.selectMaxCustomerNo();
        String customerNo = NumberGeneratorUtil.getContactNo(PrefixCodeEnum.CUSTOMER_PREFIX, maxNo);
        AuthUser authUser = ShiroKit.getUser();
        customerInfo.setCreateUser(authUser.getId());
        customerInfo.setUpdateUser(authUser.getId());
        customerInfo.setCustomerNo(customerNo);
    }

    private List<CustomerUserInfo> customerUserDetail(Long id) {
        QueryWrapper<CustomerUserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("customer_id", id);
        return customerUserMapper.selectList(queryWrapper);
    }

    private void userInfoListDeletor(Long customerId) {
        QueryWrapper<CustomerUserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("customer_id", customerId);
        customerUserMapper.delete(queryWrapper);
    }

    private Boolean userInfoListCreator(List<CustomerUserInfo> userInfoList, Long id) {
        Long maxUserNo = customerUserMapper.selectMaxUserNo();
        boolean userUpdateFlag = true;
        for (CustomerUserInfo customerUserInfo : userInfoList) {
            customerUserInfo.setCustomerId(id);
            String customerNo = NumberGeneratorUtil.getContactNo(CUSTOMER_USER_PREFIX, maxUserNo++);
            customerUserInfo.setUserNo(customerNo);
            int userAddNum = customerUserMapper.insert(customerUserInfo);
            if (userAddNum <= 0) {
                userUpdateFlag = false;
            }
        }
        return userUpdateFlag;
    }

}
