package com.zksy.system.basicData.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zksy.common.core.domain.AjaxResult;
import com.zksy.common.utils.DateUtils;
import com.zksy.system.basicData.domain.CrmComplain;
import com.zksy.system.basicData.domain.CrmFile;
import com.zksy.system.basicData.domain.dto.CrmComplainDTO;
import com.zksy.system.basicData.mapper.CrmComplainMapper;
import com.zksy.system.basicData.service.CaptchaService;
import com.zksy.system.basicData.service.CrmComplainService;
import com.zksy.system.basicData.service.CrmFileService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.zksy.system.utils.PdfUtil.fillPdf;

/**
 * 投诉Service业务层处理
 *
 * @author sy
 * @date 2024-05-10
 */
@Service
@Slf4j
public class CrmComplainServiceImpl extends ServiceImpl<CrmComplainMapper, CrmComplain> implements CrmComplainService {

    @Resource
    private CrmComplainMapper mapper;

    @Autowired
    private CrmFileService crmFileService;

    @Autowired
    private CaptchaService captchaService;

    @Override
    public AjaxResult saveCrmComplain(CrmComplainDTO dto) {
        String msg = captchaService.checkImageCode(dto.getImageKey(), dto.getImageCode());
        if (com.zksy.common.utils.StringUtils.isNotBlank(msg)) {
            return AjaxResult.error(999,msg);
        }
        CrmComplain entity = new CrmComplain();
        BeanUtils.copyProperties(dto,entity);
        entity.setCreateBy(dto.getName());
        entity.setCreateTime(new Date());
        int number = mapper.insert(entity);
        if(number > 0 ){
            if(dto.getFiles() != null) {
                for (CrmFile file : dto.getFiles()) {
                    //添加文件
                    file.setFid(entity.getId());
                    file.setUpdateBy(entity.getName());
                    file.setUpdateTime(new Date());
                    crmFileService.updateById(file);
                }
            }
        }else{
            return AjaxResult.success("投诉失败");
        }
        return AjaxResult.success("投诉成功");
    }

    @Override
    public AjaxResult updateCrmComplain(CrmComplain crmComplain) {
        CrmComplain info = mapper.selectById(crmComplain.getId());
        log.info("数据长度之前:{}",crmComplain.getFiles().size());
        //赋值
        BeanUtils.copyProperties(crmComplain, info);
        info.setUpdateBy(info.getName());
        info.setFiles(null);
        info.setUpdateTime(new Date());
        int number = mapper.updateById(info);
        if(number > 0 ){
            if(crmComplain.getFiles() != null) {
                for (CrmFile file : crmComplain.getFiles()) {
                    //添加文件
                    file.setFid(info.getId());
                    file.setUpdateBy(info.getName());
                    file.setUpdateTime(new Date());
                    crmFileService.updateById(file);
                }
            }
        }else{
            return AjaxResult.success("投诉失败");
        }
        return AjaxResult.success("投诉成功");
    }

    @Override
    public AjaxResult getByComplainId(String id) {
        CrmComplain crmComplain = baseMapper.selectById(id);
        List<CrmFile> crmFile = crmFileService.selectByFid(crmComplain.getId());
        if(crmFile != null) {
            crmComplain.setFiles(crmFile);
        }
        return AjaxResult.success("查询成功",crmComplain);
    }

    @Override
    public AjaxResult removeCrmComplain(List<String> ids) {
        //查询fids所有文件
        List<CrmFile> crmFileList = crmFileService.selectByFids(ids);
        for(CrmFile crmFile : crmFileList){
            //根据id删除文件
            crmFileService.removeById(crmFile.getId());
        }
        mapper.deleteBatchIds(ids);
        return AjaxResult.success("删除文件成功");
    }

    @Override
    public void generateVoucher(HttpServletResponse response, String name, Long id) throws Exception {
        InputStream inputStream = new ClassPathResource("/template/投诉模板.pdf").getInputStream();
        Map<String, String> data = new HashMap<>();
        CrmComplain owLeavingMessage = mapper.selectById(id);

        data.put("type", name);
        data.put("title",owLeavingMessage.getTitle());
        data.put("createTime", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, owLeavingMessage.getCreateTime()));
        data.put("name", owLeavingMessage.getName());
        data.put("phone", owLeavingMessage.getPhone());
        data.put("card", owLeavingMessage.getCard());
        if(StringUtils.isNotEmpty(owLeavingMessage.getEnterpriseName())) {
            data.put("enterpriseName", owLeavingMessage.getEnterpriseName());
        }
        if(StringUtils.isNotEmpty(owLeavingMessage.getUnifiedSocialCreditCode())) {
            data.put("unifiedSocialCreditCode", owLeavingMessage.getUnifiedSocialCreditCode());
        }
        data.put("content",owLeavingMessage.getContent());
        data.put("remark", owLeavingMessage.getRemark());

        byte[] filledPdfBytes = fillPdf(inputStream, null, data);
        // 设置HTTP响应头
        response.setContentType("application/pdf");
        response.setHeader("Content-Disposition", "attachment; filename=tousu.pdf");

        // 将字节数组写入到HTTP响应输出流中
        OutputStream outStream = response.getOutputStream();
        outStream.write(filledPdfBytes);
        outStream.flush();
        outStream.close();
    }
}
