package com.testor.module.threeframework.service.impl;

import com.testor.biz.sys.org.model.domain.SysOrg;
import com.testor.biz.sys.org.service.SysOrgService;
import com.testor.biz.sys.user.service.SysUserService;
import com.testor.common.constant.StatusEnum;
import com.testor.module.notice.model.domain.TSysFile;
import com.testor.module.notice.service.TSysFileService;
import com.testor.module.threeframework.dao.TThreeTimeDao;
import com.testor.module.threeframework.model.domain.TThreeTime;
import com.testor.module.threeframework.model.domain.TThreeTimeAuxiliary;
import com.testor.module.threeframework.model.dto.TThreeTimeAuxiliaryEditDTO;
import com.testor.module.threeframework.model.dto.TThreeTimeEditDTO;
import com.testor.module.threeframework.model.vo.TThreeTimeAuxiliaryVO;
import com.testor.module.threeframework.model.vo.TThreeTimeVO;
import com.testor.module.threeframework.service.TThreeTimeAuxiliaryService;
import com.testor.module.threeframework.service.TThreeTimeService;
import com.tongtech.tfw.backend.common.biz.models.BaseResponse;
import com.tongtech.tfw.backend.common.biz.models.BizGeneralResponse;
import com.tongtech.tfw.backend.common.models.supers.SuperServiceImpl;
import com.tongtech.tfw.backend.core.helper.IdHelper;
import com.tongtech.tfw.backend.core.helper.StringHelper;
import com.tongtech.tfw.backend.core.helper.TypeHelper;
import com.tongtech.tfw.backend.core.helper.bean.BeanHelper;
import org.apache.commons.lang3.ObjectUtils;
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 java.util.ArrayList;
import java.util.List;

/**
 * 三同时管理Service业务层处理
 *
 * @author testor-framework
 * @date 2022-09-15 17:16:20
 */
@Service
public class TThreeTimeServiceImpl extends SuperServiceImpl<TThreeTimeDao, TThreeTime> implements TThreeTimeService {
    @Autowired(required = false)
    private TThreeTimeDao tThreeTimeDao;

    @Autowired(required = false)
    private TThreeTimeAuxiliaryService tThreeTimeAuxiliaryService;

    @Autowired(required = false)
    private TSysFileService tSysFileService;

    @Autowired
    private SysOrgService sysOrgService;

    @Autowired
    private SysUserService sysUserService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public BaseResponse<TThreeTime> addEntity(TThreeTimeEditDTO addRequest) {
        BaseResponse<TThreeTime> baseResponse = new BaseResponse<>();
        String id = IdHelper.getId32bit();
        String serialNumber = String.valueOf(System.currentTimeMillis());
        addRequest.setSerialNumber(serialNumber);


        List<TThreeTimeAuxiliaryEditDTO> auxiliaryList = addRequest.getAuxiliaryList();
        List<TThreeTimeAuxiliary> tThreeTimeAuxiliaries = BeanHelper.listToList(auxiliaryList, TThreeTimeAuxiliary.class);
        for (TThreeTimeAuxiliary tThreeTimeAuxiliary : tThreeTimeAuxiliaries) {
            String idAuxiliary = IdHelper.getId32bit();
            tThreeTimeAuxiliary.setId(idAuxiliary);
            tThreeTimeAuxiliary.setParentId(id);
        }

        TThreeTime dataThreeTime = BeanHelper.beanToBean(addRequest, TThreeTime.class);
        dataThreeTime.setId(id);
        boolean result = save(dataThreeTime);
        boolean saveBatch = tThreeTimeAuxiliaryService.saveBatch(tThreeTimeAuxiliaries);
        if (result && saveBatch) {
            TThreeTime newEntity = new TThreeTime();
            newEntity.setId(id);
            baseResponse.setData(newEntity);
        } else {
            throw new RuntimeException("添加失败");
        }
        return baseResponse;
    }

