package com.inkasso.factoring.salesManagement.service.impl;

import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.inkasso.adapter.exception.BusinessException;
import com.inkasso.adapter.util.CodeUtil;
import com.inkasso.factoring.common.entity.ResponseJson;
import com.inkasso.factoring.file.entity.FileStorageDO;
import com.inkasso.factoring.file.enums.FileTypeEnum;
import com.inkasso.factoring.file.service.FileService;
import com.inkasso.factoring.salesManagement.dao.CSalesContractBasicInfoMapper;
import com.inkasso.factoring.salesManagement.entity.CSalesContractBasicInfo;
import com.inkasso.factoring.salesManagement.entity.CSalesContractGoodsInfo;
import com.inkasso.factoring.salesManagement.entity.CSalesContractPersonInfo;
import com.inkasso.factoring.salesManagement.entity.vo.SalesContractBasicVo;
import com.inkasso.factoring.salesManagement.service.ICSalesContractBasicInfoService;
import com.inkasso.factoring.salesManagement.service.ICSalesContractGoodsInfoService;
import com.inkasso.factoring.salesManagement.service.ICSalesContractManagementService;
import com.inkasso.factoring.salesManagement.service.ICSalesContractPersonInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

/**
 * <p>
 * 销售合同-基本信息表 服务实现类
 * </p>
 *
 * @author yafan
 * @since 2023-11-28
 */
@Service
public class CSalesContractBasicInfoServiceImpl extends ServiceImpl<CSalesContractBasicInfoMapper, CSalesContractBasicInfo> implements ICSalesContractBasicInfoService {

    @Autowired
    private ICSalesContractPersonInfoService personInfoService;
    @Autowired
    private ICSalesContractGoodsInfoService goodsInfoService;
    @Autowired
    private FileService fileService;
    @Autowired
    private RestTemplate restTemplate;
    @Value("${trade.salesContractEnterUrl}")
    private String salesContractEnterUrl;
    @Autowired
    private ICSalesContractManagementService salesContractManagementService;

    @Override
    public CSalesContractBasicInfo getDetail(Long id) {
        CSalesContractBasicInfo contractBasicInfo = getOne(new QueryWrapper<CSalesContractBasicInfo>()
                .eq("c_sales_contract_management_id", id));
        if (contractBasicInfo == null) {
            contractBasicInfo = new CSalesContractBasicInfo();
        } else {
            //人员信息
            List<CSalesContractPersonInfo> personInfoList = personInfoService.list(new QueryWrapper<CSalesContractPersonInfo>()
                    .eq("c_sales_contract_basic_info_id", contractBasicInfo.getId()));
            contractBasicInfo.setPersonInfoList(personInfoList);

            //货物信息
            List<CSalesContractGoodsInfo> goodsInfoList = goodsInfoService.list(new QueryWrapper<CSalesContractGoodsInfo>()
                    .eq("c_sales_contract_basic_info_id", contractBasicInfo.getId()));
            contractBasicInfo.setGoodsInfoList(goodsInfoList);

            //合同文件
            List<FileStorageDO> fileStorageDOS = fileService.findByBusinessId(contractBasicInfo.getId(), FileTypeEnum.SALES_CONTRACT_FILE.getCode());
            contractBasicInfo.setFileStorages(fileStorageDOS);
        }
        SalesContractBasicVo contractBasicVo = salesContractManagementService.getView(id);
        contractBasicInfo.setContractBasicVo(contractBasicVo);


        return contractBasicInfo;
    }

    @Override
    public void doAdd(CSalesContractBasicInfo salesContractBasicInfo) {
        try {
            restTemplate.postForObject(salesContractEnterUrl, salesContractBasicInfo, String.class);
        } catch (Exception e) {
            String result = e.getMessage().substring(7, e.getMessage().length() - 1);
            JSONObject jsonObject = new JSONObject(result);
            throw new BusinessException(CodeUtil.FAIL, jsonObject.get("msg").toString());
        }
    }

    @Override
    public List<CSalesContractGoodsInfo> importGoodsInfo(MultipartFile file) {
        return goodsInfoService.importGoodsInfo(file);
    }

    @Override
    public void downloadTemplateFile(HttpServletResponse response) {
        OutputStream out = null;
        BufferedInputStream inputStream = null;
        try {
            ClassPathResource classPathResource = new ClassPathResource("templateFiles/销售合同货物信息.xlsx");
            response.setHeader("Content-Type", "application/vnd.ms-exce");
            response.setHeader("Content-Length", String.valueOf(classPathResource.contentLength()));
            response.setHeader("Content-disposition", "attachment;filename=" + java.net.URLEncoder.encode(classPathResource.getFilename(), "UTF-8"));
            out = response.getOutputStream();
            inputStream = new BufferedInputStream(classPathResource.getInputStream());
            byte[] buffer = new byte[1024];
            while ((inputStream.read(buffer)) > 0) {
                out.write(buffer);
                out.flush();
            }

        } catch (Exception e) {
            throw new BusinessException(CodeUtil.FAIL, "下载模板失败!");
        } finally {
            try {
                inputStream.close();
                out.close();
            } catch (IOException e) {
                log.error("关闭文件流失败!");
            }
        }
    }
}
