package com.artfess.yhxt.specialcheck.manager.impl;

import com.artfess.base.context.BaseContext;
import com.artfess.base.query.PageList;
import com.artfess.base.query.QueryFilter;
import com.artfess.base.query.QueryOP;
import com.artfess.sysConfig.persistence.manager.SysIdentityManager;
import com.artfess.uc.dao.UserDao;
import com.artfess.uc.manager.OrgManager;
import com.artfess.uc.manager.UserManager;
import com.artfess.uc.model.Org;
import com.artfess.uc.model.User;
import com.artfess.uc.util.ContextUtil;
import com.artfess.yhxt.basedata.manager.AccessoryManager;
import com.artfess.yhxt.basedata.model.BridgeInformation;
import com.artfess.yhxt.disease.manager.DiseaseManager;
import com.artfess.yhxt.disease.model.Disease;
import com.artfess.yhxt.specialcheck.model.SiteInspection;
import com.artfess.yhxt.specialcheck.dao.SiteInspectionDao;
import com.artfess.yhxt.specialcheck.manager.SiteInspectionManager;
import com.artfess.base.manager.impl.BaseManagerImpl;
import com.artfess.yhxt.specialcheck.vo.*;
import com.artfess.yhxt.task.manager.TaskWaitHandleManager;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 巡检表 服务实现类
 *
 * @author xzh
 * @company 阿特菲斯信息技术有限公司
 * @since 2021-08-12
 */
@Service
public class SiteInspectionManagerImpl extends BaseManagerImpl<SiteInspectionDao, SiteInspection> implements SiteInspectionManager {

    @Resource
    private DiseaseManager diseaseManager;

    @Resource
    private TaskWaitHandleManager taskWaitHandleManager;

    @Resource
    private BaseContext baseContext;
    @Resource
    private UserManager userManager;
    @Resource
    SysIdentityManager sysIdentityManager;
    @Resource
    AccessoryManager accessoryManager;

    @Override
    public PageList<SiteInspectionVo> querySiteInspection(QueryFilter<SiteInspection> queryFilter) {
        HashMap<String, Object> map = new HashMap<>();
        Map<String, Object> params = queryFilter.getParams();
        if (params != null) {
            map.putAll(params);
        }
        //IPage<SiteInspectionVo> results = baseMapper.querySiteInspection(convert2IPage(queryFilter.getPageBean()), map, convert2Wrapper(queryFilter, currentModelClass()));
        //查询多选
        IPage<SiteInspectionVo> results = baseMapper.querySiteInspectionList(convert2IPage(queryFilter.getPageBean()), map, convert2Wrapper(queryFilter, currentModelClass()));

        List<SiteInspectionVo> records = results.getRecords();


        LocalDate today = LocalDate.now();


        for (SiteInspectionVo record : records) {
            //巡检人ID RUMMAGER_ID_
            String rummagerId = record.getRummagerId();
            List<String> rummagerIds = Arrays.asList(rummagerId.split(","));
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.in("ID_",rummagerIds);
            List<User> users = userManager.getBaseMapper().selectList(userQueryWrapper);
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < users.size(); i++) {
                User user = users.get(i);
                String fullname = user.getFullname();
                if (i==0) {
                    sb.append(fullname);
                }else {
                    sb.append(","+fullname);
                }
            }
                record.setRummagerName(sb.toString());


            //记录人ID
            String recorderId = record.getRecorderId();
            if (StringUtils.isNotEmpty(recorderId) ) {
                User recorderUser = this.userManager.getById(recorderId);
                record.setRecorderName(recorderUser.getFullname());
            }
            record.setIsTimeout(0);
            if(null != record.getHandStatus()){

                Integer state = Integer.valueOf(record.getHandStatus());
                if(state < 3 || state ==7 ){
                    //判断时间
                    LocalDate patrolDate = record.getPatrolDate();
                   if(today.isAfter(patrolDate)){
                       record.setIsTimeout(1);
                   }
                }
            }
        }

