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.ComProjectTaskDAO;
import com.yiboshi.science.entity.*;
import com.yiboshi.science.enumeration.CommonEnum;
import com.yiboshi.science.param.dto.*;
import com.yiboshi.science.param.query.ComProjectTaskQueryVO;
import com.yiboshi.science.service.*;
import com.yiboshi.science.utils.SystemSetKey;
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.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 任务书表 Service 实现类
 *
 * @author lkl
 * @version 2021-08-26
 */
@Service
public class ComProjectTaskServiceImpl extends BaseServiceImpl<ComProjectTaskDAO, ComProjectTaskQueryVO, ComProjectTaskDTO, ComProjectTask> implements ComProjectTaskService {
    @Autowired
    private ComProjectTaskDAO ComProjectTaskDAO;
    @Autowired
    private ComProjectMembersService comProjectMembersService;
    @Autowired
    private ComProjectBudgetService comProjectBudgetService;
    @Autowired
    private ComTaskTargetService ComTaskTargetService;
    @Autowired
    private ComProjectStageGoalService ComProjectStageGoalService;
    @Autowired
    private ComProjectService ComProjectService;
    @Autowired
    private ComPersonService comPersonService;
    @Autowired
    private ComUnitService comUnitService;
    @Autowired
    private ComProjectCooperativeUnitsService ComProjectCooperativeUnitsService;
    @Autowired
    private ComProjectAuditService comProjectAuditService;
    @Autowired
    private ComProjectAuditNoteService comProjectAuditNoteService;
    @Autowired
    private ComProjectCheckService comProjectCheckService;
    @Autowired
    private ComDownloadService comDownloadService;
    @Autowired
    private ComFileService comFileService;

