package com.patzn.lims.frame.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.patzn.lims.core.api.PtAssert;
import com.patzn.lims.core.web.Account;
import com.patzn.lims.core.web.BaseServiceImpl;
import com.patzn.lims.excel.eto.LmsMonthPlanETO;
import com.patzn.lims.frame.entity.LmsMonthPlan;
import com.patzn.lims.frame.enums.PlanStatusEnum;
import com.patzn.lims.frame.mapper.LmsMonthPlanMapper;
import com.patzn.lims.frame.service.ILmsMonthPlanAttachmentService;
import com.patzn.lims.frame.service.ILmsMonthPlanRecordService;
import com.patzn.lims.frame.service.ILmsMonthPlanService;
import com.patzn.lims.res.service.ILmsPropertyService;
import com.patzn.poibox.utils.ExcelUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 年度计划子表 服务实现类
 * </p>
 *
 * @author patzn
 * @since 2018-06-26
 */
@Service
public class LmsMonthPlanServiceImpl extends BaseServiceImpl<LmsMonthPlanMapper, LmsMonthPlan> implements ILmsMonthPlanService {

    @Autowired
    private ILmsMonthPlanAttachmentService lmsMonthPlanAttachmentService;
    @Autowired
    private ILmsPropertyService lmsPropertyService;
    @Autowired
    private ILmsMonthPlanRecordService lmsMonthPlanRecordService;
    @Override
    public Page<LmsMonthPlan> page(Page<LmsMonthPlan> page, LmsMonthPlan lmsMonthPlan, Date startDate, Date endDate) {
        return page.setRecords(baseMapper.listMonthPlan(page, lmsMonthPlan, (Integer) PlanStatusEnum.END.getValue(), startDate, endDate));
    }

    @Override
    public List<LmsMonthPlan> list(LmsMonthPlan lmsMonthPlan) {
        return list(Wrappers.query(lmsMonthPlan));
    }

    @Override
    public Page<LmsMonthPlan> pagePlan(Page<LmsMonthPlan> page, Long planId) {
        PtAssert.fail(null == planId, "请选择年度计划");
        return super.page(page,Wrappers.<LmsMonthPlan>query().eq("year_plan_id", planId).ne("status", PlanStatusEnum.END));
    }

