package com.patzn.lims.frame.service.impl;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.patzn.cloud.commons.api.RestAssert;
import com.patzn.lims.core.web.Account;
import com.patzn.lims.core.web.LoginHelper;
import com.patzn.lims.core.oss.OssClient;
import com.patzn.lims.core.web.BaseServiceImpl;
import com.patzn.lims.frame.enums.FrameFileTypeEnum;
import com.patzn.lims.frame.enums.LmsInnerStatusEnum;
import com.patzn.lims.res.service.ILmsPropertyService;
import com.patzn.lims.frame.entity.LmsFrameCheckManage;
import com.patzn.lims.frame.entity.LmsFrameCheckManageRecord;
import com.patzn.lims.frame.entity.LmsFrameFile;
import com.patzn.lims.frame.entity.LmsFrameLog;
import com.patzn.lims.frame.mapper.LmsFrameCheckManageMapper;
import com.patzn.lims.frame.service.ILmsFrameCheckManageRecordService;
import com.patzn.lims.frame.service.ILmsFrameCheckManageService;
import com.patzn.lims.frame.service.ILmsFrameFileService;
import com.patzn.lims.frame.service.ILmsFrameLogService;
import com.patzn.lims.frame.vo.LmsFrameCheckManageVO;
import org.apache.commons.collections.CollectionUtils;
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.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author patzn123
 * @since 2018-01-09
 */
@Service
public class LmsFrameCheckManageServiceImpl extends BaseServiceImpl<LmsFrameCheckManageMapper, LmsFrameCheckManage> implements ILmsFrameCheckManageService {

    @Autowired
    private ILmsFrameFileService lmsFrameFileService;
    @Autowired
    private ILmsFrameLogService lmsFrameLogService;
    @Autowired
    private ILmsFrameCheckManageRecordService lmsFrameCheckManageRecordService;
    @Autowired
    private ILmsPropertyService lmsPropertyService;
    @Autowired
    private OssClient ossClient;

    @Override
    public Page<LmsFrameCheckManage> page(Page<LmsFrameCheckManage> page, LmsFrameCheckManage lmsFrameCheckManage) {
        lmsFrameCheckManage.setTempStatus(1);
        return page(page, Wrappers.<LmsFrameCheckManage>query(lmsFrameCheckManage));
    }


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


    @Override
    public LmsFrameCheckManageVO getVOById(Long id) {
        LmsFrameCheckManage lmsFrameCheckManage = getById(id);
        if (null == lmsFrameCheckManage) {
            return null;
        }
        //获取附件
        LmsFrameCheckManageVO vo = lmsFrameCheckManage.convert(LmsFrameCheckManageVO.class);
        LmsFrameFile lmsFrameFile = new LmsFrameFile();
        lmsFrameFile.setRelId(lmsFrameCheckManage.getId());
        List<LmsFrameFile> list = lmsFrameFileService.list(lmsFrameFile);
        list.forEach(e -> {
            e.setFilePath(ossClient.getUrl(e.getFilePath()).toString());
        });
        vo.setLmsFrameFileList(list);
        return vo;
    }


