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.google.common.collect.Lists;
import com.patzn.lims.common.StringHandleUtils;
import com.patzn.lims.common.StringStaticDataUtils;
import com.patzn.lims.core.api.PtAssert;
import com.patzn.lims.core.oss.OssClient;
import com.patzn.lims.core.web.Account;
import com.patzn.lims.core.web.LoginHelper;
import com.patzn.lims.core.web.BaseServiceImpl;
import com.patzn.lims.frame.entity.LmsYearPlan;
import com.patzn.lims.frame.entity.LmsYearPlanFile;
import com.patzn.lims.frame.entity.LmsYearPlanRecord;
import com.patzn.lims.frame.enums.PlanStatusEnum;
import com.patzn.lims.frame.mapper.LmsYearPlanMapper;
import com.patzn.lims.frame.service.ILmsYearPlanFileService;
import com.patzn.lims.frame.service.ILmsYearPlanRecordService;
import com.patzn.lims.frame.service.ILmsYearPlanService;
import com.patzn.lims.frame.vo.LmsYearPlanVO;
import com.patzn.lims.res.service.ILmsPropertyService;
import com.patzn.lims.workflow.FlowInfo;
import com.patzn.lims.workflow.FlowProcess;
import com.patzn.lims.workflow.FlowType;
import com.patzn.lims.workflow.FlowVariables;
import com.patzn.lims.workflow.service.IFlowProcessService;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
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 java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 年度总计划表 服务实现类
 * </p>
 *
 * @author patzn
 * @since 2018-06-26
 */
@Service
public class LmsYearPlanServiceImpl extends BaseServiceImpl<LmsYearPlanMapper, LmsYearPlan> implements ILmsYearPlanService {

    @Autowired
    private IFlowProcessService flowProcessClient;
//    @Autowired
//    private ILmsMsgServicE lmsMsgService;
//    @Autowired
//    private ILmsMonthPlanService lmsMonthPlanService;
    @Autowired
    private ILmsPropertyService lmsPropertyService;
    @Autowired
    private ILmsYearPlanRecordService lmsYearPlanRecordService;
    @Autowired
    private ILmsYearPlanFileService lmsYearPlanFileService;
    @Autowired
    private OssClient ossClient;

    @Override
    public Page<LmsYearPlan> page(Page<LmsYearPlan> page, LmsYearPlan lmsYearPlan, Date startDate, Date endDate) {
        return page.setRecords(baseMapper.listYearPlan(page, lmsYearPlan, (Integer) PlanStatusEnum.END.getValue(), startDate, endDate));
    }


    @Override
    public List<LmsYearPlan> list(LmsYearPlan lmsYearPlan) {
        lmsYearPlan.setTempStatus(1);
        return list(Wrappers.query(lmsYearPlan));
    }

    @Override
    public LmsYearPlanVO getVOById(Long id) {
        LmsYearPlanVO lmsYearPlanVO = new LmsYearPlanVO();
        LmsYearPlan lmsYearPlan = getById(id);
        if (null != lmsYearPlan) {
            BeanUtils.copyProperties(lmsYearPlan, lmsYearPlanVO);
            //获取附件
            LmsYearPlanFile lmsYearPlanFile = new LmsYearPlanFile();
            lmsYearPlanFile.setRelId(lmsYearPlan.getId());
            List<LmsYearPlanFile> list = lmsYearPlanFileService.list(lmsYearPlanFile);
            for (LmsYearPlanFile e:list) {
                e.setFilePath(ossClient.getUrl(e.getFilePath()).toString());
            }
            lmsYearPlanVO.setLmsYearPlanFileList(list);
        }
        return lmsYearPlanVO;
    }

    @Override
    public boolean copy(LmsYearPlan lmsYearPlan, Account account) {
        lmsYearPlan.setId(IdWorker.getId());
        lmsYearPlan.setStatus((Integer) PlanStatusEnum.DRAFT.getValue());
        lmsYearPlan.setMakerId(account.getUserId());
        lmsYearPlan.setMaker(account.getUserName());
        lmsYearPlan.setMakeDate(new Date());
        lmsYearPlan.setUserId(account.getUserId());
        lmsYearPlan.setTempStatus(1);
        return super.save(lmsYearPlan);
    }

