package com.yiboshi.science.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yiboshi.arch.exception.BusinessException;
import com.yiboshi.science.base.BaseServiceImpl;
import com.yiboshi.science.base.Pagination;
import com.yiboshi.science.dao.ComProjectCheckDAO;
import com.yiboshi.science.entity.*;
import com.yiboshi.science.enumeration.CommonEnum;
import com.yiboshi.science.param.dto.ComProjectAuditNoteDTO;
import com.yiboshi.science.param.dto.ComProjectCheckDTO;
import com.yiboshi.science.param.dto.ComProjectResultsDTO;
import com.yiboshi.science.param.dto.DataStatisticsDTO;
import com.yiboshi.science.param.query.ComProjectCheckQueryVO;
import com.yiboshi.science.service.*;
import com.yiboshi.science.utils.CreateCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 中期考核表 Service 实现类
 *
 * @author lkl
 * @version 2021-08-26
 */
@Service
public class ComProjectCheckServiceImpl extends BaseServiceImpl<ComProjectCheckDAO, ComProjectCheckQueryVO, ComProjectCheckDTO, ComProjectCheck> implements ComProjectCheckService {

    @Autowired
    private ComProjectCheckDAO comProjectCheckDAO;
    @Autowired
    private ComProjectResultsService comProjectResultsService;
    @Autowired
    private ComProjectAuditService comProjectAuditService;
    @Autowired
    private ComProjectTaskService ComProjectTaskService;
    @Autowired
    private ComYearService comYearService;
    @Autowired
    private ComProjectService comProjectService;
    @Autowired
    private CreateCodeUtil createCodeUtil;
    @Autowired
    private ComPersonService comPersonService;
    @Autowired
    private ComUnitService comUnitService;
    @Autowired
    private ComProjectAuditNoteService comProjectAuditNoteService;

    @Override
    protected void setCriteriaForQuery(ComProjectCheckQueryVO vo, QueryWrapper<ComProjectCheckQueryVO> criteria) {
        if (Objects.nonNull(vo.getCheckYear())) {
            criteria.eq("check_year", vo.getCheckYear());
        }
        if (Objects.nonNull(vo.getProjId())) {
            criteria.eq("proj_id", vo.getProjId());
        }
        if (Objects.nonNull(vo.getOtherResults())) {
            criteria.eq("other_results", vo.getOtherResults());
        }
        if (Objects.nonNull(vo.getWorkProgress())) {
            criteria.eq("work_progress", vo.getWorkProgress());
        }
        if (Objects.nonNull(vo.getApplyMoney())) {
            criteria.eq("apply_money", vo.getApplyMoney());
        }
        if (Objects.nonNull(vo.getUsingMoney())) {
            criteria.eq("using_money", vo.getUsingMoney());
        }
        if (Objects.nonNull(vo.getSurplusMoney())) {
            criteria.eq("surplus_money", vo.getSurplusMoney());
        }
        if (Objects.nonNull(vo.getMoneyInstructions())) {
            criteria.eq("money_instructions", vo.getMoneyInstructions());
        }
        if (Objects.nonNull(vo.getCheckState())) {
            switch (vo.getCheckState()) {
                case 1://未上报任务书
                    criteria.eq("check_state", CommonEnum.checkState.noSubmit.getCode());
                    break;
                case 2://返回修改任务书
                    criteria.ne("check_state", CommonEnum.checkState.noSubmit.getCode());
                    break;
                default:
                    criteria.eq("check_state", vo.getCheckState());
                    break;
            }
        }
        if (Objects.nonNull(vo.getProjName())) {
            criteria.like("proj_name", vo.getProjName());
        }
        if (Objects.nonNull(vo.getProjNo())) {
            criteria.like("proj_no", vo.getProjNo());
        }
        if (Objects.nonNull(vo.getAppUnitName())) {
            criteria.like("unit_name", vo.getAppUnitName());
        }
        if (Objects.nonNull(vo.getAppPersonName())) {
            criteria.like("person_name", vo.getAppPersonName());
        }
    }

    @Override
    public Pagination<ComProjectCheckDTO> getListByPage(ComProjectCheckQueryVO vo) {
        QueryWrapper criteria = new QueryWrapper();
        setCriteriaForQuery(vo, criteria);
//        long total = this.count(criteria);
        Page<ComProjectCheckQueryVO> page = new Page<>(vo.getPageIndex(), vo.getPageSize());
        List<ComProjectCheckDTO> dtoList = comProjectCheckDAO.getListByPage(page, criteria).getRecords();
        return new Pagination<>(dtoList, page.getTotal(), vo.getPageSize());
    }

    @Override
    public void updateState(String id, Integer state) {
        ComProjectCheck comProjectCheck = new ComProjectCheck();
        comProjectCheck.setId(id);
        comProjectCheck.setCheckState(state);
        this.update(comProjectCheck);
    }