    @Override
    public boolean copy(LmsMonthPlan lmsMonthPlan) {
        PtAssert.fail(null == lmsMonthPlan || null == lmsMonthPlan.getYearPlanId(), "请确认年度计划");
        lmsMonthPlan.setId(IdWorker.getId());
        lmsMonthPlan.setStatus((Integer) PlanStatusEnum.DRAFT.getValue());
        return super.save(lmsMonthPlan);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean submit(Long[] ids, Date endDate) {
        PtAssert.fail(ArrayUtils.isEmpty(ids), "请选择计划");
        PtAssert.fail(null == endDate, "请输入完成日期");
        List<LmsMonthPlan> list = super.list(Wrappers.<LmsMonthPlan>query().in("id", ids));
        for (LmsMonthPlan monthPlan : list) {
            PtAssert.fail((Integer) PlanStatusEnum.START.getValue() != monthPlan.getStatus(), "只能提交实施中的计划");
            PtAssert.fail(0 == lmsMonthPlanAttachmentService.getCountByPlanId(monthPlan.getId()), "提交的计划必须上传附件");
        }
        return super.update(new LmsMonthPlan().setStatus((Integer)PlanStatusEnum.END.getValue()).setEndDate(endDate), Wrappers.<LmsMonthPlan>query().in("id", ids));
    }


    @Override
    public Page<LmsMonthPlan> pageReport(Page<LmsMonthPlan> page, Long planId) {
        PtAssert.fail(null == planId, "请选择年度计划");
        return super.page(page, Wrappers.<LmsMonthPlan>query().eq("year_plan_id", planId).eq("status", PlanStatusEnum.END));
    }

    @Override
    public void exportMonthPlan(Long[] ids, HttpServletResponse response) {
        PtAssert.fail(ArrayUtils.isEmpty(ids), "请选择导出数据");
//        List<LmsMonthPlan> list = super.list(Wrappers.<LmsMonthPlan>query().in("id", ids));
//        List<LmsNewMonthPlanETO> etoList = new ArrayList<>();
//        list.forEach(e->{
//            LmsNewMonthPlanETO lmsNewMonthPlanETO = new LmsNewMonthPlanETO();
//            lmsNewMonthPlanETO.setName(e.getName());
//            lmsNewMonthPlanETO.setStatus(e.getStatus().getDisplay());
//            lmsNewMonthPlanETO.setFrequency(e.getFrequency());
//            lmsNewMonthPlanETO.setBeginDate(DateUtils.dateTransfer(e.getBeginDate(),"yyyy-MM-dd"));
//            lmsNewMonthPlanETO.setDutyUnit(e.getDutyUnit());
//            lmsNewMonthPlanETO.setDutyMan(e.getDutyMan());
//            lmsNewMonthPlanETO.setRemark(e.getRemark());
//            etoList.add(lmsNewMonthPlanETO);
//                }
//        );
//        //导出
//       new LmsNewMonthPlanExportHandler(etoList).generater(response);
    }

    @Override
    public void exportMonthReport(Long[] ids, HttpServletResponse response) {
        PtAssert.fail(ArrayUtils.isEmpty(ids), "请选择导出数据");
        List<LmsMonthPlan> list = super.list(Wrappers.<LmsMonthPlan>query().in("id", ids));
//        List<LmsMonthPlanETO> etoList = list.stream().map(obj -> obj.convert(LmsMonthPlanETO.class)).collect(Collectors.toList());
//        //导出
//        new LmsMonthReportExportHandler(etoList).generater(response);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean importMonthPlan(MultipartFile file, Long planId, Account account) {
        Collection<LmsMonthPlanETO> etos = null;
        try {
            etos = ExcelUtils.readSheetAtOne(LmsMonthPlanETO.class, file, "导入计划失败");
        } catch (Exception e) {
            PtAssert.fail("导入计划失败！");
        }
        if (CollectionUtils.isEmpty(etos)) {
            return false;
        }
        List<LmsMonthPlan> list = etos.stream().map(obj -> {
            LmsMonthPlan plan = new LmsMonthPlan();
            plan.setId(IdWorker.getId());
            plan.setStatus((Integer) PlanStatusEnum.DRAFT.getValue());
            plan.setYearPlanId(planId);
            plan.setName(obj.getName());
            plan.setFrequency(obj.getFrequency());
            plan.setBeginDate(obj.getBeginDate());
            plan.setDutyUnit(obj.getDutyUnit());
            plan.setDutyMan(obj.getDutyMan());
            plan.setRemark(obj.getRemark());
            plan.setUname(account.getUserName());
            return plan;
        }).collect(Collectors.toList());
        return super.saveBatch(list);
    }


    @Override
    public boolean updateMonthPlanByYearPlan(Long yearId, PlanStatusEnum status) {
        return super.update(new LmsMonthPlan().setStatus((Integer) status.getValue()), Wrappers.<LmsMonthPlan>query().eq("year_plan_id", yearId));
    }


    @Override
    public boolean updatePlanById(LmsMonthPlan lmsMonthPlan) {
        PtAssert.fail(null == lmsMonthPlan.getId(), "id不能为空");
        LmsMonthPlan dbMonthPlan = super.getById(lmsMonthPlan.getId());
        String remark = lmsPropertyService.getCompareDifferent(lmsMonthPlan, dbMonthPlan, "月度不确定度计划对比", "月度不确定度计划修改内容：");
        if (StringUtils.isNotEmpty(remark)) {
            lmsMonthPlanRecordService.saveMonthPlanRecordByIds(dbMonthPlan, PlanStatusEnum.valueOf(dbMonthPlan.getStatus()), 2, new Long[]{lmsMonthPlan.getId()}, remark);
        }
        return super.updateById(lmsMonthPlan);
    }

}
