package cn.wise.sc.cement.business.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.wise.sc.cement.business.entity.Sample;
import cn.wise.sc.cement.business.mapper.SampleMapper;
import cn.wise.sc.cement.business.model.BaseResponse;
import cn.wise.sc.cement.business.model.PageQuery;
import cn.wise.sc.cement.business.model.SampleSaveDto;
import cn.wise.sc.cement.business.model.query.SampleManageQuery;
import cn.wise.sc.cement.business.model.vo.SampleVo;
import cn.wise.sc.cement.business.service.ISampleService;
import cn.wise.sc.cement.business.service.ISysUserService;
import cn.wise.sc.cement.business.util.ExcelUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ztw
 * @since 2020-08-24
 */
@Service
public class SampleServiceImpl extends ServiceImpl<SampleMapper, Sample> implements ISampleService {

    @Resource
    private SampleMapper sampleMapper;
    private final ISysUserService userService;

    public SampleServiceImpl(ISysUserService userService) {
        this.userService = userService;
    }

    /**
     * 分页列表
     *
     * @param pageQuery
     * @param sampleName
     * @param cementCode
     * @return
     */
    @Override
    public BaseResponse<IPage<SampleVo>> getPage(PageQuery pageQuery, String sampleName, String cementCode) {
        Map<String, Object> params = new HashMap<>();
        params.put("sampleName", sampleName);
        params.put("cementCode", cementCode);
        Page<SampleVo> page = new Page<>(pageQuery.getPageNo(), pageQuery.getPageSize());
        IPage<SampleVo> pages = sampleMapper.getPage(page, params);
        return BaseResponse.okData(pages);
    }

    /**
     * 样品管理详情
     *
     * @param id
     * @return
     */
    @Override
    public BaseResponse<SampleVo> getDetail(Integer id) {
        SampleVo sampleVo = sampleMapper.getDetail(id);
        if (sampleVo == null) {
            return BaseResponse.errorMsg("信息错误!");
        }
        return BaseResponse.okData(sampleVo);
    }

    /**
     * 样品登记
     *
     * @param query
     * @return
     */
    @Transactional
    @Override
    public BaseResponse<String> register(SampleManageQuery query) {
        if (query.getId() == null) {
            return BaseResponse.errorMsg("参数错误!");
        }
        Sample sample = sampleMapper.selectById(query.getId());
        if (sample == null) {
            return BaseResponse.errorMsg("信息错误");
        }
        sample.setOperatorId(userService.getLoginUser().getId())
                .setRegisterTime(LocalDateTime.now())
                .setHandleDate(query.getHandleDate())
                .setLittlePosition(query.getLittlePosition())
                .setOriginalPosition(query.getOriginalPosition())
                .setRemark(query.getRemark());
        sampleMapper.updateById(sample);
        return BaseResponse.okData("样品登记成功");
    }

    /**
     * 样品销毁
     *
     * @param id
     * @return
     */
    @Transactional
    @Override
    public BaseResponse<String> destruction(Integer id) {
        if (id == null) {
            return BaseResponse.errorMsg("参数错误!");
        }
        Sample sample = sampleMapper.selectById(id);
        if (sample == null) {
            return BaseResponse.errorMsg("信息错误");
        }
        sample.setStatus(2)
                .setDestructionTime(LocalDateTime.now());
        sampleMapper.updateById(sample);
        return BaseResponse.okData("样品已销毁");
    }

