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


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.casic.missiles.core.application.service.AbstractDictService;
import com.casic.missiles.core.base.service.IBaseExportService;
import com.casic.missiles.dto.IdDTO;
import com.casic.missiles.dto.ReturnDTO;
import com.casic.missiles.dto.ReturnUtil;
import com.casic.missiles.dto.meter.MeterPriceRequest;
import com.casic.missiles.enums.BusinessExceptionEnum;
import com.casic.missiles.enums.ExportEnum;
import com.casic.missiles.enums.PrefixCodeEnum;
import com.casic.missiles.enums.meter.MeterDictEnum;
import com.casic.missiles.exception.BusinessException;
import com.casic.missiles.mapper.meter.MeterPriceCategoryMapper;
import com.casic.missiles.mapper.meter.MeterPriceItemMapper;
import com.casic.missiles.mapper.meter.MeterPriceMapper;
import com.casic.missiles.model.meter.MeterPrice;
import com.casic.missiles.model.meter.MeterPriceCategory;
import com.casic.missiles.model.meter.MeterPriceItem;
import com.casic.missiles.service.meter.MeterPriceService;
import com.casic.missiles.utils.DictCodeUtils;
import com.casic.missiles.utils.NumberGeneratorUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

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

@Service("MeterPriceService")
public class MeterPriceServiceImpl extends ServiceImpl<MeterPriceMapper, MeterPrice> implements MeterPriceService {

    @Resource
    private MeterPriceMapper meterPriceMapper;

    @Resource
    private MeterPriceCategoryMapper meterPriceCategoryMapper;

    @Resource
    private MeterPriceItemMapper meterPriceItemMapper;

    @Resource
    private AbstractDictService dictService;

    @Resource
    private IBaseExportService iBaseExportService;

    @Override
    public Page<MeterPrice> queryPriceList(Page<MeterPrice> page, MeterPriceRequest meterPriceRequest) {
        Page<MeterPrice> meterPricePage = meterPriceMapper.queryPriceList(page, meterPriceRequest);
        meterPricePage.setRecords(supplementList(meterPricePage.getRecords()));
        return meterPricePage;
    }

    @Override
    public ReturnDTO deletePrice(IdDTO idDto) {
        if(meterPriceMapper.deleteById(idDto.getId())>0){
            return ReturnUtil.success();
        }
        throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
    }

    @Override
    @Transactional
    public ReturnDTO addMeterPrice(MeterPrice meterPrice) {
        MeterPriceCategory priceCategory = new MeterPriceCategory(null,meterPrice.getCheckType(),meterPrice.getCategoryName());
        int categoryFlag = meterPriceCategoryMapper.insert(priceCategory);
        MeterPriceItem item = new MeterPriceItem(null,priceCategory.getId(),meterPrice.getItemName());
        if(categoryFlag>0 && meterPriceItemMapper.insert(item)>0){
            Long maxNo = meterPriceMapper.getMaxNo();
            String priceNo = NumberGeneratorUtil.getContactNo(PrefixCodeEnum.PRICE_PREFIX, maxNo);
            meterPrice.setPriceNo(priceNo);
            meterPrice.setPriceType(priceCategory.getId().toString());
            meterPrice.setPriceItem(item.getId().toString());
            if(meterPriceMapper.insert(meterPrice)>0){
                return ReturnUtil.success();
            }
            throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
        }
        throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
    }

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

    @Override
    public MeterPrice queryPriceInfo(IdDTO idDto) {
        MeterPrice meterPrice = meterPriceMapper.queryPriceInfo(idDto.getId());
        meterPrice.setCheckTypeName(dictService.getDictNameByCode(MeterDictEnum.CHECK_TYPE,meterPrice.getCheckType()));
        meterPrice.setDirectorDiscountPermissionName(dictService.getDictNameByCode(MeterDictEnum.DIRECTOR_DISCOUNT_PERMISSION,meterPrice.getDirectorDiscountPermission()));
        meterPrice.setOperatorDiscountPermissionName(dictService.getDictNameByCode(MeterDictEnum.OPERATOR_DISCOUNT_PERMISSION,meterPrice.getOperatorDiscountPermission()));
        return meterPrice;
    }

    @Override
    @Transactional
    public ReturnDTO updatePriceInfo(MeterPrice meterPrice) {
        int updateFlag = meterPriceMapper.updateById(meterPrice);
        MeterPriceCategory priceCategory = new MeterPriceCategory(Long.parseLong(meterPrice.getPriceType()),meterPrice.getCheckType(),meterPrice.getCategoryName());
        int categoryFlag = meterPriceCategoryMapper.updateById(priceCategory);
        MeterPriceItem item = new MeterPriceItem(Long.parseLong(meterPrice.getPriceItem()),priceCategory.getId(),meterPrice.getItemName());
        int itemFlag = meterPriceItemMapper.updateById(item);
        if(categoryFlag>0 && itemFlag>0 && updateFlag>0){
            return ReturnUtil.success();
        }
        throw new BusinessException(BusinessExceptionEnum.HANDLE_FAILED);
    }

    @Override
    public void exportPriceList(MeterPriceRequest meterPriceRequest, HttpServletResponse response) {
        try {
            List<MeterPrice> meterPrices;
            if(!CollectionUtils.isEmpty(meterPriceRequest.getIds())){
                MeterPriceRequest request = new MeterPriceRequest();
                request.setIds(meterPriceRequest.getIds());
                meterPrices = supplementList(meterPriceMapper.queryPriceList(request));
            }else{
                meterPrices = supplementList(meterPriceMapper.queryPriceList(meterPriceRequest));
            }
            iBaseExportService.exportExcel(response,MeterPrice.class,meterPrices, ExportEnum.METER_PRICE.getSheetName());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private List<MeterPrice> supplementList(List<MeterPrice> meterPriceList){
        meterPriceList.forEach(bean->{
            bean.setCheckTypeName(dictService.getDictNameByCode(MeterDictEnum.CHECK_TYPE,bean.getCheckType()));
            bean.setDirectorDiscountPermissionName(dictService.getDictNameByCode(MeterDictEnum.DIRECTOR_DISCOUNT_PERMISSION,bean.getDirectorDiscountPermission()));
            bean.setOperatorDiscountPermissionName(dictService.getDictNameByCode(MeterDictEnum.OPERATOR_DISCOUNT_PERMISSION,bean.getOperatorDiscountPermission()));
        });
        return meterPriceList;
    }

}
