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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.LoginHelper;
import com.patzn.lims.core.web.BaseServiceImpl;
import com.patzn.lims.core.oss.OssClient;
import com.patzn.lims.res.service.ILmsPropertyService;
import com.patzn.lims.frame.entity.LmsFrameFile;
import com.patzn.lims.frame.entity.LmsFrameInnerCheckManage;
import com.patzn.lims.frame.entity.LmsFrameInnerCheckManageRecord;
import com.patzn.lims.frame.entity.LmsFrameLog;
import com.patzn.lims.frame.enums.FrameFileTypeEnum;
import com.patzn.lims.frame.enums.LmsInnerStatusEnum;
import com.patzn.lims.frame.mapper.LmsFrameInnerCheckManageMapper;
import com.patzn.lims.frame.service.ILmsFrameFileService;
import com.patzn.lims.frame.service.ILmsFrameInnerCheckManageRecordService;
import com.patzn.lims.frame.service.ILmsFrameInnerCheckManageService;
import com.patzn.lims.frame.service.ILmsFrameLogService;
import com.patzn.lims.frame.vo.LmsFrameInnerCheckManageVO;
import org.apache.commons.collections.CollectionUtils;
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 javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 内审实施管理 服务实现类
 * </p>
 *
 * @author patzn123
 * @since 2018-01-09
 */
@Service
public class LmsFrameInnerCheckManageServiceImpl extends BaseServiceImpl<LmsFrameInnerCheckManageMapper, LmsFrameInnerCheckManage> implements ILmsFrameInnerCheckManageService {

    @Autowired
    private ILmsFrameFileService lmsFrameFileService;
    @Autowired
    private ILmsFrameLogService lmsFrameLogService;
    @Autowired
    private ILmsFrameInnerCheckManageRecordService lmsFrameInnerCheckManageRecordService;

    @Autowired
    private ILmsPropertyService lmsPropertyService;
    @Autowired
    private OssClient ossClient;

    @Override
    public Page<LmsFrameInnerCheckManage> page(Page<LmsFrameInnerCheckManage> page, LmsFrameInnerCheckManage lmsFrameInnerCheckManage) {
        lmsFrameInnerCheckManage.setTempStatus(1);
         QueryWrapper wrapper = Wrappers.<LmsFrameInnerCheckManage>query(lmsFrameInnerCheckManage);

         if (StringUtils.isNotBlank(lmsFrameInnerCheckManage.getCheckManageItem())){
             wrapper.like("check_manage_item", lmsFrameInnerCheckManage.getCheckManageItem());
             lmsFrameInnerCheckManage.setCheckManageTime(null);
         }
        if (StringUtils.isNotBlank(lmsFrameInnerCheckManage.getCheckManageContent())){
            wrapper.like("check_manage_content", lmsFrameInnerCheckManage.getCheckManageContent());
            lmsFrameInnerCheckManage.setCheckManageContent(null);
        }
        if (StringUtils.isNotBlank(lmsFrameInnerCheckManage.getCheckManageResult())){

            wrapper.like("check_manage_result", lmsFrameInnerCheckManage.getCheckManageResult());
            lmsFrameInnerCheckManage.setCheckManageResult(null);
        }
        if (StringUtils.isNotBlank(lmsFrameInnerCheckManage.getCheckMemberName())){

            wrapper.like("check_member_name", lmsFrameInnerCheckManage.getCheckMemberName());
            lmsFrameInnerCheckManage.setCheckMemberName(null);
        }
        if (StringUtils.isNotBlank(lmsFrameInnerCheckManage.getCheckType())){
            wrapper.like("check_type", lmsFrameInnerCheckManage.getCheckType());
            lmsFrameInnerCheckManage.setCheckType(null);
        }

        if (lmsFrameInnerCheckManage.getCheckManageTime() != null) {
            String pattern = "yyyy-MM-dd";
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
            wrapper.eq(" to_char(check_manage_time, 'yyyy-MM-dd') ", simpleDateFormat.format(lmsFrameInnerCheckManage.getCheckManageTime()) );
            lmsFrameInnerCheckManage.setCheckManageTime(null);
        }
        return page(page, wrapper);
    }

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

    @Override
    public LmsFrameInnerCheckManageVO getVOById(Long id) {
        LmsFrameInnerCheckManageVO lmsFrameInnerCheckManageVO = new LmsFrameInnerCheckManageVO();
        LmsFrameInnerCheckManage lmsFrameInnerCheckManage = getById(id);
        if (null != lmsFrameInnerCheckManage) {
            BeanUtils.copyProperties(lmsFrameInnerCheckManage, lmsFrameInnerCheckManageVO);
            //获取附件
            LmsFrameFile lmsFrameFile = new LmsFrameFile();
            lmsFrameFile.setRelId(lmsFrameInnerCheckManage.getId());
            List<LmsFrameFile> lmsFrameFileList=lmsFrameFileService.list(lmsFrameFile);
            lmsFrameFileList.forEach(e -> {
                e.setFilePath(ossClient.getUrl(e.getFilePath()).toString());
            });
            lmsFrameInnerCheckManageVO.setLmsFrameFileList(lmsFrameFileList);
        }

        return lmsFrameInnerCheckManageVO;
    }