    @Override
    protected void setCriteriaForQuery(ComProjectTaskQueryVO vo, QueryWrapper<ComProjectTaskQueryVO> criteria) {
        if (Objects.nonNull(vo.getProjId())) {
            criteria.eq("proj_id", vo.getProjId());
        }
        if (Objects.nonNull(vo.getReportYear())) {
            criteria.eq("c.report_year", vo.getReportYear());
        }
        if (Objects.nonNull(vo.getProjType())) {
            criteria.eq("proj_type", vo.getProjType());
        }
        if (Objects.nonNull(vo.getAppUnitId())) {
            criteria.eq("app_unit_id", vo.getAppUnitId());
        }
        if (Objects.nonNull(vo.getAppPersonId())) {
            criteria.eq("app_person_id", vo.getAppPersonId());
        }
        if (Objects.nonNull(vo.getStartDate())) {
            criteria.eq("start_date", vo.getStartDate());
        }
        if (Objects.nonNull(vo.getEndDate())) {
            criteria.eq("end_date", vo.getEndDate());
        }
        if (Objects.nonNull(vo.getProjState())) {
            criteria.eq("proj_state", vo.getProjState());
        }
        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());
        }
        if (Objects.nonNull(vo.getTaskState())) {
            switch (vo.getTaskState()) {
                case 1://未上报任务书
                    criteria.and(qw -> qw.in("task_state", CommonEnum.taskState.draft.getCode(),
                            CommonEnum.taskState.waitSubmit.getCode()).or().isNull("task_state"));
                    break;
                case 2://返回修改任务书
                    criteria.eq("task_state", CommonEnum.taskState.returnModify.getCode());
                    break;
                case 3://已上报任务书
                    criteria.in("task_state",
                            CommonEnum.taskState.review.getCode(),
                            CommonEnum.taskState.failed.getCode(),
                            CommonEnum.taskState.pass.getCode());
                    break;
                case 4://所有任务书
                    break;
                case 5://任务书
                    criteria.and(qw -> qw.in("task_state", CommonEnum.taskState.review.getCode()).or().isNull("test_state"));
                    break;
            }
        }
    }

    @Override
    public Pagination<ComProjectTaskDTO> getListByPage(ComProjectTaskQueryVO vo) {
        QueryWrapper criteria = new QueryWrapper();
        setCriteriaForQuery(vo, criteria);
        Page<ComProjectTaskQueryVO> page = new Page<>(vo.getPageIndex(), vo.getPageSize());
        List<ComProjectTaskDTO> dtoList = ComProjectTaskDAO.getListByPage(page, criteria).getRecords();
        return new Pagination<>(dtoList, page.getTotal(), vo.getPageSize());
    }

    public DataStatisticsDTO getCount(ComProjectTaskQueryVO e) {
        QueryWrapper criteria = new QueryWrapper();
        setCriteriaForQuery(e, criteria);
        return ComProjectTaskDAO.getCount(criteria);
    }

    public void updateState(String id, Integer state) {
        ComProjectTask ComProjectTask = new ComProjectTask();
        ComProjectTask.setId(id);
        ComProjectTask.setTaskState(state);
        this.update(ComProjectTask);
    }

    public ComProjectTaskDTO getTaskByProjId(String projId) {
        ComProjectTaskDTO dto = ComProjectTaskDAO.getByProjId(projId);
        //申报单位
        ComUnitDTO comUnitDTO = comUnitService.getUnitById(dto.getAppUnitId());
        if (null != comUnitDTO) {
            dto.setAppUnitName(comUnitDTO.getUnitName());
            if (Objects.isNull(dto.getOrganizationCode()))
                dto.setOrganizationCode(comUnitDTO.getOrganizationCode());
            if (Objects.isNull(dto.getUnitAddress()))
                dto.setUnitAddress(comUnitDTO.getUnitAddress());
            if (Objects.isNull(dto.getRegisteredAddress()))
                dto.setRegisteredAddress(comUnitDTO.getRegisteredAddress());
            if (Objects.isNull(dto.getPostCode()))
                dto.setPostCode(comUnitDTO.getPostCode());

            if (Objects.isNull(dto.getLegalPerson()))
                dto.setLegalPerson(comUnitDTO.getLegalPerson());
            if (Objects.isNull(dto.getWorkforce()))
                dto.setWorkforce(comUnitDTO.getWorkforce());
            if (Objects.isNull(dto.getSpecializedPersonnel()))
                dto.setSpecializedPersonnel(comUnitDTO.getSpecializedPersonnel());
            if (Objects.isNull(dto.getResearchPersonnel()))
                dto.setResearchPersonnel(comUnitDTO.getResearchPersonnel());

            if (Objects.isNull(dto.getDepositBank()))
                dto.setDepositBank(comUnitDTO.getDepositBank());
            if (Objects.isNull(dto.getBankAccount()))
                dto.setBankAccount(comUnitDTO.getBankAccount());
            if (Objects.isNull(dto.getDepositBankAddress()))
                dto.setDepositBankAddress(comUnitDTO.getDepositBankAddress());
            if (Objects.isNull(dto.getInterbankNumber()))
                dto.setInterbankNumber(comUnitDTO.getInterbankNumber());
        }
        // 申报人
        ComPersonDTO comPersonDTO = comPersonService.getPersonById(dto.getAppPersonId());
        if (null != comPersonDTO) {
            loadPersonInfo(dto, comPersonDTO);
        }
        return dto;
    }

    private void loadPersonInfo(ComProjectTaskDTO dto, ComPersonDTO comPersonDTO) {
        dto.setAppPersonName(comPersonDTO.getPersonName());
        dto.setCertId(comPersonDTO.getCertId());
        dto.setSex(comPersonDTO.getSex());
        dto.setBirthday(comPersonDTO.getBirthday());
        dto.setNationName(comPersonDTO.getNationName());
        dto.setDegreeName(comPersonDTO.getDegreeName());
        dto.setTitleName(comPersonDTO.getTitleName());
        dto.setDutyName(comPersonDTO.getDuty());
        dto.setSpecName(comPersonDTO.getSpecName());
        dto.setMobile(comPersonDTO.getMobile());
        dto.setEmail(comPersonDTO.getEmail());
    }

    @Transactional
    public String save(ComProjectTaskDTO dto) {
        if (dto.getTaskState().equals(CommonEnum.taskState.noWrite.getCode()))
            dto.setTaskState(CommonEnum.taskState.draft.getCode());
        String id = "";
        ComProjectTask task = new ComProjectTask();
        task.setProjId(dto.getProjId());
        task = this.getEntity(task);
        if (null == task) {
            task = convert2Entity(dto);
            id = this.insert(task);
        } else {
            task = convert2Entity(dto);
            id = this.update(task);
        }
        return id;
    }

    @Transactional
    public void report(ComProjectAudit model, String unitId, String treeCode) {
        ComProjectTask ComProjectTask = this.entityById(model.getAuditObjectId());
        if (null == ComProjectTask)
            throw new BusinessException("任务书不存在或已上报");
        if (!ComProjectTask.getTaskState().equals(CommonEnum.taskState.waitSubmit.getCode()) && !ComProjectTask.getTaskState().equals(CommonEnum.taskState.returnModify.getCode()))
            throw new BusinessException("任务书不存在或已上报");
        comProjectAuditService.report(ComProjectTask.getReportYear(), model.getAuditObjectId(), model.getAuditType(), unitId, treeCode);
        // 更新任务书状态
        this.updateState(model.getAuditObjectId(), CommonEnum.taskState.review.getCode());
    }

    @Transactional
    public void audit(ComProjectAudit comProjectAudit, String unitId, String treeCode) {
        // false 报上级或返回下一级  true报到最高级或返回个人
        int state = 0;
        ComProjectTask test = new ComProjectTask();
        test.setId(comProjectAudit.getAuditObjectId());
        if (comProjectAudit.getAuditResult().equals(CommonEnum.auditResult.pass.getCode())) {
            if (state == 0) {
                test.setTaskState(CommonEnum.taskState.pass.getCode());
                comProjectCheckService.insertCheckListByTestId(test.getId());
            }
        } else if (comProjectAudit.getAuditResult().equals(CommonEnum.auditResult.returnModify.getCode())) {
            if (state == 0)
                test.setTaskState(CommonEnum.taskState.returnModify.getCode());
        } else {
            test.setTaskState(CommonEnum.taskState.failed.getCode());
        }
        if (null != test.getTaskState())
            this.update(test);
    }

}