    /**
     * 样品列表导出
     *
     * @param sampleName
     * @param cementCode
     * @param fileName
     * @param response
     */
    public void export(String sampleName, String cementCode,
                       String fileName, HttpServletResponse response) {
        Map<String, Object> params = new HashMap<>();
        params.put("sampleName", sampleName);
        params.put("cementCode", cementCode);
        List<Map<String, Object>> list = sampleMapper.exportList(params);

        if (!CollectionUtils.isEmpty(list)) {
            Map<String, Object> map = list.get(0);
            String[] headers = new String[map.size()];
            headers[0] = "序号";
            headers[1] = "样品名称";
            headers[2] = "样品本所编号";
            headers[3] = "所属项目";
            headers[4] = "小样信息";
            headers[5] = "原样存储";
            headers[6] = "样品重量（kg）";
            headers[7] = "是否为平行样";
            headers[8] = "状态";
            List<Object[]> datas = new ArrayList<>(headers.length);
            for (Map<String, Object> m : list) {
                Object[] objects = new Object[headers.length];
                for (int j = 0; j < headers.length; j++) {
                    String obj = m.get(headers[j]).toString();
                    //如果序号带小数点 去除.0,保留整数
                    if (j == 0) {
                        obj = obj.split("\\.")[0];
                    }
                    objects[j] = obj;
                }
                datas.add(objects);
            }
            ExcelUtil.excelExport(
                    fileName == null || fileName.trim().length() <= 0 ? "样品列表" : fileName, headers,
                    datas, response);
        }
    }

    @Override
    public BaseResponse<String> bindSavePosition(SampleManageQuery query) {

        if (query.getId() == null) {
            return BaseResponse.errorMsg("");
        }

        Sample sample = this.getById(query.getId());
        sample.setStatus(1);
        sample.setDestructionTime(LocalDateTime.now());
        sample.setHandleDate(LocalDate.now());

        sample.setLittlePosition(query.getLittlePosition());
        sample.setOriginalPosition(query.getOriginalPosition());

        boolean b = this.updateById(sample);
        if (b) {
            return BaseResponse.okData("更新成功!");
        } else {
            return BaseResponse.errorMsg("更新失败,可以重新尝试!");
        }
    }

    @Override
    public BaseResponse<Boolean> ampleReview(Integer id) {

        if (id == null) {
            log.debug("样品复查失败!没有指定样品id!");
            return BaseResponse.errorMsg("请指定样品id");
        }
        Sample sample = this.getById(id);
        sample.setStatus(3);
        boolean b = this.updateById(sample);
        if (b) {
            return BaseResponse.okData(true);
        }
        return BaseResponse.okData(false);
    }

    @Override
    public void upload(HttpServletResponse response) {

        List<SampleSaveDto> saveDtos = sampleMapper.getSampleSaveList();
        List<Map<String, Object>> list = new ArrayList<>();
        saveDtos.forEach(arg -> {
            Map<String, Object> map = new HashMap<>();
            map.put("项目名称", arg.getId());
            map.put("项目编号", arg.getCementCode());
            map.put("样品名称", arg.getName());
            map.put("样品状态", arg.getSampleForm());
            map.put("来样编号", arg.getSampleCode());
            map.put("本所编号", arg.getCementCode());
            map.put("小样保存位置", arg.getLittlePosition());
            map.put("保存日期", arg.getRegisterTime());
            map.put("销毁日期", arg.getDestructionTime());
            map.put("批准人", arg.getUserName());
            map.put("备注", arg.getRemark());
            list.add(map);
        });
        if (!CollectionUtils.isEmpty(list)) {
            Map<String, Object> map = list.get(0);
            String[] headers = new String[map.size()];
            headers[0] = "项目名称";
            headers[1] = "项目编号";
            headers[2] = "样品名称";
            headers[3] = "样品状态";
            headers[4] = "来样编号";
            headers[5] = "本所编号";
            headers[6] = "小样保存位置";
            headers[7] = "保存日期";
            headers[8] = "销毁日期";
            headers[9] = "批准人";
            headers[10] = "备注";
            List<Object[]> datas = new ArrayList<>(headers.length);
            for (Map<String, Object> m : list) {
                Object[] objects = new Object[headers.length];
                for (int j = 0; j < headers.length; j++) {
                    String obj;
                    if (j < 7) {
                        obj  = m.get(headers[j]) == null ? "—" : m.get(headers[j]).toString();
                    }else {
                        obj =  m.get(headers[j]) == null ? "" : m.get(headers[j]).toString();
                    }
                    //如果序号带小数点 去除.0,保留整数
                    if (j == 0) {
                        obj = obj.split("\\.")[0];
                    }
                    objects[j] = obj;
                }
                datas.add(objects);
            }
            ExcelUtil.excelExportNew("样品处置列表", headers,
                    datas, response);
        }
    }

}