    @Override
    public Page<LmsYearPlan> pageReport(Page<LmsYearPlan> page, LmsYearPlan lmsYearPlan) {
        lmsYearPlan.setTempStatus(1);
        return page.setRecords(baseMapper.selectPageReport(page, lmsYearPlan));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public List<FlowProcess> submitYearPlanFlow(Long[] ids) {
        if (ArrayUtils.isEmpty(ids)) {
            return null;
        }
        Account account = LoginHelper.getAccount();
        List<LmsYearPlan> yearPlans = super.list(Wrappers.<LmsYearPlan>query().in("id", ids));
        List<LmsYearPlanRecord> recordList = Lists.newArrayList();
        List<FlowInfo> flowInfoList = new ArrayList<>();
        List<LmsYearPlan> saveYearPlanList = yearPlans.stream().filter(years -> null != years && (years.getStatus().equals((Integer)PlanStatusEnum.DRAFT.getValue()) || years.getStatus().equals((Integer) PlanStatusEnum.BACK.getValue()))).map(years -> {
            flowInfoList.add(FlowInfo.convertFlowInfo(FlowType.YEAR_UNSURE_CHECK,
                    account, years.getId(), years.getName()));
            // 设置状态为待审批人审批
            LmsYearPlan lmsYearPlan = new LmsYearPlan();
            lmsYearPlan.setId(years.getId());
            lmsYearPlan.setStatus((Integer)PlanStatusEnum.AUDIT.getValue());
            //操作记录
            LmsYearPlanRecord record = new LmsYearPlanRecord();
            record.setMainPlanId(years.getId());
            record.setOperator(account.getUserName());
            record.setLiable(account.getUserName());
            record.setRemark("不缺定度评审计划提交审批");
            record.setType(0);
            record.setTarget(PlanStatusEnum.AUDIT.getDisplay());
            record.setOrigin(PlanStatusEnum.DRAFT.getDisplay());
            recordList.add(record);
            return lmsYearPlan;
        }).collect(Collectors.toList());

        PtAssert.fail(CollectionUtils.isEmpty(saveYearPlanList), "只能提交草稿或退回状态的计划");
        updateBatchById(saveYearPlanList);
        if (CollectionUtils.isNotEmpty(recordList)) {
            lmsYearPlanRecordService.saveBatch(recordList);
        }
        return flowProcessClient.saveTask(flowInfoList,account);

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean approveFlow(String taskId, String status, String reason) {
        FlowVariables flowVariables = new FlowVariables(taskId);
        FlowInfo flowInfo;
        Map<String, Object> map = new HashMap<>(2);
        Account account = LoginHelper.getAccount();
        PtAssert.fail(!StringHandleUtils.isOnlyZeroOne(status), "状态值有误");
        LmsYearPlanRecord record = new LmsYearPlanRecord();
        record.setOperator(account.getUserName());
        record.setLiable(account.getUserName());
        record.setOrigin(PlanStatusEnum.AUDIT.getDisplay());
        if (StringStaticDataUtils.ZERO.equals(status)) {
            //审批驳回
            map.put("unsurePlanCheckPass", false);
            map.put(FlowInfo.APPLY_ID, LoginHelper.getAccount().getUserId());
            flowVariables.setVariables(map);
            flowInfo = flowProcessClient.complete(flowVariables);
            LmsYearPlan lmsYearPlan = getById(flowInfo.getId());
            lmsYearPlan.setStatus((Integer)PlanStatusEnum.BACK.getValue());

            record.setTarget(PlanStatusEnum.PASS.getDisplay());
            record.setRemark("不确定度计划评审驳回" + reason);
            record.setType(0);
            record.setMainPlanId(flowInfo.getId());

            super.updateById(lmsYearPlan);
            lmsYearPlanRecordService.save(record);
            super.update(new LmsYearPlan().setStatus((Integer)PlanStatusEnum.BACK.getValue()).setReason(reason), Wrappers.<LmsYearPlan>query().eq("id", flowInfo.getId()));
           // lmsMsgService.sendMsg("/lims/uncertainty_judge_plan", "计划：" + lmsYearPlan.getName() + "，审批人审批不通过，原因：" + reason, "审批人审批退回", account, Arrays.asList(new Long[]{lmsYearPlan.getMakerId()}));
            return null != flowInfo;
        }
        //审批通过
        map.put("unsurePlanCheckPass", true);
        map.put(FlowInfo.APPLY_ID, LoginHelper.getAccount().getUserId());
        flowVariables.setVariables(map);
        flowInfo = flowProcessClient.complete(flowVariables);
        LmsYearPlan lmsYearPlan = getById(flowInfo.getId());
        super.update(new LmsYearPlan().setStatus((Integer)PlanStatusEnum.PASS.getValue()).setReason(reason), Wrappers.<LmsYearPlan>query().eq("id", flowInfo.getId()));
        lmsYearPlan.setApproverId(LoginHelper.getAccount().getUserId());
        lmsYearPlan.setApprover(LoginHelper.getAccount().getUserName());
        lmsYearPlan.setApproveDate(new Date());
        lmsYearPlan.setStatus((Integer)PlanStatusEnum.PASS.getValue());

        record.setTarget(PlanStatusEnum.PASS.getDisplay());
        record.setRemark("不确定度计划评审通过" + reason);
        record.setType(0);
        record.setMainPlanId(flowInfo.getId());

        super.updateById(lmsYearPlan);
        lmsYearPlanRecordService.save(record);
        //lmsMsgService.sendMsg("/lims/uncertainty_judge_plan", "计划：" + lmsYearPlan.getName() + "，审批人审批通过", "新的需确认的审批", account, Arrays.asList(new Long[]{lmsYearPlan.getMakerId()}));
        return null != flowInfo;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean approveConfirm(String taskId, String status, String reason) {
        FlowInfo flowInfo = null;
        if (StringStaticDataUtils.SUCCESS.equals(status)) {
            // 确认审批完成
            flowInfo = flowProcessClient.complete(taskId);
            PtAssert.fail(null == flowInfo, "确认审批失败！");
            //审批通过
            return null != flowInfo && updateYearMonthStatus(flowInfo.getId(), PlanStatusEnum.END);
        }
        flowInfo = flowProcessClient.complete(taskId);
        updateYearMonthStatus(flowInfo.getId(), PlanStatusEnum.BACK);
        return true;
    }

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


    public boolean updateYearMonthStatus(Long id, PlanStatusEnum statusEnum) {
        LmsYearPlan lmsYearPlan = new LmsYearPlan();
        lmsYearPlan.setId(id);
        lmsYearPlan.setStatus((Integer)statusEnum.getValue());
        //lmsMonthPlanService.updateMonthPlanByYearPlan(id, statusEnum);
        return super.updateById(lmsYearPlan);
    }


    @Override
    public LmsYearPlanFile uploadFile(MultipartFile file, LmsYearPlan lmsYearPlan) {
        Long companyId = LoginHelper.getAccount().getCompanyId();
        String folderPath = "frame/yearPlan/" + companyId + "/";
        return lmsYearPlanFileService.saveAndUpload(file, "lims", folderPath, lmsYearPlan.getId(), 0);
    }

    @Override
    public Boolean deleteFile(Long id) {
        Long[] ids = new Long[]{id};
        return lmsYearPlanFileService.deleteBatch(ids);
    }


    @Override
    public Boolean add(LmsYearPlan lmsYearPlan) {

        LmsYearPlan entity = new LmsYearPlan();
        entity.setUserId(LoginHelper.getAccount().getUserId());
        entity.setTempStatus(0);
        LmsYearPlan temp = baseMapper.selectOne(Wrappers.query(entity));
        lmsYearPlan.setTempStatus(1);

        if (null != temp) {
            lmsYearPlan.setId(temp.getId());
            updateById(lmsYearPlan);
        } else {
            lmsYearPlan.setUserId(LoginHelper.getAccount().getUserId());

            save(lmsYearPlan);
        }

        return true;
    }


    @Override
    public LmsYearPlanVO getTempVO() {
        LmsYearPlanVO lmsYearPlanVO = new LmsYearPlanVO();
        LmsYearPlan entity = new LmsYearPlan();
        entity.setUserId(LoginHelper.getAccount().getUserId());
        entity.setTempStatus(0);
        LmsYearPlan lmsYearPlan = baseMapper.selectOne(Wrappers.query(entity));
        if (null != lmsYearPlan) {
            BeanUtils.copyProperties(lmsYearPlan, lmsYearPlanVO);
            //改成删除附件
            lmsYearPlanFileService.deleteByYearPlan(lmsYearPlan.getId());

        } else {
            LmsYearPlan plan = new LmsYearPlan();
            plan.setTempStatus(0);
            plan.setUserId(LoginHelper.getAccount().getUserId());
            save(plan);
            BeanUtils.copyProperties(plan, lmsYearPlanVO);
        }

        return lmsYearPlanVO;
    }

}
