package net.vtstar.zhongtong.avi.laboratory.service;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import net.vtstar.user.mybatis.provider.Operation;
import net.vtstar.user.mybatis.provider.WhereFilter;
import net.vtstar.user.search.service.SearchService;
import net.vtstar.user.util.UserUtil;
import net.vtstar.utils.DateUtils;
import net.vtstar.zhongtong.avi.laboratory.domain.DailyCheckModel;
import net.vtstar.zhongtong.avi.laboratory.domain.DailyCheckRecord;
import net.vtstar.zhongtong.avi.laboratory.domain.DailyItemModel;
import net.vtstar.zhongtong.avi.laboratory.domain.DailyItemRecord;
import net.vtstar.zhongtong.avi.laboratory.domain.vo.CheckRecordVo;
import net.vtstar.zhongtong.avi.laboratory.mapper.DailyCheckModelMapper;
import net.vtstar.zhongtong.avi.laboratory.mapper.DailyCheckRecordMapper;
import net.vtstar.zhongtong.avi.laboratory.mapper.DailyItemModelMapper;
import net.vtstar.zhongtong.avi.laboratory.mapper.DailyItemRecordMapper;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ResourceUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.*;

/**
 * @Author: xiadongwei
 * @Date: 2019/10/20 15:52
 */
@Slf4j
@Service
public class DailyCheckService {

    @Autowired
    private SearchService searchService;

    @Autowired
    private DailyCheckModelMapper checkModelMapper;

    @Autowired
    private DailyItemModelMapper itemModelMapper;

    @Autowired
    private DailyCheckRecordMapper checkRecordMapper;

    @Autowired
    private DailyItemRecordMapper itemRecordMapper;

    /**
     * 根据类型查询点检模板, 关联查询点检项模板;
     * 1.根据type查询点检模板, 若点检模板不存在, 则创建该类型的点检模板;
     * 2.根据点检模板ID, 查询对应点检项模板;
     */
    public Map<String, Object> getCheckByType(String type) {
        Map<String, Object> map = new HashMap<>();
        List<DailyCheckModel> list = checkModelMapper.findList(new WhereFilter() {{
            addFilter("type", Operation.EQUAL, type);
        }}, DailyCheckModel.class);
        if (CollectionUtils.isEmpty(list)) {
            DailyCheckModel model = new DailyCheckModel();
            model.setType(type);
            model.setOrderNum(1);
            model.setRev("A/O");
            model.setSheetNo("ZT/MR-PD66-Q000-23");
            model.setNo("Q000-100993-");
            model.setCreateTime(new Date());
            checkModelMapper.insert(model);
            map.put("checkModel", model);
            map.put("checkItem", new ArrayList<>());
            return map;
        } else {
            DailyCheckModel model = list.get(0);
            map.put("checkModel", model);
            List<DailyItemModel> itemModelList = itemModelMapper.findList(new WhereFilter() {{
                addFilter("check_model_id", Operation.EQUAL, model.getId());
            }}, DailyItemModel.class);
            map.put("checkItem", itemModelList);
            return map;
        }
    }

    /**
     * 新增/编辑检测项模板
     *
     * @param itemModel 检测项模板
     */
    public void saveCheckItemModel(DailyItemModel itemModel) {
        Long itemModelId = itemModel.getId();
        if (null == itemModelId) {
            itemModel.setCreateBy(UserUtil.getUsername());
            itemModel.setCreateTime(new Date());
            itemModelMapper.insert(itemModel);
        } else {
            DailyItemModel oldItemModel = itemModelMapper.getById(itemModelId, DailyItemModel.class);
            oldItemModel.setUpdateBy(UserUtil.getUsername());
            oldItemModel.setUpdateTime(new Date());
            itemModelMapper.update(oldItemModel);
        }
    }

    /**
     * 新增检测记录
     *
     * @param checkRecordVo
     */
    @Transactional
    public void addCheckRecord(CheckRecordVo checkRecordVo) {
        DailyCheckRecord checkRecord = checkRecordVo.getCheckRecord();
        checkRecordMapper.insertRecord(checkRecord);
        List<DailyItemRecord> itemRecords = checkRecordVo.getItemRecords();
        for (DailyItemRecord itemRecord : itemRecords) {
            itemRecord.setCheckRecordId(checkRecord.getId());
        }
        itemRecordMapper.insertList(itemRecords);
    }