    public ComProjectCheckDTO getCheckInfoById(String id) {
        ComProjectCheckDTO comProjectCheckDTO = this.dtoById(id);
        if (null == comProjectCheckDTO)
            throw new BusinessException("中期考核表不存在");
        ComProject comProject = comProjectService.entityById(comProjectCheckDTO.getProjId());
        ComPerson comPerson = comPersonService.entityById(comProject.getAppPersonId());
        ComUnit comUnit = comUnitService.entityById(comProject.getAppUnitId());
        comProjectCheckDTO.setProjName(comProject.getProjName());
        comProjectCheckDTO.setProjNo(comProject.getProjNo());
        comProjectCheckDTO.setStartDate(comProject.getStartDate());
        comProjectCheckDTO.setEndDate(comProject.getEndDate());
        comProjectCheckDTO.setAppPersonName(comPerson.getPersonName());
        comProjectCheckDTO.setAppUnitName(comUnit.getUnitName());
        List<String> results = comProjectResultsService.getArrayByObjectId(comProjectCheckDTO.getId());
        if (results.size() == 0)
//            results = comProjectResultsService.getList();
        comProjectCheckDTO.setResults(results);
        //审核记录列表
        List<ComProjectAuditNoteDTO> auditList = comProjectAuditNoteService.getListByObjectId(comProjectCheckDTO.getId());
        comProjectCheckDTO.setAuditList(auditList);
        return comProjectCheckDTO;
    }

    @Transactional
    public String saveAndReport(ComProjectCheckDTO comProjectCheckDTO, String unitId, String treeCode) {
        ComProjectCheck model = this.entityById(comProjectCheckDTO.getId());
        if (null == model)
            throw new BusinessException("中期考核表不存在或已上报");
        if (!model.getCheckState().equals(CommonEnum.checkState.noSubmit.getCode()) && !model.getCheckState().equals(CommonEnum.checkState.returnModify.getCode()))
            throw new BusinessException("中期考核表不存在或已上报");
        ComProjectCheck comProjectCheck = convert2Entity(comProjectCheckDTO);
        comProjectResultsService.insertList(comProjectCheckDTO.getResults(), comProjectCheck.getId());
        comProjectAuditService.report(comProjectCheckDTO.getCheckYear(), comProjectCheckDTO.getId(), 3, unitId, treeCode);
        comProjectCheck.setCheckState(CommonEnum.checkState.review.getCode());
        return this.update(comProjectCheck);
    }

    @Transactional
    @Override
    public String save(ComProjectCheckDTO comProjectCheckDTO) {
        ComProjectCheck comProjectCheck = convert2Entity(comProjectCheckDTO);
        comProjectResultsService.insertList(comProjectCheckDTO.getResults(), comProjectCheck.getId());
        return this.update(comProjectCheck);
    }

    @Override
    public void audit(ComProjectAudit comProjectAudit, String unitId, String treeCode) {
        // false 报上级或返回下一级  true报到最高级或返回个人
        int state = 0;
//        int state = comProjectAuditService.audit(comProjectAudit, treeCode,null);
        ComProjectCheck comProjectCheck = new ComProjectCheck();
        comProjectCheck.setId(comProjectAudit.getAuditObjectId());
        if (comProjectAudit.getAuditResult().equals(CommonEnum.auditResult.pass.getCode())) {
            if (state==0) {
                comProjectCheck.setCheckState(CommonEnum.checkState.pass.getCode());
            }
        } else if (comProjectAudit.getAuditResult().equals(CommonEnum.auditResult.returnModify.getCode())) {
            if (state==0)
                comProjectCheck.setCheckState(CommonEnum.checkState.returnModify.getCode());
        } else {
            comProjectCheck.setCheckState(CommonEnum.checkState.failed.getCode());
        }
        if (null != comProjectCheck.getCheckState())
            this.update(comProjectCheck);
    }

    @Override
    public void insertCheckListByTestId(String testId) {
        ComProjectTask test = ComProjectTaskService.entityById(testId);
        if (null == test)
            return;
        String checkYear = comYearService.getCheckYear(test.getReportYear());
        if (checkYear.equals(""))
            return;
        String[] arr = checkYear.split(",");
        ComProjectCheck model = new ComProjectCheck();
        model.setProjId(test.getProjId());
        List<ComProjectCheck> list = this.entityList(model);
        for (int i = 0; i < arr.length; i++) {
            if (createCodeUtil.ParseInt(arr[i])) {
                Integer year = Integer.parseInt(arr[i]);
                if (null != list && list.size() > 0) {
                    if (list.stream().filter(e -> e.getCheckYear().equals(year)).collect(Collectors.toList()).size() == 0) {
                        ComProjectCheck check = new ComProjectCheck();
                        check.setProjId(test.getProjId());
                        check.setCheckState(CommonEnum.checkState.noSubmit.getCode());
                        check.setCheckYear(year);
                        this.save(check);
                    }
                } else {
                    ComProjectCheck check = new ComProjectCheck();
                    check.setProjId(test.getProjId());
                    check.setCheckState(CommonEnum.checkState.noSubmit.getCode());
                    check.setCheckYear(year);
                    this.save(check);
                }
            }
        }
    }

    @Override
    public DataStatisticsDTO getCount(ComProjectCheckQueryVO e) {
        QueryWrapper criteria = new QueryWrapper();
        setCriteriaForQuery(e, criteria);
        return comProjectCheckDAO.getCount(criteria);
    }
}