    @Override
    public BaseResponse<List<TThreeTimeVO>> getThreeTime(String id) {
        BaseResponse<List<TThreeTimeVO>> baseResponse = new BaseResponse<>();
        if (StringHelper.isNotEmpty(id)) {
            TThreeTime data = getById(id);

            if (ObjectUtils.isEmpty(data)) {
                return baseResponse;
            }


            List<TThreeTimeVO> tThreeTimeVOS = new ArrayList<>();

            int planInt = Integer.parseInt(data.getPlan());
            for (int i = planInt; i > 0; i--) {

                TThreeTimeVO tThreeTimeVO = gettThreeTimeVO(data, i);
                List<TThreeTimeAuxiliaryVO> auxiliaryList = tThreeTimeVO.getAuxiliaryList();
                for (TThreeTimeAuxiliaryVO tThreeTimeAuxiliaryVO : auxiliaryList) {
                    String accessory = tThreeTimeAuxiliaryVO.getAccessory();
                    List<TSysFile> list = new ArrayList<>();
                    if(StringUtils.isNotBlank(accessory)){
                        String[] split = accessory.split(",");
                        for (String s : split) {
                            TSysFile tSysFile = tSysFileService.getById(s);
                            list.add(tSysFile);
                        }
                    }
                    tThreeTimeAuxiliaryVO.setTSysFileList(list);
                }
                tThreeTimeVOS.add(tThreeTimeVO);
            }

            baseResponse.setData(tThreeTimeVOS);
        }
        return baseResponse;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public BaseResponse<BizGeneralResponse> updateEntity(TThreeTimeEditDTO updateRequest) {
        BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();

        String id = updateRequest.getId();
//        String plan = updateRequest.getPlan();

        String plan = updateRequest.getAuxiliaryList().get(0).getPlan();
        List<TThreeTimeAuxiliary> threeTimeAuxiliaryByPlan = tThreeTimeAuxiliaryService.getThreeTimeAuxiliaryByPlan(id, plan);
        if (null != threeTimeAuxiliaryByPlan && threeTimeAuxiliaryByPlan.size() > 0) {
            // 表明存在，需要修改，或者删除

//            List<String> auxiliaryIds = threeTimeAuxiliaryByPlan.stream().map(TThreeTimeAuxiliary::getId).collect(Collectors.toList());
            threeTimeAuxiliaryByPlan.forEach(a -> a.setStatus(StatusEnum.DEACTIVATE.getCode()));
            // 修改原本已存在的信息状态
            boolean updateBatchById = tThreeTimeAuxiliaryService.updateBatchById(threeTimeAuxiliaryByPlan);
            if (!updateBatchById) {
                throw new RuntimeException("附件修改失败");
            }
        }

        // 具体信息走修改
        TThreeTime tThreeTime = BeanHelper.beanToBean(updateRequest, TThreeTime.class);
        boolean result = updateById(tThreeTime);

        List<TThreeTimeAuxiliaryEditDTO> auxiliaryList = updateRequest.getAuxiliaryList();
        List<TThreeTimeAuxiliary> tThreeTimeAuxiliaries = BeanHelper.listToList(auxiliaryList, TThreeTimeAuxiliary.class);
        for (TThreeTimeAuxiliary tThreeTimeAuxiliary : tThreeTimeAuxiliaries) {
            String idAuxiliary = IdHelper.getId32bit();
            tThreeTimeAuxiliary.setId(idAuxiliary);
            tThreeTimeAuxiliary.setParentId(id);
        }
        // 附件走新增
        boolean saveBatch = tThreeTimeAuxiliaryService.saveBatch(tThreeTimeAuxiliaries);
        if (!result || !saveBatch) {
            throw new RuntimeException("修改失败");
        }
        baseResponse.setData(BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
        return baseResponse;
    }

    private TThreeTimeVO gettThreeTimeVO(TThreeTime data, int i) {
        TThreeTimeVO tThreeTimeVO = new TThreeTimeVO();

        String id = data.getId();
        String plan = String.valueOf(i);
        tThreeTimeVO.setId(id);
        tThreeTimeVO.setPlan(plan);
        // 立项时间
        tThreeTimeVO.setProjectApprovalDate(data.getProjectApprovalDate());
//        SysUser createUser = sysUserService.getById(data.getCreateBy());
//        tThreeTimeVO.setCreateBy(createUser.getUserName());
        tThreeTimeVO.setCreateBy(data.getCreateBy());
        tThreeTimeVO.setCreateDate(data.getCreateDate());
//        SysUser updateUser = sysUserService.getById(data.getUpdateBy());
//        tThreeTimeVO.setUpdateBy(updateUser.getUserName());
        tThreeTimeVO.setUpdateBy(data.getUpdateBy());
        tThreeTimeVO.setUpdateDate(data.getUpdateDate());


        switch (i) {
            case 1:
                // 项目性质
                tThreeTimeVO.setProjectNature(data.getProjectNature());
                // 项目编号
                tThreeTimeVO.setSerialNumber(data.getSerialNumber());
                // 项目名称
                tThreeTimeVO.setName(data.getName());
                // 建设单位
                tThreeTimeVO.setOrgId(data.getOrgId());
                SysOrg org = sysOrgService.getById(data.getOrgId());
                tThreeTimeVO.setOrgName(org.getOrgName());
                // 项目简介
                tThreeTimeVO.setIntro(data.getIntro());
                // 安全预评价
                tThreeTimeVO.setSafetyEvaluation(data.getSafetyEvaluation());
                // 环境影响评价
                tThreeTimeVO.setEvlAppraisal(data.getEvlAppraisal());
                break;
            case 2:
                // 安全设施设计专篇
                tThreeTimeVO.setSafetyFacilities(data.getSafetyFacilities());
                // 环境保护设计专篇
                tThreeTimeVO.setEvlProtection(data.getEvlProtection());
                break;
            case 3:
                // 施工基本信息
                tThreeTimeVO.setConstruction(data.getConstruction());
                tThreeTimeVO.setDangerousProjectsState(data.getDangerousProjectsState());
                break;
            case 4:
                // 安全验收评价
                tThreeTimeVO.setSafetyAcceptance(data.getSafetyAcceptance());
                // 环保验收监测（调查）
                tThreeTimeVO.setEvlSurvey(data.getEvlSurvey());
                break;
            case 5:
                // 后评价
                tThreeTimeVO.setPostEvaluation(data.getPostEvaluation());
                break;
            default:
        }

        List<TThreeTimeAuxiliary> threeTimeAuxiliaryByPlan = tThreeTimeAuxiliaryService.getThreeTimeAuxiliaryByPlan(id, plan);
        List<TThreeTimeAuxiliaryVO> tThreeTimeAuxiliaryVOS = BeanHelper.listToList(threeTimeAuxiliaryByPlan, TThreeTimeAuxiliaryVO.class);
        tThreeTimeVO.setAuxiliaryList(tThreeTimeAuxiliaryVOS);
        return tThreeTimeVO;
    }
}