    @Override
    public LmsFrameCheckManageVO getTempVO() {
        LmsFrameCheckManage entity = new LmsFrameCheckManage();
        entity.setUserId(LoginHelper.getAccount().getUserId());
        entity.setTempStatus(0);
        LmsFrameCheckManage frameCheckManage = baseMapper.selectOne(Wrappers.<LmsFrameCheckManage>query().eq("temp_status",0).eq("user_id",LoginHelper.getAccount().getUserId()).last("LIMIT 1"));
        if (null != frameCheckManage) {
            LmsFrameCheckManageVO vo = frameCheckManage.convert(LmsFrameCheckManageVO.class);
            //获取附件
            LmsFrameFile lmsFrameFile = new LmsFrameFile();
            lmsFrameFile.setRelId(frameCheckManage.getId());
            List<LmsFrameFile> lmsFrameFileList = lmsFrameFileService.list(lmsFrameFile);
            lmsFrameFileList.forEach(e -> {
                e.setFilePath(ossClient.getUrl(e.getFilePath()).toString());
            });
            vo.setLmsFrameFileList(lmsFrameFileList);
            return vo;
        }
        LmsFrameCheckManage manage = new LmsFrameCheckManage();
        manage.setTempStatus(0);
        manage.setUserId(LoginHelper.getAccount().getUserId());
        if (save(manage)) {
            LmsFrameCheckManageVO vo = new LmsFrameCheckManageVO();
            vo.setTempStatus(manage.getTempStatus());
            vo.setUserId(manage.getUserId());
            return vo;
        }
        return null;
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean edit(LmsFrameCheckManage lmsFrameCheckManage) {
        if (null != lmsFrameCheckManage.getId()) {
            //提交数据操作日志保存
            LmsFrameCheckManage entity = getById(lmsFrameCheckManage.getId());
            String remark = lmsPropertyService.getObjectCompareDifferent(lmsFrameCheckManage, entity, "管理评审计划实施对比", "修改信息：");
            if (StringUtils.isNotBlank(remark)) {
                LmsFrameCheckManageRecord record = new LmsFrameCheckManageRecord();
                record.setCheckManageId(entity.getId());
                record.setOperator(LoginHelper.getAccount().getUserName());
                record.setRemark(remark);
                record.setType(2);
                record.setLiable(LoginHelper.getAccount().getUserName());
                record.setOrigin(0 == entity.getStatus() ? "草稿" : "已提交");
                record.setTarget(0 == entity.getStatus() ? "草稿" : "已提交");
                lmsFrameCheckManageRecordService.save(record);
            }
            if (1 == entity.getStatus()) {
                LmsFrameLog log = new LmsFrameLog();
                log.setUserId(LoginHelper.getAccount().getUserId());
                log.setUserName(LoginHelper.getAccount().getUserName());
                log.setTableName("lms_frame_check_manage");
                log.setOrginParams(entity.toString());
                log.setParams(lmsFrameCheckManage.toString());
                log.setCreateTime(new Date());
                lmsFrameLogService.save(log);
            }
        }
        return updateById(lmsFrameCheckManage);
    }


    @Override
    public Boolean add(LmsFrameCheckManage lmsFrameCheckManage) {
        Account account = LoginHelper.getAccount();
        lmsFrameCheckManage.setCheckManageTime(new Date());
        lmsFrameCheckManage.setUname(account.getUserName());
        LmsFrameCheckManage temp = baseMapper.selectOne(Wrappers.<LmsFrameCheckManage>query().eq("temp_status",0).eq("user_id",account.getUserId()).last("LIMIT 1"));
        if (null != temp) {
            lmsFrameCheckManage.setId(temp.getId());
            lmsFrameCheckManage.setTempStatus(1);
            return updateById(lmsFrameCheckManage);
        }
        lmsFrameCheckManage.setUserId(account.getUserId());
        lmsFrameCheckManage.setTempStatus(1);
        return save(lmsFrameCheckManage);
    }


    @Override
    public Boolean delete(Long[] ids) {
        lmsFrameFileService.deleteBatch(ids);
        return remove(Wrappers.<LmsFrameCheckManage>query().in("id", ids));
    }


    @Override
    public LmsFrameFile uploadFile(MultipartFile file, LmsFrameCheckManage lmsFrameCheckManage) {
        Long companyId = LoginHelper.getAccount().getCompanyId();
        String folderPath = "frame/InnerCheckManage/" + companyId + "/";
        return lmsFrameFileService.saveAndUpload(file, "lims", folderPath, lmsFrameCheckManage.getId(), FrameFileTypeEnum.CHECK_MANAGE.getValue());
    }

    @Override
    public void downloadFile(Long id, HttpServletResponse response) {
        LmsFrameFile lmsFrameFile = lmsFrameFileService.getById(id);
        String fileUrl = lmsFrameFile.getFilePath();
        String orgFileName = lmsFrameFile.getOrginName().replaceAll("\\s*", "");
        lmsFrameFileService.downloadFile(response, "lims", fileUrl, orgFileName);
    }


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


    @Override
    public Boolean submit(List<Long> ids) {

        int count = super.count(Wrappers.<LmsFrameCheckManage>query().eq("status", 1).in("id", ids));
        RestAssert.fail(count > 0, "选择了已经提交的数据，请确认");
        if (CollectionUtils.isEmpty(ids)) {
            return false;
        }

        List<LmsFrameCheckManageRecord> recordList = Lists.newArrayList();
        for (Long id : ids) {
            LmsFrameCheckManageRecord record = new LmsFrameCheckManageRecord();
            record.setCheckManageId(id);
            record.setOperator(LoginHelper.getAccount().getUserName());
            record.setLiable(LoginHelper.getAccount().getUserName());
            record.setRemark("提交");
            record.setType(0);
            record.setOrigin("草稿");
            record.setTarget("已提交");
            record.setOrigin(LmsInnerStatusEnum.DRAFT.getDisplay());
            recordList.add(record);
        }
        if (CollectionUtils.isNotEmpty(recordList)) {
            lmsFrameCheckManageRecordService.saveBatch(recordList);
        }

        return updateBatchById(ids.stream().map(id -> {
            LmsFrameCheckManage entity = new LmsFrameCheckManage();
            entity.setId(id);
            entity.setStatus(1);
            return entity;
        }).collect(Collectors.toList()));
    }


    @Override
    public boolean existByIds(Long[] ids) {
        return super.count(Wrappers.<LmsFrameCheckManage>query().in("check_plan_id", ids)) >= 1;
    }
}