            return new PageList<>(results);

        }


    @Override
    public SiteDiseaseVo getSiteInspectionById(String id) {
        //巡检病害vo
        SiteDiseaseVo siteDiseaseVo = this.baseMapper.getSiteInspectionById(id);
        //巡检vo
        SiteInspectionVo siteInspectionVo = siteDiseaseVo.getSiteInspectionVo();
        //巡检人ID RUMMAGER_ID_
        String rummagerId = siteInspectionVo.getRummagerId();
        if (StringUtils.isNotEmpty(rummagerId) ) {
            List<String> rummagerIds = Arrays.asList(rummagerId.split(","));
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.in("ID_", rummagerIds);
            List<User> users = userManager.getBaseMapper().selectList(userQueryWrapper);
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < users.size(); i++) {
                User user = users.get(i);
                String fullname = user.getFullname();
                if (i == 0) {
                    sb.append(fullname);
                } else {
                    sb.append("," + fullname);
                }
            }
            siteInspectionVo.setRummagerName(sb.toString());
        }

        //记录人ID
        String recorderId = siteInspectionVo.getRecorderId();
        if (StringUtils.isNotEmpty(recorderId) ) {
            User recorderUser = this.userManager.getById(recorderId);
            siteInspectionVo.setRecorderName(recorderUser.getFullname());
        }
        QueryWrapper<Disease> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("RELEVANCE_ID_",id);

        List<Disease> diseaseList = diseaseManager.getBaseMapper().selectList(queryWrapper);
        if (diseaseList.size()>0) {
            diseaseList.forEach(s -> {
                s.setAccessories(accessoryManager.getAccessoryBySourceId(s.getId()));
            });
        }
        siteDiseaseVo.setDiseaseList(diseaseList);
        return siteDiseaseVo;
    }

    @Override
    public PageList<DefaultBpmCheckOpinionVo> getSiteInspectionStatus(QueryFilter queryFilter) {
        IPage<DefaultBpmCheckOpinionVo> results = this.baseMapper.getSiteInspectionStatus(convert2IPage(queryFilter.getPageBean()), convert2Wrapper(queryFilter, currentModelClass()));
        return new PageList<DefaultBpmCheckOpinionVo>(results);
    }


    @Override
    public PageList<SiteInspectionTaskVo> getSiteInspectionTask(QueryFilter queryFilter) {
        IPage<SiteInspectionTaskVo> results = this.baseMapper.getSiteInspectionTask(convert2IPage(queryFilter.getPageBean()), convert2Wrapper(queryFilter, currentModelClass()));
        return new PageList<SiteInspectionTaskVo>(results);
    }

    @Override
    public SiteInspectionDiseaseVo saveSiteDiseaseVo(SiteInspectionDiseaseVo vo) {
        //巡检信息
        SiteInspection siteInspection = vo.getSiteInspection();
        //病害信息
        List<Disease> diseaseList = vo.getDiseaseList();
        //保存巡检信息
        this.saveOrUpdate(siteInspection);
        //根据巡检ID删除病害信息
        QueryWrapper<Disease> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("RELEVANCE_ID_", siteInspection.getId());
        diseaseManager.getBaseMapper().delete(queryWrapper);
        //保存病害信息
        this.diseaseManager.saveOrUpdateBatch(diseaseList);
        return vo;
    }

    @Override
    public SiteInspection saveSite(SiteInspection siteInspection) {
        if (StringUtils.isEmpty(siteInspection.getId())) {
            siteInspection.setHandStatus("1");


            String rummagerId = siteInspection.getRummagerId();
            String currentOrgId = ContextUtil.getCurrentOrgId(rummagerId);
            String currentOrgName = ContextUtil.getCurrentOrgName(rummagerId);
            //记录人
           // siteInspection.setRecorderId(rummagerId);
            //公司ID
//            if (StringUtils.isNotEmpty(currentOrgId)&& StringUtils.isNotEmpty(currentOrgName)) {
//                siteInspection.setCompanyId(currentOrgId);
//                siteInspection.setCompanyName(currentOrgName);
//            }
            sysIdentityManager.nextId("xcgdbh");
            this.create(siteInspection);
        } else {
            if (!"1".equals(siteInspection.getHandStatus())){
                return null;
            }
            this.update(siteInspection);
            SiteInspection updateVo = new SiteInspection();
            updateVo.setId("1");
            return updateVo;
        }
        //巡检id
        String id = siteInspection.getId();
        //业务数据类型
        String bizType = "1";

        this.taskWaitHandleManager.saveTask(siteInspection, bizType);
        return siteInspection;
    }

    @Override
    public void updateSitestatus(SiteTaskVo siteTaskVo) {
        String siteId = siteTaskVo.getSiteId();
        String status = siteTaskVo.getStatus();
        UpdateWrapper<SiteInspection> updateWrapper = new UpdateWrapper<SiteInspection>();
        if (status.equals("2")){
            updateWrapper.set("RECORDER_ID_",baseContext.getCurrentUserId());
            updateWrapper.set("RECORDER_ACCOUNT_",baseContext.getCurrentUserAccout());
        }
        updateWrapper.set("HAND_STATUS_", status);
        updateWrapper.eq("ID_", siteId);
        this.update(null, updateWrapper);
        this.taskWaitHandleManager.updateTask(siteTaskVo);
    }

    @Override
    public PageList<SiteInspectionVo> queryTaskHistory(QueryFilter<SiteInspection> queryFilter) {
        HashMap<String, Object> map = new HashMap<>();
        Map<String, Object> params = queryFilter.getParams();
        if (params != null) {
            map.putAll(params);
        }
        //登录者ID
        String userId = baseContext.getCurrentUserId();
        List<String> ids = this.baseMapper.selectBizId(userId);
        queryFilter.addFilter("a.ID_", ids, QueryOP.IN);
        IPage<SiteInspectionVo> results = this.baseMapper.queryTaskHistory(convert2IPage(queryFilter.getPageBean()), map, convert2Wrapper(queryFilter, currentModelClass()));
        List<SiteInspectionVo> records = results.getRecords();
        for (SiteInspectionVo record : records) {
            //巡检人ID RUMMAGER_ID_
            String rummagerId = record.getRummagerId();
            if (StringUtils.isNotEmpty(rummagerId)) {
                List<String> rummagerIds = Arrays.asList(rummagerId.split(","));
                QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
                userQueryWrapper.in("ID_", rummagerIds);
                List<User> users = userManager.getBaseMapper().selectList(userQueryWrapper);
                StringBuffer sb = new StringBuffer();
                for (int i = 0; i < users.size(); i++) {
                    User user = users.get(i);
                    String fullname = user.getFullname();
                    if (i == 0) {
                        sb.append(fullname);
                    } else {
                        sb.append("," + fullname);
                    }
                }
                record.setRummagerName(sb.toString());
            }


            //记录人ID
            String recorderId = record.getRecorderId();
            if (StringUtils.isNotEmpty(recorderId) ) {
                User recorderUser = this.userManager.getById(recorderId);
                record.setRecorderName(recorderUser.getFullname());
            }
        }
        return new PageList<>(results);
    }

    @Override
    public void exportSite(String ids) {
        if (StringUtils.isEmpty(ids)){
            throw new RuntimeException("请选择对应的巡检信息");
        }
        //巡检id
        List<String> siteIds = Arrays.asList(ids.split(","));
        for (String siteId : siteIds) {
            SiteInspection siteInspection = this.getById(siteId);
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet("日常巡检记录表");
            //公司
            HSSFRow row = sheet.createRow(0);
            HSSFCell cell = row.createCell(0);
            //
            HSSFRow row1 = sheet.createRow(1);
            HSSFCell cell1 = row1.createCell(0);
            cell1.setCellValue("日常巡查记录表");
            HSSFRow row2 = sheet.createRow(2);
            HSSFCell cell2 = row2.createCell(0);
            cell2.setCellValue("巡查中队:");
            HSSFCell cell3 = row2.createCell(3);
            cell3.setCellValue("日期:");


        }
    }

}
