package com.qmth.sop.business.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qmth.boot.core.exception.StatusException;
import com.qmth.sop.business.bean.dto.DataPermissionDto;
import com.qmth.sop.business.bean.params.CustomReceiverParam;
import com.qmth.sop.business.bean.result.SysCustomReceiverResult;
import com.qmth.sop.business.bean.result.TBDeviceDeliveryResult;
import com.qmth.sop.business.entity.SysCustomReceiver;
import com.qmth.sop.business.entity.SysUser;
import com.qmth.sop.business.mapper.SysCustomReceiverMapper;
import com.qmth.sop.business.service.SysCustomReceiverService;
import com.qmth.sop.business.service.SysUserService;
import com.qmth.sop.common.contant.SystemConstant;
import com.qmth.sop.common.enums.ExceptionResultEnum;
import com.qmth.sop.common.enums.ProductTypeEnum;
import com.qmth.sop.common.util.FileUtil;
import com.qmth.sop.common.util.ServletUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

/**
 * @Description
 * @Author haoguanghui
 * @date 2024/09/04
 */
@Service
public class SysCustomReceiverServiceImpl extends ServiceImpl<SysCustomReceiverMapper, SysCustomReceiver> implements SysCustomReceiverService {

    @Resource
    private SysUserService sysUserService;

    @Override
    public List<SysCustomReceiver> listCustom(ProductTypeEnum type) {
        return baseMapper.listCustom(type);
    }

    @Override
    public IPage<SysCustomReceiverResult> pageReceiver(Page<SysCustomReceiverResult> page, ProductTypeEnum type, String name) {
        SysUser requestUser = (SysUser) ServletUtil.getRequestUser();
        DataPermissionDto dpr = sysUserService.buildUserDataPermission(requestUser.getId());
        return baseMapper.page(new Page<>(page.getCurrent(), page.getSize()), type, name, dpr);
    }

    @Override
    public Long saveCustomReceiver(CustomReceiverParam param, SysUser requestUser) {
        Long id = param.getId();
        SysCustomReceiver sysCustomReceiver = new SysCustomReceiver();
        BeanUtils.copyProperties(param, sysCustomReceiver);

        //新增
        if (id == null) {
            LambdaQueryWrapper<SysCustomReceiver> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysCustomReceiver::getType, param.getType());
            queryWrapper.eq(SysCustomReceiver::getName, param.getName());
            queryWrapper.eq(SysCustomReceiver::getUnit, param.getUnit());
            queryWrapper.eq(SysCustomReceiver::getConsignee, param.getConsignee());
            List<SysCustomReceiver> customReceiverList = this.list(queryWrapper);
            if (!customReceiverList.isEmpty()) {
                throw ExceptionResultEnum.ERROR.exception(String.format("该客户下已经存在收件人:%s，请不要重复新增", param.getConsignee()));
            }

            sysCustomReceiver.insertInfo(requestUser.getId());
            this.save(sysCustomReceiver);
            id = sysCustomReceiver.getId();
        } else { //编辑
            SysCustomReceiver existCustomReceiver = this.getById(id);
            if (Objects.isNull(existCustomReceiver)) {
                throw ExceptionResultEnum.ERROR.exception("操作的数据记录不存在");
            }

            sysCustomReceiver.updateInfo(requestUser.getId());
            this.updateById(sysCustomReceiver);
        }
        return id;
    }

    @Override
    public void export(ProductTypeEnum type, String name) {
        SysUser requestUser = (SysUser) ServletUtil.getRequestUser();
        DataPermissionDto dpr = sysUserService.buildUserDataPermission(requestUser.getId());
        List<SysCustomReceiverResult> receiverResultList = baseMapper.listCustomReceiver(type, name, dpr);
        receiverResultList.forEach(item -> {
            item.setTypeName(item.getType().getTitle());
        });
        File fileTemp = null;
        try {
            fileTemp = SystemConstant.getFileTempVar(SystemConstant.XLSX_PREFIX);
            EasyExcel.write(fileTemp, SysCustomReceiverResult.class).sheet("客户收件信息").doWrite(receiverResultList);
            HttpServletResponse response = ServletUtil.getResponse();
            FileUtil.outputFile(response, fileTemp, "客户收件信息.xlsx");
        } catch (IOException e) {
            throw ExceptionResultEnum.ERROR.exception(e.getMessage());
        } finally {
            if (Objects.nonNull(fileTemp)) {
                fileTemp.delete();
            }
        }
    }
}