    @Override
    public LmsFrameInnerCheckManageVO getTempVO() {
        LmsFrameInnerCheckManageVO lmsFrameInnerCheckManageVO = new LmsFrameInnerCheckManageVO();
        LmsFrameInnerCheckManage entity = new LmsFrameInnerCheckManage();
        entity.setUserId(LoginHelper.getAccount().getUserId());
        entity.setTempStatus(0);
        LmsFrameInnerCheckManage lmsFrameInnerCheckManage = baseMapper.selectOne(Wrappers.query(entity));
        if (null != lmsFrameInnerCheckManage) {
            BeanUtils.copyProperties(lmsFrameInnerCheckManage, lmsFrameInnerCheckManageVO);
            //获取附件
            LmsFrameFile lmsFrameFile = new LmsFrameFile();
            lmsFrameFile.setRelId(lmsFrameInnerCheckManage.getId());
            lmsFrameInnerCheckManageVO.setLmsFrameFileList(lmsFrameFileService.list(lmsFrameFile));
        } else {
            LmsFrameInnerCheckManage manage = new LmsFrameInnerCheckManage();
            manage.setTempStatus(0);
            manage.setUserId(LoginHelper.getAccount().getUserId());
            save(manage);
            BeanUtils.copyProperties(manage, lmsFrameInnerCheckManageVO);
        }

        return lmsFrameInnerCheckManageVO;
    }

    @Override
    @Transactional
    public Boolean edit(LmsFrameInnerCheckManage lmsFrameInnerCheckManage) {
        if (null != lmsFrameInnerCheckManage.getId()) {//提交数据操作日志保存
            LmsFrameInnerCheckManage entity = getById(lmsFrameInnerCheckManage.getId());
            String remark = lmsPropertyService.getObjectCompareDifferent(lmsFrameInnerCheckManage, entity, "内审实施信息对比", "修改信息：");
            if (StringUtils.isNotBlank(remark)) {
                LmsFrameInnerCheckManageRecord record = new LmsFrameInnerCheckManageRecord();
                record.setInnerManageId(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() ? "草稿" : "已提交");
                lmsFrameInnerCheckManageRecordService.save(record);
            }
            if (1 == entity.getStatus()) {
                LmsFrameLog log = new LmsFrameLog();
                log.setUserId(LoginHelper.getAccount().getUserId());
                log.setUserName(LoginHelper.getAccount().getUserName());
                log.setTableName("lms_frame_inner_check_manage");
                log.setOrginParams(entity.toString());
                log.setParams(lmsFrameInnerCheckManage.toString());
                log.setCreateTime(new Date());
                lmsFrameLogService.save(log);
            }
        }
        return updateById(lmsFrameInnerCheckManage);
    }

    @Override
    public Boolean add(LmsFrameInnerCheckManage lmsFrameInnerCheckManage) {
//        lmsFrameInnerCheckManage.setCheckMemberId(LoginHelper.getAccount().getUserId());
//        lmsFrameInnerCheckManage.setCheckMemberName(LoginHelper.getAccount().getUserName());
        lmsFrameInnerCheckManage.setCheckManageTime(new Date());

        LmsFrameInnerCheckManage entity = new LmsFrameInnerCheckManage();
        entity.setUserId(LoginHelper.getAccount().getUserId());
        entity.setTempStatus(0);
        LmsFrameInnerCheckManage temp = baseMapper.selectOne(Wrappers.query(entity));
        lmsFrameInnerCheckManage.setUname(LoginHelper.getAccount().getUserName());
        if (null != temp) {
            lmsFrameInnerCheckManage.setId(temp.getId());
            lmsFrameInnerCheckManage.setTempStatus(1);
            updateById(lmsFrameInnerCheckManage);
        } else {
            lmsFrameInnerCheckManage.setUserId(LoginHelper.getAccount().getUserId());
            lmsFrameInnerCheckManage.setTempStatus(1);
            save(lmsFrameInnerCheckManage);
        }

        return true;
    }

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

    @Override
    public LmsFrameFile uploadFile(MultipartFile file, LmsFrameInnerCheckManage lmsFrameInnerCheckManage) {
        Long companyId = LoginHelper.getAccount().getCompanyId();
        String folderPath = "frame/InnerCheckManage/" + companyId + "/";
        return lmsFrameFileService.saveAndUpload(file, "lims", folderPath, lmsFrameInnerCheckManage.getId(), FrameFileTypeEnum.INNER_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) {
        Long[] ids = new Long[]{id};
        return lmsFrameFileService.deleteBatch(ids);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean submit(List<Long> ids) {
        RestAssert.fail(count(Wrappers.<LmsFrameInnerCheckManage>query().in("id", ids).eq("status", 1)) > 0, "选择了已经提交的，请确认");

        List<LmsFrameInnerCheckManageRecord> recordList = Lists.newArrayList();
        List<LmsFrameInnerCheckManage> entityList = Lists.newArrayList();
        for (Long id : ids) {
            LmsFrameInnerCheckManage entity = new LmsFrameInnerCheckManage();
            entity.setId(id);
            entity.setStatus(1);
            entityList.add(entity);
            LmsFrameInnerCheckManageRecord record = new LmsFrameInnerCheckManageRecord();
            record.setInnerManageId(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)) {
            lmsFrameInnerCheckManageRecordService.saveBatch(recordList);
        }
        return updateBatchById(entityList);
    }

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