    /**
     * 根据查询条件搜索检测记录
     *
     * @param pageFilter 条件
     */
    public List<DailyCheckRecord> getCheckRecord(String type, JSONObject pageFilter) {
        PageHelper.startPage(pageFilter.getIntValue("pageNum"), pageFilter.getIntValue("pageSize"));
        return checkRecordMapper.findList(searchService.pageFilter2Filter(pageFilter, new WhereFilter() {{
            addFilter("type", Operation.EQUAL, type);
        }}), DailyCheckRecord.class);
    }

    /**
     * 根据检测记录ID 查询对应的检测报告
     *
     * @param checkId 检测报告ID
     */
    public Map<String, Object> getCheckRecordDetailsByID(Long checkId) {
        Map<String, Object> map = new HashMap<>();
        DailyCheckRecord recordById = checkRecordMapper.getById(checkId, DailyCheckRecord.class);
        map.put("checkRecord", recordById);
        List<DailyItemRecord> itemModelList = itemRecordMapper.findList(new WhereFilter() {{
            addFilter("check_record_id", Operation.EQUAL, recordById.getId());
        }}, DailyItemRecord.class);
        map.put("itemRecords", itemModelList);
        return map;
    }

    /**
     * 删除检测项模板
     */
    public void deleteCheckItemModelById(Long id) {
        itemModelMapper.delById(id, DailyItemModel.class);
    }

    /**
     * 下载/打印检测报告
     */
    public void expert(Long recordId, HttpServletResponse response) {
        DailyCheckRecord recordById = checkRecordMapper.getById(recordId, DailyCheckRecord.class);
        List<DailyItemRecord> itemModelList = itemRecordMapper.findList(new WhereFilter() {{
            addFilter("check_record_id", Operation.EQUAL, recordById.getId());
        }}, DailyItemRecord.class);
        try {
            File file = ResourceUtils.getFile("classpath:template/化验室检测模板.xls");
            //将检测数据写入检测报告，并下载
            XSSFWorkbook workbook = null;
            XSSFSheet sheet = null;
            InputStream is = new FileInputStream(file);
            workbook = new XSSFWorkbook(is);
            sheet = workbook.getSheetAt(0);
            if (sheet != null) {
                sheet.getRow(0).getCell(5).setCellValue(recordById.getRev());
                sheet.getRow(1).getCell(5).setCellValue(recordById.getSheetNo());
                sheet.getRow(2).getCell(5).setCellValue(recordById.getNo());
                if ("PICKLING".equals(recordById.getType())){
                    sheet.getRow(3).getCell(0).setCellValue("酸洗磷化线槽液日常检测报告");
                }else if("ELECTROPHORESIS".equals(recordById.getType())){
                    sheet.getRow(3).getCell(0).setCellValue("电泳槽液日常检测报告");
                }else {
                    sheet.getRow(3).getCell(0).setCellValue("前处理槽液日常检测报告");
                }
                int num = 6;
                for (DailyItemRecord itemRecord : itemModelList){
                    sheet.getRow(num).getCell(0).setCellValue(itemRecord.getOrderNum());
                    sheet.getRow(num).getCell(1).setCellValue(itemRecord.getName());
                    sheet.getRow(num).getCell(2).setCellValue(itemRecord.getIsNecessary() ? "★" : "");
                    sheet.getRow(num).getCell(3).setCellValue(itemRecord.getCheckResult());
                    sheet.getRow(num).getCell(4).setCellValue(itemRecord.getRangeAll());
                    sheet.getRow(num).getCell(5).setCellValue(itemRecord.getFrequency());
                    sheet.getRow(num).getCell(6).setCellValue(DateUtils.parseDateToString(itemRecord.getCreateTime(), "yyyyMMdd HH:mm:ss"));
                    num ++;
                }
                sheet.getRow(26).getCell(1).setCellValue(recordById.getRecordInfo());
                sheet.getRow(34).getCell(1).setCellValue(recordById.getCreateBy());
                sheet.getRow(34).getCell(4).setCellValue(DateUtils.parseDateToString(recordById.getCreateTime(), "yyyy年MM月dd日"));
            }
            ServletOutputStream outputStream = response.getOutputStream();
            String filename;
            if ("PICKLING".equals(recordById.getType())){
                filename = "酸洗磷化线槽液日常检测报告";
            }else if("ELECTROPHORESIS".equals(recordById.getType())){
                filename = "电泳槽液日常检测报告";
            }else {
                filename = "前处理槽液日常检测报告";
            }
            String codedFileName = URLEncoder.encode(filename, "UTF-8");
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename=" + codedFileName + ".xls");
            response.setHeader("fileName", codedFileName + ".xls");
            workbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
            is.close();
        } catch (Exception e) {
            log.error("检测报告模板导出失败!原因: {}", e.getMessage());
        }
    }
}
