package com.fdkankan.manage.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fdkankan.common.annotation.Dict;
import com.fdkankan.common.constant.ErrorCode;
import com.fdkankan.common.constant.InvoiceType;
import com.fdkankan.common.exception.BusinessException;
import com.fdkankan.common.response.Result;
import com.fdkankan.common.response.ResultData;
import com.fdkankan.common.util.DateExtUtil;
import com.fdkankan.fyun.oss.UploadToOssUtil;
import com.fdkankan.manage.entity.Invoice;
import com.fdkankan.manage.entity.InvoiceRegister;
import com.fdkankan.manage.mapper.IInvoiceMapper;
import com.fdkankan.manage.service.IInvoiceRegisterService;
import com.fdkankan.manage.service.IInvoiceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fdkankan.manage.service.IOrderService;
import com.fdkankan.manage.vo.InvoicePageParamVO;
import com.fdkankan.manage.vo.InvoiceRegisterDetailVO;
import com.fdkankan.manage.vo.InvoiceVO;
import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 * 发票表 服务实现类
 * </p>
 *
 * @author 
 * @since 2022-05-31
 */
@RefreshScope
@Service
public class InvoiceServiceImpl extends ServiceImpl<IInvoiceMapper, Invoice> implements IInvoiceService {

    @Value("${oss.dir.invoice}")
    private String invoiceOssDir;
    @Value("${invoice.prefix}")
    private String invoicePrefix;
    @Value("${oss.prefix.url}")
    private String ossPrefixUrl;



    @Autowired
    private IInvoiceRegisterService invoiceRegisterService;
    @Autowired
    private UploadToOssUtil uploadToOssUtil;

    @Dict
    @Override
    public Page<InvoiceVO> pageInvoice(InvoicePageParamVO param) {
        return baseMapper.pageInvoice(new Page(param.getPageNum(), param.getPageSize()), param);
    }

    @Override
    public ResultData invoiceRegister(
        Long userId, Long id, String invoiceNum,
        String shipNum, MultipartFile file) throws IOException {
        Invoice invoice = this.getById(id);
        if(Objects.isNull(invoice)){
            throw new BusinessException(ErrorCode.FAILURE_CODE_9001);
        }
        Integer type = invoice.getType();
        if(InvoiceType.NO_NEAD.code().equals(type)){
            throw new BusinessException(ErrorCode.FAILURE_CODE_9002);
        }

        InvoiceRegister invoiceRegister = invoiceRegisterService.getByInvoiceId(id);
        if(Objects.isNull(invoiceRegister)){
            invoiceRegister = new InvoiceRegister();
            invoiceRegister.setInvoiceId(invoice.getId());
            invoiceRegister.setInvoiceNum(invoiceNum);
            invoiceRegister.setCreaterId(userId);
        }else{
            invoiceRegister.setUpdaterId(userId);
            invoiceRegister.setUpdateTime(new Date());
        }
        //普通发票
        if(InvoiceType.ORDINARY.code().equals(type)){
            if(Objects.isNull(file) || file.isEmpty()){
                throw new BusinessException(ErrorCode.FAILURE_CODE_5048);
            }
            String fileName = invoicePrefix + invoice.getId() + ".jpg";
            String ossFilePath = String.format(invoiceOssDir) + "/" + fileName;
            uploadToOssUtil.upload(file.getBytes(), ossFilePath);
            invoiceRegister.setInvoiceUrl(ossPrefixUrl + ossFilePath);
        }else{//专用发票
            if(StrUtil.isEmpty(shipNum)){
                throw new BusinessException(ErrorCode.FAILURE_CODE_9003);
            }
            invoiceRegister.setShipNum(shipNum);
        }
        invoiceRegisterService.saveOrUpdate(invoiceRegister);

        return ResultData.ok();
    }

    @Override
    public ResultData getInvoiceRegisterDetail(Long id) {

        Invoice invoice = this.getById(id);
        if(Objects.isNull(invoice)){
            throw new BusinessException(ErrorCode.FAILURE_CODE_9001);
        }
        InvoiceRegister invoiceRegister = invoiceRegisterService.getByInvoiceId(id);
        if(Objects.isNull(invoice)){
            throw new BusinessException(ErrorCode.FAILURE_CODE_9004);
        }
        return ResultData.ok(InvoiceRegisterDetailVO.builder()
            .type(invoice.getType())
            .email(invoice.getEmailAddress())
            .invoiceNum(invoiceRegister.getInvoiceNum())
            .invoiceUrl(invoiceRegister.getInvoiceUrl())
            .shipNum(invoiceRegister.getShipNum())
            .build());
    }

}
