package com.ruoyi.system.service.visit.impl;

import com.alibaba.fastjson2.JSONArray;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.TimeUtils;
import com.ruoyi.common.zqt.ZQTDateUtils;
import com.ruoyi.common.zqt.ZQTPageUtil;
import com.ruoyi.common.zqt.ZQTreeNode;
import com.ruoyi.system.domain.form.MdForm;
import com.ruoyi.system.domain.form.MdFormCategory;
import com.ruoyi.system.domain.form.MdFormTemplate;
import com.ruoyi.system.domain.grid.*;
import com.ruoyi.system.domain.grid.vo.GridWgBean;
import com.ruoyi.system.domain.system.SysOtherappAttachment;
import com.ruoyi.system.domain.system.SysOtherappAttachmentExample;
import com.ruoyi.system.domain.system.enums.AttachEnums;
import com.ruoyi.system.domain.task.TkCommonTask;
import com.ruoyi.system.domain.task.TkCommonTaskExample;
import com.ruoyi.system.domain.visit.*;
import com.ruoyi.system.domain.visit.ext.VisitPlanExt;
import com.ruoyi.system.domain.visit.ext.VisitPlanObjExt;
import com.ruoyi.system.domain.visit.ext.VisitPlanTaskExt;
import com.ruoyi.system.domain.visit.vo.VisitPlanRate;
import com.ruoyi.system.domain.visit.vo.VisitPlanTaskSearchParam;
import com.ruoyi.system.listener.MyBaseService;
import com.ruoyi.system.mapper.task.TkCommonTaskMapper;
import com.ruoyi.system.mapper.visit.*;
import com.ruoyi.system.service.BaseServiceImpl;
import com.ruoyi.system.service.form.FormManager;
import com.ruoyi.system.service.form.MdFormCategoryService;
import com.ruoyi.system.service.form.MdFormService;
import com.ruoyi.system.service.form.MdFormTemplateService;
import com.ruoyi.system.service.grid.GridRegionFacadeService;
import com.ruoyi.system.service.grid.GridRegionService;
import com.ruoyi.system.service.grid.GridRegionUserService;
import com.ruoyi.system.service.other.BsCommonService;
import com.ruoyi.system.service.system.SysOtherappAttachmentService;
import com.ruoyi.system.service.visit.VisitPlanService;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.util.CollectionUtils;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Cesar
 * @date ${cTime}
 * @desc VisitPlanService实现
 */
@Service
@MyBaseService
public class VisitPlanServiceImpl extends BaseServiceImpl<VisitPlanMapper, VisitPlan, VisitPlanExample> implements VisitPlanService {

    private static final Logger LOGGER = LoggerFactory.getLogger(VisitPlanServiceImpl.class);

    @Autowired
    VisitPlanMapper visitPlanMapper;
    @Autowired
    VisitPlanTaskMapper visitPlanTaskMapper;
    @Autowired
    VisitPlanTaskExtMapper visitPlanTaskExtMapper;
    @Autowired
    VisitPlanObjExtMapper visitPlanObjExtMapper;
    @Autowired
    VisitPlanObjMapper visitPlanObjMapper;
    @Autowired
    VisitPlanUserExtMapper visitPlanUserExtMapper;
    @Autowired
    VisitPlanUserMapper visitPlanUserMapper;
    @Autowired
    GridRegionUserService gridRegionUserService;
    @Autowired
    SysOtherappAttachmentService sysOtherappAttachmentService;
    @Autowired
    GridRegionService gridRegionService;
    @Autowired
    TkCommonTaskMapper tkCommonTaskMapper;
    @Autowired
    BsCommonService bsCommonService;
    @Autowired
    VisitFreeInterviewMapper visitFreeInterviewMapper;

    @Autowired
    private GridRegionFacadeService gridRegionFacadeService;

    @Autowired
    private MdFormService mdFormService;

    @Autowired
    private FormManager formManager;

    @Autowired
    private MdFormCategoryService mdFormCategoryService;

    @Autowired
    private MdFormTemplateService mdFormTemplateService;

    @Override
    public PageInfo<VisitPlanExt> selectByPage(int pageNum, int pageSize, String planTitle, String planType, String planTime, String planObjType, String planFl) {
        VisitPlanExample example = new VisitPlanExample();
        VisitPlanExample.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(planFl)) {
            criteria.andPlanFlEqualTo(planFl);
        }
        if (StringUtils.isNotBlank(planTitle)) {
            criteria.andPlanTitleLike("%" + planTitle + "%");
        }
        if (StringUtils.isNotBlank(planType)) {
            criteria.andPlanTypeEqualTo(planType);
        }
        if (StringUtils.isNotBlank(planTime)) {
            criteria.andPlanTimeEqualTo(planTime);
        }
        if (StringUtils.isNotBlank(planObjType)) {
            criteria.andPlanObjTypeEqualTo(planObjType);
        }
        example.setOrderByClause(" create_time desc");
        PageHelper.startPage(pageNum, pageSize);

        List<VisitPlan> list = visitPlanMapper.selectByExampleWithBLOBs(example);
        int count = (int) visitPlanMapper.countByExample(example);
        List<VisitPlanExt> resultList = new ArrayList<VisitPlanExt>();

        for (VisitPlan wszfPlan : list) {
            VisitPlanExt wszfPlanExt = new VisitPlanExt();
            DecimalFormat df = new DecimalFormat("######0.00");
            VisitPlanTaskExample allTaskExample = new VisitPlanTaskExample();
            VisitPlanTaskExample endTaskExample = new VisitPlanTaskExample();
            allTaskExample.createCriteria().andPlanIdEqualTo(wszfPlan.getId());
            endTaskExample.createCriteria().andPlanIdEqualTo(wszfPlan.getId()).andPlanTaskStatusEqualTo("1");//已走访

            double allCount = (double) visitPlanTaskMapper.countByExample(allTaskExample);
            double endCount = (double) visitPlanTaskMapper.countByExample(endTaskExample);
            BeanUtils.copyProperties(wszfPlan, wszfPlanExt);
            if (endCount == 0) {
                wszfPlanExt.setWcl(df.format(0) + "%");
            } else {
                wszfPlanExt.setWcl(df.format(((endCount / allCount) * 100)) + "%");
            }
            wszfPlanExt.setPlanTypeName(bsCommonService.getName(wszfPlan.getPlanType()));
            resultList.add(wszfPlanExt);
        }
        PageInfo<VisitPlanExt> pageInfo = new PageInfo<>(resultList);
        return ZQTPageUtil.build(pageInfo, pageNum, pageSize, count);
    }

    @Override
    @Transactional
    public void save(VisitPlanExt wszfPlanExt) {
        String uuid = UUID.randomUUID().toString();
        //网格员
        List<GridRegionUser> regionUserList = gridRegionFacadeService.getRegionUserListForList(wszfPlanExt.getWgCodeList());
        if(CollectionUtils.isEmpty(regionUserList)){
            throw new ServiceException("该网格下没有网格员！");
        }
        wszfPlanExt.setIsValid("1");
        if(StringUtils.isNotBlank(wszfPlanExt.getTemplateId())){
            String formId = formManager.saveFormTemplateWithWST(wszfPlanExt.getTemplateId(), wszfPlanExt.getCreateBy());
            wszfPlanExt.setFormId(formId);
        }
        //判断保存还是发布
        if ("1".equals(wszfPlanExt.getPlanStatus())) {//草稿
            wszfPlanExt.setId(uuid);
            wszfPlanExt.setCreateTime(new Date());
            visitPlanMapper.insertSelective(wszfPlanExt);

            //走访网格员中间表
            List<VisitPlanUser> planUserList = new ArrayList<>();
            regionUserList.forEach(wszfPlanUser -> {
                VisitPlanUser visitPlanUser = new VisitPlanUser();
                visitPlanUser.setId(UUID.randomUUID().toString());
                visitPlanUser.setPlanUserName(wszfPlanUser.getYlzd1());
                visitPlanUser.setUseid(wszfPlanUser.getUserId());
                visitPlanUser.setWgCode(wszfPlanUser.getWgId());
                visitPlanUser.setPlanId(uuid);
                visitPlanUser.setCreateTime(new Date());
                visitPlanUser.setCreateBy(wszfPlanExt.getCreateBy());
                visitPlanUser.setIsValid("1");
                planUserList.add(visitPlanUser);
            });
            visitPlanUserExtMapper.insertForList(planUserList);

            //走访对象中间表
            List<VisitPlanObjExt> wszfPlanObjList = wszfPlanExt.getWszfPlanObjList();
            wszfPlanObjList.forEach(wszfPlanObj -> {
                wszfPlanObj.setId(UUID.randomUUID().toString());
                wszfPlanObj.setPlanId(uuid);
                wszfPlanObj.setCreateTime(new Date());
                wszfPlanObj.setCreateBy(wszfPlanExt.getCreateBy());
                wszfPlanObj.setIsValid("1");
            });
            visitPlanObjExtMapper.insertForList(wszfPlanObjList);
        } else {//发布 状态先改为发布中 新增成功后再改为已发布
            wszfPlanExt.setPlanStatus("3");//发布中
            wszfPlanExt.setId(uuid);
            wszfPlanExt.setCreateTime(new Date());
            visitPlanMapper.insertSelective(wszfPlanExt);

            //走访网格员中间表
            List<VisitPlanUser> planUserList = new ArrayList<>();
            regionUserList.forEach(wszfPlanUser -> {
                VisitPlanUser visitPlanUser = new VisitPlanUser();
                visitPlanUser.setId(UUID.randomUUID().toString());
                visitPlanUser.setPlanUserName(wszfPlanUser.getYlzd1());
                visitPlanUser.setUseid(wszfPlanUser.getUserId());
                visitPlanUser.setWgCode(wszfPlanUser.getWgId());
                visitPlanUser.setPlanId(uuid);
                visitPlanUser.setCreateTime(new Date());
                visitPlanUser.setCreateBy(wszfPlanExt.getCreateBy());
                visitPlanUser.setIsValid("1");
                planUserList.add(visitPlanUser);
            });
            visitPlanUserExtMapper.insertForList(planUserList);

            List<VisitPlanObjExt> wszfPlanObjList = wszfPlanExt.getWszfPlanObjList();
            List<VisitPlanTask> planTaskList = new ArrayList<VisitPlanTask>();


            wszfPlanObjList.forEach(wszfPlanObj -> {
                //走访对象中间表
                String objId = UUID.randomUUID().toString();
                wszfPlanObj.setId(objId);
                wszfPlanObj.setPlanId(uuid);
                wszfPlanObj.setCreateTime(new Date());
                wszfPlanObj.setCreateBy(wszfPlanExt.getCreateBy());
                wszfPlanObj.setIsValid("1");

                //任务表
                VisitPlanTask planTask = new VisitPlanTask();
                planTask.setId(UUID.randomUUID().toString());
                planTask.setCreateTime(new Date());
                planTask.setCreateBy(wszfPlanExt.getCreateBy());
                if(StringUtils.isNotBlank(wszfPlanExt.getFormId())){
                    planTask.setYlzd2(wszfPlanExt.getFormId());
                }
                planTask.setPlanId(uuid);
                planTask.setObjWgCode(wszfPlanObj.getWgCode());
                planTask.setVisitPlanObjId(objId);
                planTask.setObjId(wszfPlanObj.getObjId());
                planTask.setObjName(wszfPlanObj.getObjName());
                planTask.setObjType(wszfPlanObj.getObjType());
                planTask.setObjNumber(wszfPlanObj.getObjNumber());
                planTask.setObjUserName(wszfPlanObj.getObjUserName());
                planTask.setPlanTaskStatus("2");
                planTask.setIsValid("1");

                wszfPlanObj.setCreateTime(new Date());

                //根据地块查出网格员
                Optional<GridRegionUser> planUser = regionUserList.stream().filter(user -> Objects.equals(user.getWgId(), wszfPlanObj.getWgCode().substring(0, wszfPlanObj.getWgCode().length() - 3))).findFirst();
                if (planUser.isPresent()) {
                    planTask.setVisitPlanUserId(planUser.get().getUserId());
                    planTask.setUrserId(planUser.get().getUserId());
                    planTask.setWgyCode(planUser.get().getWgId());
                    planTask.setWgyName(planUser.get().getYlzd1());
                    planTaskList.add(planTask);
                }
            });
            visitPlanObjExtMapper.insertForList(wszfPlanObjList);//走访对象中间表

            if (visitPlanTaskExtMapper.insertForList(planTaskList) != 0) {//批量新增成功后 修改计划表状态
                wszfPlanExt.setPlanStatus("2");
                wszfPlanExt.setUpdateTime(new Date());
                visitPlanMapper.updateByPrimaryKey(wszfPlanExt);
            }

        }

        //附件
        if (!CollectionUtils.isEmpty(wszfPlanExt.getOtherappAttachments())) {
            for (SysOtherappAttachment attachment : wszfPlanExt.getOtherappAttachments()) {
                attachment.setAttachType(AttachEnums.AttachType.PLAN.name());
                attachment.setBusinessId(uuid);
                attachment.setValid(Byte.valueOf("1"));
                sysOtherappAttachmentService.insertSelective(attachment);
            }
        }
    }

    @Override
    @Transactional
    public void update(VisitPlanExt wszfPlanExt) {
        //有templateId变化，表单变化
        if(StringUtils.isNotBlank(wszfPlanExt.getTemplateId())){
            VisitPlan visitPlan = visitPlanMapper.selectByPrimaryKey(wszfPlanExt.getId());
            if(!visitPlan.getTemplateId().equals(wszfPlanExt.getTemplateId())){
                String formId = formManager.saveFormTemplateWithWST(wszfPlanExt.getTemplateId(), wszfPlanExt.getCreateBy());
                wszfPlanExt.setFormId(formId);
            }
        }
        if(CollectionUtils.isEmpty(wszfPlanExt.getWgCodeList())){
            //没有传wgList,代表网格员和obj信息没有变化
            if (!"1".equals(wszfPlanExt.getPlanStatus())) {
                wszfPlanExt.setPlanStatus("3");//发布中
            }
            wszfPlanExt.setUpdateTime(new Date());
            visitPlanMapper.updateByPrimaryKeySelective(wszfPlanExt);
        }else{
            //网格员
            List<GridRegionUser> regionUserList = gridRegionFacadeService.getRegionUserListForList(wszfPlanExt.getWgCodeList());
            if(CollectionUtils.isEmpty(regionUserList)){
                throw new ServiceException("该网格下没有网格员！");
            }
            if (StringUtils.isNotEmpty(wszfPlanExt.getId())) {
                //先删除两张中间表的相关数据
                VisitPlanObjExample objMapper = new VisitPlanObjExample();
                VisitPlanUserExample userExample = new VisitPlanUserExample();
                objMapper.createCriteria().andPlanIdEqualTo(wszfPlanExt.getId());
                userExample.createCriteria().andPlanIdEqualTo(wszfPlanExt.getId());
                visitPlanObjMapper.deleteByExample(objMapper);
                visitPlanUserMapper.deleteByExample(userExample);
                //判断保存还是发布
                if ("1".equals(wszfPlanExt.getPlanStatus())) {//草稿
                    wszfPlanExt.setUpdateTime(new Date());
                    visitPlanMapper.updateByPrimaryKeySelective(wszfPlanExt);

                    //走访网格员中间表
                    List<VisitPlanUser> planUserList = new ArrayList<>();
                    regionUserList.forEach(wszfPlanUser -> {
                        VisitPlanUser visitPlanUser = new VisitPlanUser();
                        visitPlanUser.setId(UUID.randomUUID().toString());
                        visitPlanUser.setPlanUserName(wszfPlanUser.getYlzd1());
                        visitPlanUser.setUseid(wszfPlanUser.getUserId());
                        visitPlanUser.setWgCode(wszfPlanUser.getWgId());
                        visitPlanUser.setPlanId(wszfPlanExt.getId());
                        visitPlanUser.setCreateTime(new Date());
                        visitPlanUser.setCreateBy(wszfPlanExt.getCreateBy());
                        visitPlanUser.setIsValid("1");
                        planUserList.add(visitPlanUser);
                    });
                    visitPlanUserExtMapper.insertForList(planUserList);

                    //走访对象中间表
                    List<VisitPlanObjExt> wszfPlanObjList = wszfPlanExt.getWszfPlanObjList();
                    wszfPlanObjList.forEach(wszfPlanObj -> {
                        wszfPlanObj.setId(UUID.randomUUID().toString());
                        wszfPlanObj.setPlanId(wszfPlanExt.getId());
                        wszfPlanObj.setCreateTime(new Date());
                        wszfPlanObj.setCreateBy(wszfPlanExt.getCreateBy());
                        wszfPlanObj.setIsValid("1");
                    });
                    visitPlanObjExtMapper.insertForList(wszfPlanObjList);
                } else {//发布 状态先改为发布中 新增成功后再改为已发布
                    wszfPlanExt.setPlanStatus("3");//发布中
                    wszfPlanExt.setUpdateTime(new Date());
                    visitPlanMapper.updateByPrimaryKeySelective(wszfPlanExt);

                    //走访网格员中间表
                    List<VisitPlanUser> planUserList = new ArrayList<>();
                    regionUserList.forEach(wszfPlanUser -> {
                        VisitPlanUser visitPlanUser = new VisitPlanUser();
                        visitPlanUser.setId(UUID.randomUUID().toString());
                        visitPlanUser.setPlanUserName(wszfPlanUser.getYlzd1());
                        visitPlanUser.setUseid(wszfPlanUser.getUserId());
                        visitPlanUser.setWgCode(wszfPlanUser.getWgId());
                        visitPlanUser.setPlanId(wszfPlanExt.getId());
                        visitPlanUser.setCreateTime(new Date());
                        visitPlanUser.setCreateBy(wszfPlanExt.getCreateBy());
                        visitPlanUser.setIsValid("1");
                        planUserList.add(visitPlanUser);
                    });
                    visitPlanUserExtMapper.insertForList(planUserList);

                    List<VisitPlanObjExt> wszfPlanObjList = wszfPlanExt.getWszfPlanObjList();
                    List<VisitPlanTask> planTaskList = new ArrayList<VisitPlanTask>();


                    wszfPlanObjList.forEach(wszfPlanObj -> {
                        //走访对象中间表
                        String objId = UUID.randomUUID().toString();
                        wszfPlanObj.setId(objId);
                        wszfPlanObj.setPlanId(wszfPlanExt.getId());
                        wszfPlanObj.setCreateTime(new Date());
                        wszfPlanObj.setCreateBy(wszfPlanExt.getCreateBy());
                        wszfPlanObj.setIsValid("1");

                        //任务表
                        VisitPlanTask planTask = new VisitPlanTask();
                        planTask.setId(UUID.randomUUID().toString());
                        planTask.setCreateTime(new Date());
                        planTask.setCreateBy(wszfPlanExt.getCreateBy());
                        planTask.setPlanId(wszfPlanExt.getId());
                        if(StringUtils.isNotBlank(wszfPlanExt.getFormId())){
                            planTask.setYlzd2(wszfPlanExt.getFormId());
                        }
                        planTask.setObjWgCode(wszfPlanObj.getWgCode());
                        planTask.setVisitPlanObjId(objId);
                        planTask.setObjId(wszfPlanObj.getObjId());
                        planTask.setObjName(wszfPlanObj.getObjName());
                        planTask.setObjType(wszfPlanObj.getObjType());
                        planTask.setObjNumber(wszfPlanObj.getObjNumber());
                        planTask.setObjUserName(wszfPlanObj.getObjUserName());
                        planTask.setPlanTaskStatus("2");
                        planTask.setIsValid("1");

                        wszfPlanObj.setCreateTime(new Date());

                        //根据地块查出网格员
                        Optional<GridRegionUser> planUser = regionUserList.stream().filter(user -> Objects.equals(user.getWgId(), wszfPlanObj.getWgCode().substring(0, wszfPlanObj.getWgCode().length() - 3))).findFirst();
                        if (planUser.isPresent()) {
                            planTask.setVisitPlanUserId(planUser.get().getUserId());
                            planTask.setUrserId(planUser.get().getUserId());
                            planTask.setWgyCode(planUser.get().getWgId());
                            planTask.setWgyName(planUser.get().getYlzd1());
                            planTaskList.add(planTask);
                        }
                    });
                    visitPlanObjExtMapper.insertForList(wszfPlanObjList);//走访对象中间表

                    if (visitPlanTaskExtMapper.insertForList(planTaskList) != 0) {//批量新增成功后 修改计划表状态
                        wszfPlanExt.setPlanStatus("2");
                        wszfPlanExt.setUpdateTime(new Date());
                        visitPlanMapper.updateByPrimaryKeySelective(wszfPlanExt);
                    }

                }
            }
        }
        //附件
        SysOtherappAttachmentExample example = new SysOtherappAttachmentExample();
        example.createCriteria().andBusinessIdEqualTo(wszfPlanExt.getId()).andAttachTypeEqualTo(AttachEnums.AttachType.PLAN.name());
        sysOtherappAttachmentService.deleteByExample(example);
        if (!CollectionUtils.isEmpty(wszfPlanExt.getOtherappAttachments())) {
            for (SysOtherappAttachment attachment : wszfPlanExt.getOtherappAttachments()) {
                attachment.setAttachType(AttachEnums.AttachType.PLAN.name());
                attachment.setBusinessId(wszfPlanExt.getId());
                attachment.setValid(Byte.valueOf("1"));
                sysOtherappAttachmentService.insertSelective(attachment);
            }
        }
    }

    @Override
    public void updateTaskRecordId(String planTaskId, String recordId) {
        VisitPlanTask visitPlanTask = visitPlanTaskMapper.selectByPrimaryKey(planTaskId);
        if(visitPlanTask != null){
            visitPlanTask.setYlzd3(recordId);
            visitPlanTask.setPlanTaskStatus("1");
            visitPlanTaskMapper.updateByPrimaryKeySelective(visitPlanTask);
        }
    }

    @Override
    public void delete(String id) {
        //删除任务表
        VisitPlanTaskExample planTaskExample = new VisitPlanTaskExample();
        planTaskExample.createCriteria().andPlanIdEqualTo(id);
        visitPlanTaskMapper.deleteByExample(planTaskExample);
        //删除对象中间表
        VisitPlanObjExample planObjExample = new VisitPlanObjExample();
        planObjExample.createCriteria().andPlanIdEqualTo(id);
        visitPlanObjMapper.deleteByExample(planObjExample);
//        删除网格员中间表
        VisitPlanUserExample planUserExample = new VisitPlanUserExample();
        planUserExample.createCriteria().andPlanIdEqualTo(id);
        visitPlanUserMapper.deleteByExample(planUserExample);
//        删除计划表
        visitPlanMapper.deleteByPrimaryKey(id);
    }

    @Override
    public VisitPlanExt info(String id) {
        VisitPlanExt wszfPlanExt = new VisitPlanExt();
        try {
            //计划表
            VisitPlan wszfPlan = visitPlanMapper.selectByPrimaryKey(id);
            //对象中间表
            VisitPlanObjExample planObjExample = new VisitPlanObjExample();
            planObjExample.createCriteria().andPlanIdEqualTo(id);
            List<VisitPlanObj> wszfPlanObjs = visitPlanObjMapper.selectByExample(planObjExample);
            //网格员中间表
            VisitPlanUserExample planUserExample = new VisitPlanUserExample();
            planUserExample.createCriteria().andPlanIdEqualTo(id);
            List<VisitPlanUser> wszfPlanUsers = visitPlanUserMapper.selectByExample(planUserExample);
            //附件表
            SysOtherappAttachmentExample attachmentExample = new SysOtherappAttachmentExample();
            attachmentExample.createCriteria().andBusinessIdEqualTo(id).andAttachTypeEqualTo(AttachEnums.AttachType.PLAN.name());
            List<SysOtherappAttachment> attachmentList = sysOtherappAttachmentService.selectByExample(attachmentExample);

            List<VisitPlanObjExt> wszfPlanExtObjList = new ArrayList<VisitPlanObjExt>();
            wszfPlanObjs.forEach(wszfPlanObj -> {
                VisitPlanObjExt planExtObj = new VisitPlanObjExt();
                try {
                    PropertyUtils.copyProperties(planExtObj, wszfPlanObj);
                    wszfPlanExtObjList.add(planExtObj);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });


            PropertyUtils.copyProperties(wszfPlanExt, wszfPlan);

            //走访表单表
            if(StringUtils.isNotBlank(wszfPlanExt.getFormId())){
                MdForm mdForm = mdFormService.selectByPrimaryKey(wszfPlanExt.getFormId());
                wszfPlanExt.setFormName(mdForm == null?"":mdForm.getName());
            }
            if(StringUtils.isNotBlank(wszfPlanExt.getTemplateId())){
                MdFormTemplate mdFormTemplate = mdFormTemplateService.selectByPrimaryKey(wszfPlanExt.getTemplateId());
                wszfPlanExt.setTemplateName(mdFormTemplate == null?"":mdFormTemplate.getName());
                if(mdFormTemplate != null && StringUtils.isNotBlank(mdFormTemplate.getCategoryId())){
                    wszfPlanExt.setCategoryId(mdFormTemplate.getCategoryId());
                    MdFormCategory mdFormCategory = mdFormCategoryService.selectByPrimaryKey(mdFormTemplate.getCategoryId());
                    wszfPlanExt.setCategoryName(mdFormCategory == null?"":mdFormCategory.getName());
                }
            }
            wszfPlanExt.setWszfPlanObjList(wszfPlanExtObjList);
            wszfPlanExt.setVisitPlanUserList(wszfPlanUsers);
            wszfPlanExt.setOtherappAttachments(attachmentList);
            wszfPlanExt.setPlanTypeName(bsCommonService.getName(wszfPlan.getPlanType()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return wszfPlanExt;
    }

    @Override
    public PageInfo<VisitPlanTaskExt> planTaskPage(int pageNum, int pageSize, String planId, String planTaskStatus, String objWgCode, String startTime, String endTime, String objType, String objName) {
        VisitPlanTaskExample example = new VisitPlanTaskExample();
        VisitPlanTaskExample.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(planId)) {
            criteria.andPlanIdEqualTo(planId);
        }
        if (StringUtils.isNotBlank(planTaskStatus)) {
            criteria.andPlanTaskStatusEqualTo(planTaskStatus);
        }
        if (StringUtils.isNotBlank(objWgCode)) {
            criteria.andObjWgCodeLike(objWgCode + "%");
        }
        if (StringUtils.isNotBlank(objName)) {
            criteria.andObjNameLike("%" + objName + "%");
        }
        if (StringUtils.isNotBlank(objType)) {
            criteria.andObjTypeEqualTo(objType);
        }
        if (StringUtils.isNotBlank(startTime)) {
            criteria.andUpdateTimeGreaterThanOrEqualTo(ZQTDateUtils.getTodayStartTime(ZQTDateUtils.getPastDate(startTime, "yyyy-MM-dd")));
        }
        if (StringUtils.isNotBlank(endTime)) {
            criteria.andUpdateTimeLessThanOrEqualTo(ZQTDateUtils.getTodayEndTime(ZQTDateUtils.getPastDate(endTime, "yyyy-MM-dd")));
        }
        PageHelper.startPage(pageNum, pageSize);
        List<VisitPlanTask> wszfPlanTasks = visitPlanTaskMapper.selectByExampleWithBLOBs(example);
        int count = (int) visitPlanTaskMapper.countByExample(example);
        List<VisitPlanTaskExt> wszfPlanTaskExtList = new ArrayList<VisitPlanTaskExt>();
        wszfPlanTasks.forEach(wszfPlanTask -> {
            VisitPlanTaskExt planTaskExt = new VisitPlanTaskExt();
            try {
                PropertyUtils.copyProperties(planTaskExt, wszfPlanTask);
                if (StringUtils.isNotEmpty(planTaskExt.getTaskId())) {

                    TkCommonTask tkCommonTask = tkCommonTaskMapper.selectByPrimaryKey(planTaskExt.getTaskId());
                    planTaskExt.setTkId(tkCommonTask.getTkId());
                    planTaskExt.setTkStatus(tkCommonTask.getTkStatus() == 50 ? "已完成" : "未完成");

                }
                GridRegionExample wgxxbExample = new GridRegionExample();
                wgxxbExample.createCriteria().andWgCodeEqualTo(planTaskExt.getObjWgCode());
                List<GridRegion> bsWgxxbList = gridRegionService.selectByExample(wgxxbExample);
                GridRegion bsWgxxb = bsWgxxbList.get(0);
                planTaskExt.setWgName(bsWgxxb.getWgName());//地块名称

                VisitPlan wszfPlan = visitPlanMapper.selectByPrimaryKey(wszfPlanTask.getPlanId());
                planTaskExt.setPlanTitle(wszfPlan.getPlanTitle());

                //走访表单表
                if(StringUtils.isNotBlank(wszfPlan.getFormId())){
                    MdForm mdForm = mdFormService.selectByPrimaryKey(wszfPlan.getFormId());
                    planTaskExt.setFormName(mdForm == null?"":mdForm.getName());
                }

                //附件
                SysOtherappAttachmentExample attachmentExample = new SysOtherappAttachmentExample();
                attachmentExample.createCriteria().andBusinessIdEqualTo(wszfPlanTask.getId());
                List<SysOtherappAttachment> attachmentList = sysOtherappAttachmentService.selectByExample(attachmentExample);
                planTaskExt.setOtherappAttachments(attachmentList);


                wszfPlanTaskExtList.add(planTaskExt);
            } catch (Exception e) {
                e.printStackTrace();
            }

        });


        PageInfo<VisitPlanTaskExt> pageInfo = new PageInfo<>(wszfPlanTaskExtList);
        return ZQTPageUtil.build(pageInfo, pageNum, pageSize, count);
    }

    @Override
    public ZQTreeNode getPlanWgTree(String planId) {
        VisitPlanObjExample objExample = new VisitPlanObjExample();
        objExample.createCriteria().andPlanIdEqualTo(planId);
        List<VisitPlanObj> planObjList = visitPlanObjMapper.selectByExample(objExample);
        List<String> fourCodeList = planObjList.stream().map(VisitPlanObj::getWgCode).collect(Collectors.toList());

        //地块
        GridRegionExample fourWgExample = new GridRegionExample();
        fourWgExample.createCriteria().andWgCodeIn(fourCodeList).andLevelEqualTo("4");
        List<GridRegion> fourWgList = gridRegionService.selectByExample(fourWgExample);

        //三级网格
        List<String> thirdCodeList = fourWgList.stream().map(GridRegion::getWgParentId).collect(Collectors.toList());
        GridRegionExample thirdWgExample = new GridRegionExample();
        thirdWgExample.createCriteria().andWgCodeIn(thirdCodeList).andLevelEqualTo("3");
        List<GridRegion> thirdWgList = gridRegionService.selectByExample(thirdWgExample);

        //二级网格
        List<String> secondCodeList = thirdWgList.stream().map(GridRegion::getWgParentId).collect(Collectors.toList());
        GridRegionExample secondWgExample = new GridRegionExample();
        secondWgExample.createCriteria().andWgCodeIn(secondCodeList).andLevelEqualTo("2");
        List<GridRegion> secondWgList = gridRegionService.selectByExample(secondWgExample);

        ZQTreeNode reult = new ZQTreeNode();
        List<ZQTreeNode> secondReult = new ArrayList<>();


        for (GridRegion secondWg : secondWgList) {
            if (secondCodeList.contains(secondWg.getWgCode())) {
                ZQTreeNode map = new ZQTreeNode();
                map.setId(secondWg.getId());
                map.setCode(secondWg.getWgCode());
                map.setName(secondWg.getWgName());
                map.setParentId(secondWg.getWgParentId());
                map.setLevel(secondWg.getLevel());
                secondReult.add(map);
                List<ZQTreeNode> thirdReult = new ArrayList<>();

                for (GridRegion thirdWg : thirdWgList) {
                    ZQTreeNode thirdmap = new ZQTreeNode();
                    if (StringUtils.isNotEmpty(thirdWg.getWgParentId()) && thirdWg.getWgParentId().equals(secondWg.getWgCode()) && thirdCodeList.contains(thirdWg.getWgCode())) {
                        thirdmap.setId(thirdWg.getId());
                        thirdmap.setCode(thirdWg.getWgCode());
                        thirdmap.setName(thirdWg.getWgName());
                        thirdmap.setParentId(thirdWg.getWgParentId());
                        thirdmap.setLevel(thirdWg.getLevel());
                        thirdReult.add(thirdmap);
                    }
                    List<ZQTreeNode> fourReult = new ArrayList<>();

                    for (GridRegion fourWg : fourWgList) {
                        ZQTreeNode fourmap = new ZQTreeNode();
                        if (StringUtils.isNotEmpty(fourWg.getWgParentId()) && fourWg.getWgParentId().equals(thirdWg.getWgCode()) && fourCodeList.contains(fourWg.getWgCode())) {
                            fourmap.setId(fourWg.getId());
                            fourmap.setCode(fourWg.getWgCode());
                            fourmap.setName(fourWg.getWgName());
                            fourmap.setParentId(fourWg.getWgParentId());
                            fourmap.setLevel(fourWg.getLevel());
                            fourReult.add(fourmap);
                        }
                    }

                    thirdmap.setChild(fourReult);
                }
                map.setChild(thirdReult);
            }

        }

        GridRegionExample example = new GridRegionExample();
        example.createCriteria().andLevelEqualTo("1").andIsValidEqualTo("1");
        List<GridRegion> bsWgxxbList = gridRegionService.selectByExample(example);
        reult.setChild(secondReult);
        if (bsWgxxbList.size() > 0) {
            GridRegion bsWgxxb = bsWgxxbList.get(0);
            reult.setLevel("1");
            reult.setName(bsWgxxb.getWgName());
            reult.setCode(bsWgxxb.getWgCode());
            reult.setId(bsWgxxb.getId());
        }


        return reult;
    }

    @Override
    public Map<String, String> infoTj(String wgCode, String planId) {
        VisitPlanTaskExample allExample = new VisitPlanTaskExample();
        VisitPlanTaskExample endExample = new VisitPlanTaskExample();
        DecimalFormat df = new DecimalFormat("######0.00");
        VisitPlanTaskExample.Criteria allExampleCriteria = allExample.createCriteria();
        VisitPlanTaskExample.Criteria endExampleCriteria = endExample.createCriteria();

        allExampleCriteria.andPlanIdEqualTo(planId);
        if (StringUtils.isNotEmpty(wgCode)) {
            allExampleCriteria.andObjWgCodeLike(wgCode + "%");
        }

        endExampleCriteria.andPlanIdEqualTo(planId).andPlanTaskStatusEqualTo("1");
        if (StringUtils.isNotEmpty(wgCode)) {
            endExampleCriteria.andObjWgCodeLike(wgCode + "%");
        }
        double allCount = visitPlanTaskMapper.countByExample(allExample);
        double endCount = visitPlanTaskMapper.countByExample(endExample);
        HashMap<String, String> map = new HashMap<>();
        map.put("allCount", (int) allCount + "");
        map.put("endCount", (int) endCount + "");
        if (allCount == 0 || endCount == 0) {
            map.put("wcl", "0%");
        } else {
            map.put("wcl", df.format(((endCount / allCount) * 100)) + "%");
        }

        return map;
    }

    @Override
    public Map<String, String> aqzfPcTj() {
        HashMap<String, String> map = new HashMap<>();
        DecimalFormat df = new DecimalFormat("######0.00");
        //企业
        VisitPlanTaskExample allCompanyExample = new VisitPlanTaskExample();
        VisitPlanTaskExample endCompanyExample = new VisitPlanTaskExample();
        allCompanyExample.createCriteria().andObjTypeEqualTo("1").andIsValidEqualTo("1");
        endCompanyExample.createCriteria().andObjTypeEqualTo("1").andIsValidEqualTo("1").andPlanTaskStatusEqualTo("1");
        double allCompanyCount = visitPlanTaskMapper.countByExample(allCompanyExample);
        double endCompanyCount = visitPlanTaskMapper.countByExample(endCompanyExample);
        map.put("allCompanyCount", allCompanyCount + "");
        map.put("endCompanyCount", endCompanyCount + "");
        if (allCompanyCount == 0 || endCompanyCount == 0) {
            map.put("companyWcl", "0%");
        } else {
            map.put("companyWcl", df.format(((endCompanyCount / allCompanyCount) * 100)) + "%");
        }

        //九小场所
        VisitPlanTaskExample allJiuxiaoExample = new VisitPlanTaskExample();
        VisitPlanTaskExample endJiuxiaoExample = new VisitPlanTaskExample();
        allJiuxiaoExample.createCriteria().andObjTypeEqualTo("2").andIsValidEqualTo("1");
        endJiuxiaoExample.createCriteria().andObjTypeEqualTo("2").andIsValidEqualTo("1").andPlanTaskStatusEqualTo("1");
        double allJiuxiaoCount = visitPlanTaskMapper.countByExample(allJiuxiaoExample);
        double endJiuxiaoCount = visitPlanTaskMapper.countByExample(endJiuxiaoExample);
        map.put("allJiuxiaoCount", allJiuxiaoCount + "");
        map.put("endJiuxiaoCount", endJiuxiaoCount + "");
        if (allJiuxiaoCount == 0 || endJiuxiaoCount == 0) {
            map.put("jiuxiaoWcl", "0%");
        } else {
            map.put("jiuxiaoWcl", df.format(((endJiuxiaoCount / allJiuxiaoCount) * 100)) + "%");
        }

        //问题隐患
        TkCommonTaskExample allTaskExample = new TkCommonTaskExample();
        TkCommonTaskExample endTaskExample = new TkCommonTaskExample();
        allTaskExample.createCriteria().andFormIdIsNotNull().andStandby1EqualTo("0").andComeFromEqualTo(12);
        endTaskExample.createCriteria().andFormIdIsNotNull().andStandby1EqualTo("0").andTkStatusEqualTo(50).andComeFromEqualTo(12);
        double allTaskCount = tkCommonTaskMapper.countByExample(allTaskExample);
        double endTaskCount = tkCommonTaskMapper.countByExample(endTaskExample);
        map.put("allTaskCount", allTaskCount + "");
        map.put("endTaskCount", endTaskCount + "");
        if (allTaskCount == 0 || endTaskCount == 0) {
            map.put("taskWcl", "0%");
        } else {
            map.put("taskWcl", df.format(((endTaskCount / allTaskCount) * 100)) + "%");
        }

        return map;
    }

    @Override
    public Map<String, Integer> appAqzfTj(String startDate, String endDate, String objType, String wgCode) {
        Map<String, Integer> map = new HashMap<>();
        VisitPlanTaskSearchParam param = new VisitPlanTaskSearchParam();
        param.setStartDate(startDate);
        param.setEndDate(endDate);
        param.setObjType(objType);
        param.setWgCodeLikes(Arrays.asList(wgCode.split(",")));
        Integer allCount = visitPlanTaskExtMapper.countByParam(param);
        param.setPlanTaskStatus("1");
        Integer doneCount = visitPlanTaskExtMapper.countByParam(param);
        map.put("all", allCount);
        map.put("done", doneCount);
        return map;
    }

    @Override
    public Map<String, String> rhzfPcTj(String wgCode) {
        HashMap<String, String> map = new HashMap<>();
        DecimalFormat df = new DecimalFormat("######0.00");
        //走访户数
        VisitPlanTaskExample allExample = new VisitPlanTaskExample();
        VisitPlanTaskExample endExample = new VisitPlanTaskExample();
        VisitPlanTaskExample.Criteria allExampleCriteria = allExample.createCriteria();
        VisitPlanTaskExample.Criteria endExampleCriteria = endExample.createCriteria();

        if (StringUtils.isNotEmpty(wgCode)) allExampleCriteria.andObjWgCodeLike(wgCode + "%");
        if (StringUtils.isNotEmpty(wgCode)) endExampleCriteria.andObjWgCodeLike(wgCode + "%");

        allExampleCriteria.andObjTypeNotIn(Arrays.asList("1", "2")).andIsValidEqualTo("1");
        endExampleCriteria.andObjTypeNotIn(Arrays.asList("1", "2")).andIsValidEqualTo("1").andPlanTaskStatusEqualTo("1");
        double allCount = visitPlanTaskMapper.countByExample(allExample);
        double endCount = visitPlanTaskMapper.countByExample(endExample);
        map.put("allCount", (int) allCount + "");
        map.put("endCount", (int) endCount + "");
        if (allCount == 0 || endCount == 0) {
            map.put("wcl", "0%");
        } else {
            map.put("wcl", df.format(((endCount / allCount) * 100)) + "%");
        }

        //群租房/车库
        VisitPlanTaskExample qzfAllExample = new VisitPlanTaskExample();
        VisitPlanTaskExample.Criteria qzfAllExampleCriteria1 = qzfAllExample.createCriteria();
        VisitPlanTaskExample.Criteria qzfAllExampleCriteria2 = qzfAllExample.createCriteria();

        VisitPlanTaskExample qzfEndExample = new VisitPlanTaskExample();
        VisitPlanTaskExample.Criteria qzfEndExampleCriteria1 = qzfEndExample.createCriteria();
        VisitPlanTaskExample.Criteria qzfEndExampleCriteria2 = qzfEndExample.createCriteria();

        qzfAllExampleCriteria1.andObjTypeNotIn(Arrays.asList("1", "2")).andIsValidEqualTo("1").andObjTypeEqualTo("fwlx003");
        if (StringUtils.isNotEmpty(wgCode)) qzfAllExampleCriteria1.andObjWgCodeLike(wgCode + "%");
        qzfAllExampleCriteria2.andObjTypeNotIn(Arrays.asList("1", "2")).andIsValidEqualTo("1").andObjTypeLike("fwlx004");
        if (StringUtils.isNotEmpty(wgCode)) qzfAllExampleCriteria2.andObjWgCodeLike(wgCode + "%");
        qzfAllExample.or(qzfAllExampleCriteria2);

        qzfEndExampleCriteria1.andObjTypeNotIn(Arrays.asList("1", "2")).andIsValidEqualTo("1").andPlanTaskStatusEqualTo("1").andObjTypeEqualTo("fwlx003");
        if (StringUtils.isNotEmpty(wgCode)) qzfEndExampleCriteria1.andObjWgCodeLike(wgCode + "%");
        qzfEndExampleCriteria2.andObjTypeNotIn(Arrays.asList("1", "2")).andIsValidEqualTo("1").andPlanTaskStatusEqualTo("1").andObjTypeLike("fwlx004");
        if (StringUtils.isNotEmpty(wgCode)) qzfEndExampleCriteria2.andObjWgCodeLike(wgCode + "%");
        qzfEndExample.or(qzfEndExampleCriteria2);
        double qzfAllCount = visitPlanTaskMapper.countByExample(qzfAllExample);
        double qzfEndCount = visitPlanTaskMapper.countByExample(qzfEndExample);
        map.put("qzfAllCount", (int) qzfAllCount + "");
        map.put("qzfEndCount", (int) qzfEndCount + "");
        if (qzfAllCount == 0 || qzfEndCount == 0) {
            map.put("qzfWcl", "0%");
        } else {
            map.put("qzfWcl", df.format(((qzfEndCount / qzfAllCount) * 100)) + "%");
        }
        return map;
    }

    @Override
    public List<Map<String, Object>> nearSevenDayTaskNum(String wgCode, String startTime) {
        List<Map<String, Object>> list = new ArrayList<>();
        ArrayList<Date> test = null;
        if (StringUtils.isNotEmpty(startTime)) {
            test = ZQTDateUtils.getDateList(7, startTime);
        } else {
            test = ZQTDateUtils.getDateList(7);

        }
        if (test.size() > 0) {
            int i = 7;//计数器
            for (Date da : test) {
                Map<String, Object> map = new HashMap<>();
                VisitPlanTaskExample taskAqzfExample = new VisitPlanTaskExample();
                VisitPlanTaskExample.Criteria aqzfExampleCriteria = taskAqzfExample.createCriteria();

                VisitPlanTaskExample taskRhzfExample = new VisitPlanTaskExample();
                VisitPlanTaskExample.Criteria rhzfExampleCriteria = taskRhzfExample.createCriteria();

                VisitFreeInterviewExample interviewExample = new VisitFreeInterviewExample();
                VisitFreeInterviewExample.Criteria interviewCriteria = interviewExample.createCriteria();

                aqzfExampleCriteria.andIsValidEqualTo("1").andCreateTimeGreaterThanOrEqualTo(ZQTDateUtils.getTodayStartTime(da))
                        .andCreateTimeLessThanOrEqualTo(ZQTDateUtils.getTodayEndTime(da)).andObjTypeIn(Arrays.asList("1", "2"));
                rhzfExampleCriteria.andIsValidEqualTo("1").andCreateTimeGreaterThanOrEqualTo(ZQTDateUtils.getTodayStartTime(da))
                        .andCreateTimeLessThanOrEqualTo(ZQTDateUtils.getTodayEndTime(da)).andObjTypeNotIn(Arrays.asList("1", "2"));
                interviewCriteria.andIsValidEqualTo("1").andInterviewTimeYMDGreaterThanOrEqualTo(ZQTDateUtils.formatDate(da))
                        .andInterviewTimeYMDLessThanOrEqualTo(ZQTDateUtils.formatDate(da)).andPlanIdIsNotNull();

                if (StringUtils.isNotEmpty(wgCode)) {
                    aqzfExampleCriteria.andObjWgCodeLike(wgCode + "%");
                    rhzfExampleCriteria.andObjWgCodeLike(wgCode + "%");
                    interviewCriteria.andWgyCodeLike(wgCode + "%");
                }

                long aqzfCount = visitPlanTaskMapper.countByExample(taskAqzfExample);
                long rhzfCount = visitPlanTaskMapper.countByExample(taskRhzfExample);
                List<VisitFreeInterview> interviews = visitFreeInterviewMapper.selectByExample(interviewExample);

                if (CollectionUtils.isEmpty(interviews)) {
                    map.put("freeCount", 0);
                } else {
                    Map<String, List<VisitFreeInterview>> interviewMap = interviews.stream()
                            .collect(Collectors.groupingBy(o -> o.getPlanId() + o.getObjId() + o.getType()));
                    map.put("freeCount", interviewMap.size());
                }

                map.put("aqzfCount", aqzfCount);
                map.put("rhzfCount", rhzfCount);
                map.put("month", ZQTDateUtils.format(da, "MM-dd"));
                list.add(map);
                i--;
            }
        }

        Collections.reverse(list); // 倒叙
        return list;
    }

    @Override
    public List<GridWgBean> selectAqzfTj(String wgCode, String time) {
        List<GridWgBean> list = new ArrayList<>();
        String startTime = ZQTDateUtils.getMonthStartTime(time);
        String endTime = ZQTDateUtils.getMonthEndTime(time);
        List<Map<String, String>> resultMaps = visitPlanTaskExtMapper.selectAqzfTj(startTime, endTime);
        GridRegionExample wgxxbExample = new GridRegionExample();
        wgxxbExample.createCriteria().andLevelEqualTo("2");
        List<GridRegion> wgxxbList = gridRegionService.selectByExample(wgxxbExample);
        wgxxbList.forEach(bsWgxxb -> {
            GridWgBean hashMap = new GridWgBean();
            int count = 0;
            hashMap.setWgName(bsWgxxb.getWgName());
            for (Map<String, String> map : resultMaps) {
                String parentCode = map.get("parentCode").toString();
                if (parentCode.substring(0, parentCode.length() - 3).equals(bsWgxxb.getWgCode())) {
                    count += Integer.parseInt(String.valueOf(map.get("count")));
                }
            }
            hashMap.setCount(count);
            list.add(hashMap);

        });

        return list.stream().sorted(Comparator.comparing(GridWgBean::getCount).reversed()).collect(Collectors.toList());
    }

    @Override
    public VisitPlanTaskExt planTaskInfo(String id) {
        VisitPlanTaskExt planTaskExt = new VisitPlanTaskExt();
        try {
            VisitPlanTask planTask = visitPlanTaskMapper.selectByPrimaryKey(id);
            //附件
            SysOtherappAttachmentExample attachmentExample = new SysOtherappAttachmentExample();
            attachmentExample.createCriteria().andBusinessIdEqualTo(id);
            List<SysOtherappAttachment> attachmentList = sysOtherappAttachmentService.selectByExample(attachmentExample);
            PropertyUtils.copyProperties(planTaskExt, planTask);
            planTaskExt.setOtherappAttachments(attachmentList);
            GridRegionExample wgxxbExample = new GridRegionExample();
            wgxxbExample.createCriteria().andWgCodeEqualTo(planTaskExt.getObjWgCode());
            List<GridRegion> bsWgxxbList = gridRegionService.selectByExample(wgxxbExample);
            GridRegion bsWgxxb = bsWgxxbList.get(0);
            planTaskExt.setWgName(bsWgxxb.getWgName());//地块名称

            VisitPlan wszfPlan = visitPlanMapper.selectByPrimaryKey(planTaskExt.getPlanId());
            planTaskExt.setPlanTitle(wszfPlan.getPlanTitle());
            planTaskExt.setPlanExplain(wszfPlan.getPlanExplain());
            //计划附件
            SysOtherappAttachmentExample attachmentExample1 = new SysOtherappAttachmentExample();
            attachmentExample1.createCriteria().andBusinessIdEqualTo(wszfPlan.getId());
            List<SysOtherappAttachment> jhAttachmentList = sysOtherappAttachmentService.selectByExample(attachmentExample);
            planTaskExt.setJhOtherappAttachments(jhAttachmentList);

        } catch (Exception e) {
            e.printStackTrace();
        }


        return planTaskExt;
    }

    @Override
    public void updatePlanTask(VisitPlanTaskExt wszfPlanTask) {
        if ("1".equals(wszfPlanTask.getPlanTaskStatus())) wszfPlanTask.setUpdateTime(new Date());
        visitPlanTaskMapper.updateByPrimaryKeySelective(wszfPlanTask);
        //附件
        if (!CollectionUtils.isEmpty(wszfPlanTask.getOtherappAttachments())) {
            //删除之前的附件
            SysOtherappAttachmentExample attachmentExample = new SysOtherappAttachmentExample();
            attachmentExample.createCriteria().andBusinessIdEqualTo(wszfPlanTask.getId()).andAttachTypeEqualTo(AttachEnums.AttachType.PLAN_TASK.name());
            sysOtherappAttachmentService.deleteByExample(attachmentExample);

            VisitPlanTask planTask = visitPlanTaskMapper.selectByPrimaryKey(wszfPlanTask.getId());

            for (SysOtherappAttachment attachment : wszfPlanTask.getOtherappAttachments()) {
                attachment.setAttachType(AttachEnums.AttachType.PLAN_TASK.name());
                attachment.setBusinessId(wszfPlanTask.getId());
                attachment.setValid(Byte.valueOf("1"));
                sysOtherappAttachmentService.insertSelective(attachment);
            }
        }
    }

    @Override
    public Map<String, Object> countPlanTaskByUserId(String userId) {
        VisitPlanTaskExample taskAqzfExample = new VisitPlanTaskExample();
        VisitPlanTaskExample endTaskAqzfExample = new VisitPlanTaskExample();
        VisitPlanTaskExample.Criteria aqzfExampleCriteria = taskAqzfExample.createCriteria();
        VisitPlanTaskExample.Criteria endAqzfExampleCriteria = endTaskAqzfExample.createCriteria();

        VisitPlanTaskExample taskRhzfExample = new VisitPlanTaskExample();
        VisitPlanTaskExample endTaskRhzfExample = new VisitPlanTaskExample();
        VisitPlanTaskExample.Criteria rhzfExampleCriteria = taskRhzfExample.createCriteria();
        VisitPlanTaskExample.Criteria endRhzfExampleCriteria = endTaskRhzfExample.createCriteria();

        aqzfExampleCriteria.andIsValidEqualTo("1").andObjTypeIn(Arrays.asList("1", "2")).andUrserIdEqualTo(userId);
        endAqzfExampleCriteria.andIsValidEqualTo("1").andObjTypeIn(Arrays.asList("1", "2")).andUrserIdEqualTo(userId).andPlanTaskStatusEqualTo("1");
        rhzfExampleCriteria.andIsValidEqualTo("1").andObjTypeNotIn(Arrays.asList("1", "2")).andUrserIdEqualTo(userId);
        endRhzfExampleCriteria.andIsValidEqualTo("1").andObjTypeNotIn(Arrays.asList("1", "2")).andUrserIdEqualTo(userId).andPlanTaskStatusEqualTo("1");

        double aqzfCount = visitPlanTaskMapper.countByExample(taskAqzfExample);
        double endAqzfCount = visitPlanTaskMapper.countByExample(endTaskAqzfExample);
        double rhzfCount = visitPlanTaskMapper.countByExample(taskRhzfExample);
        double endRhzfCount = visitPlanTaskMapper.countByExample(endTaskRhzfExample);

        HashMap<String, Object> map = new HashMap<>();
        map.put("aqzfCount", aqzfCount);
        map.put("endAqzfCount", endAqzfCount);
        DecimalFormat df = new DecimalFormat("######0.00");
        if (aqzfCount == 0 || endAqzfCount == 0) {
            map.put("aqzfWcl", "0%");
        } else {
            map.put("aqzfWcl", df.format(((endAqzfCount / aqzfCount) * 100)) + "%");
        }
        map.put("rhzfCount", rhzfCount);
        map.put("endRhzfCount", endRhzfCount);
        if (rhzfCount == 0 || endRhzfCount == 0) {
            map.put("rhzfWcl", "0%");
        } else {
            map.put("rhzfWcl", df.format(((endRhzfCount / rhzfCount) * 100)) + "%");
        }
        return map;
    }

    /**
     * 如果有指定月份则统计指定月份的数据，否则统计近六个月的数据
     *
     * @param wszfPlanRate
     * @return
     */
    @Override
    public List<VisitPlanRate> getPlatRate(VisitPlanRate wszfPlanRate) {
        List<VisitPlanRate> rateList = new ArrayList<>();
        Map<String, String> params = new HashMap<>();
        // 如果有指定月份则统计指定月份的数据，否则统计近六个月的数据
        if (StringUtils.isNotBlank(wszfPlanRate.getTjMonth())) {
            params.put("tjMonth", wszfPlanRate.getTjMonth());
            rateList.add(visitPlanMapper.getPlanRate(params));
        } else {
            for (int i = 0; i < 6; i++) {
                params.put("tjMonth", TimeUtils.minusMonths((long) i, TimeUtils.FormatEnum.FORMAT_MONTH));
                rateList.add(visitPlanMapper.getPlanRate(params));
            }
        }
        rateList.forEach(o -> {
            if (o.getCnt() == 0) {
                o.setRate(new BigDecimal(0));
                return;
            }
            o.setRate(BigDecimal.valueOf(o.getCnt())
                    .divide(BigDecimal.valueOf(o.getCntPlan()), 4, BigDecimal.ROUND_HALF_UP)
                    .multiply(BigDecimal.valueOf(100)));
        });
        return rateList;
    }

    @Override
    public PageInfo<Map<String, Object>> getPatrolRecordPage(String objId, int pageNum, int pageSize) {
        VisitPlanTaskExample example = new VisitPlanTaskExample();
        VisitPlanTaskExample.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(objId)) {
            criteria.andObjIdEqualTo(objId);
        }
        PageHelper.startPage(pageNum, pageSize);
        List<VisitPlanTask> wszfPlanTasks = visitPlanTaskMapper.selectByExampleWithBLOBs(example);
        int count = (int) visitPlanTaskMapper.countByExample(example);

        List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
        wszfPlanTasks.forEach(wszfPlanTask -> {
            Map<String, Object> map = new HashMap<>();
            VisitPlan wszfPlan = visitPlanMapper.selectByPrimaryKey(wszfPlanTask.getPlanId());
            map.put("title", wszfPlan.getPlanTitle());
            map.put("time", wszfPlanTask.getCreateTime());
            if ("1".equals(wszfPlanTask.getPlanTaskStatus())) {
                map.put("status", "已走访");
            } else {
                map.put("status", "未走访");
            }
            result.add(map);

        });
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<Map<String, Object>>(result);
        return ZQTPageUtil.build(pageInfo, pageNum, pageSize, count);
    }

    @Override
    public PageInfo<Map<String, Object>> getYhzgPage(String objId, int pageNum, int pageSize) {
        TkCommonTaskExample example = new TkCommonTaskExample();
        TkCommonTaskExample.Criteria criteria = example.createCriteria();
        criteria.andStandby1EqualTo("0");
        if (StringUtils.isNotBlank(objId)) {
            criteria.andAdviceIdEqualTo(objId);
        }
        PageHelper.startPage(pageNum, pageSize);
        List<TkCommonTask> tkCommonTasks = tkCommonTaskMapper.selectByExample(example);
        int count = (int) tkCommonTaskMapper.countByExample(example);

        List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
        tkCommonTasks.forEach(tkCommonTask -> {
            Map<String, Object> map = new HashMap<>();
            map.put("title", tkCommonTask.getTkName());
            map.put("time", tkCommonTask.getCreateTime());
            if (50 == tkCommonTask.getTkStatus()) {
                map.put("status", "已完成");
            } else {
                map.put("status", "未完成");
            }
            result.add(map);

        });
        PageInfo<Map<String, Object>> pageInfo = new PageInfo<Map<String, Object>>(result);
        return ZQTPageUtil.build(pageInfo, pageNum, pageSize, count);
    }

    @Override
    public PageInfo<VisitPlanTaskExt> planTaskForPage(int pageNum, int pageSize,String wgCode, String planFl) {
        VisitPlanTaskExample example = new VisitPlanTaskExample();
        example.setOrderByClause("update_time desc");
        VisitPlanTaskExample.Criteria criteria = example.createCriteria();
        criteria.andPlanTaskStatusEqualTo("1");

        if (StringUtils.isNotBlank(wgCode)) {
            criteria.andObjWgCodeLike(wgCode + "%");
        }
        if (StringUtils.isNotBlank(planFl)) {
            if (planFl.equals("1")) {//安全生产走访
                criteria.andObjTypeIn(Arrays.asList("1", "2"));
            } else {//网格员入户走访
                criteria.andObjTypeNotIn(Arrays.asList("1", "2"));
            }

        }
        PageHelper.startPage(pageNum, pageSize);
        List<VisitPlanTask> wszfPlanTasks = visitPlanTaskMapper.selectByExampleWithBLOBs(example);
        int count = (int) visitPlanTaskMapper.countByExample(example);
        List<VisitPlanTaskExt> list = new ArrayList<>();
        wszfPlanTasks.forEach(wszfPlanTask -> {
            VisitPlanTaskExt planTaskExt = new VisitPlanTaskExt();
            try {
                PropertyUtils.copyProperties(planTaskExt, wszfPlanTask);
            } catch (Exception e) {
                e.printStackTrace();
            }
            planTaskExt.setPlanTime(ZQTDateUtils.formatDate(wszfPlanTask.getUpdateTime(), "yyyy-MM-dd HH:mm:ss"));
            list.add(planTaskExt);
        });

        PageInfo<VisitPlanTaskExt> pageInfo = new PageInfo<>(list);
        return ZQTPageUtil.build(pageInfo, pageNum, pageSize, count);
    }

    @Override
    public void updateByPlanTask(String userId, String planTaskStatus, String planTaskFeedback, String objId, String updateTime, String otherappAttachments, String qddkdz) {
        VisitPlanTask wszfPlanTask = new VisitPlanTask();
        wszfPlanTask.setPlanTaskStatus(planTaskStatus);
        if(StringUtils.isNotBlank(planTaskFeedback)){
            wszfPlanTask.setPlanTaskFeedback(planTaskFeedback);
        }
        if (StringUtils.isEmpty(updateTime)) {
            wszfPlanTask.setUpdateTime(new Date());
        } else {
            wszfPlanTask.setUpdateTime(ZQTDateUtils.getPastDate(updateTime, "yyyy-MM-dd HH:mm:ss"));
        }
        if (StringUtils.isNotBlank(qddkdz)) {//签到打卡地址
            wszfPlanTask.setYlzd1(qddkdz);
        }

        VisitPlanTaskExample planTaskExample = new VisitPlanTaskExample();
        planTaskExample.createCriteria().andPlanTaskStatusEqualTo("2").andIsValidEqualTo("1")
               .andUrserIdEqualTo(userId).andObjIdEqualTo(objId);

        if (StringUtils.isNotEmpty(otherappAttachments)) {
            List<VisitPlanTask> wszfPlanTasks = visitPlanTaskMapper.selectByExample(planTaskExample);
            if (wszfPlanTasks.size() > 0) {
                List<SysOtherappAttachment> otherappAttachments1 = JSONArray.parseArray(otherappAttachments, SysOtherappAttachment.class);
                for (VisitPlanTask planTask : wszfPlanTasks) {
                    for (SysOtherappAttachment attachment : otherappAttachments1) {
                        attachment.setAttachType(AttachEnums.AttachType.PLAN_TASK.name());
                        attachment.setBusinessId(planTask.getId());
                        attachment.setValid(Byte.valueOf("1"));
                        sysOtherappAttachmentService.insertSelective(attachment);
                    }
                }
            }

        }
        visitPlanTaskMapper.updateByExampleSelective(wszfPlanTask, planTaskExample);
    }

    @Override
    public long latestVisitCount(String objType, String objId) {
        Date date = new Date();
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DATE, -30);
        Date prev = cal.getTime();
        VisitPlanTaskExample example = new VisitPlanTaskExample();
        VisitPlanTaskExample.Criteria criteria = example.createCriteria();
        if("1".equals(objType) || "2".equals(objType)){
            criteria.andObjTypeEqualTo(objType);
        }else{
            List<String> objTypeList = new ArrayList<>();
            objTypeList.add("1");
            objTypeList.add("2");
            criteria.andObjTypeNotIn(objTypeList);
        }
        criteria.andCreateTimeBetween(prev, date);
        return visitPlanTaskMapper.countByExample(example);
    }

    @Override
    public PageInfo<VisitPlanTaskExt> planTaskPageApp(int pageNum, int pageSize,  String userId, String planTaskStatus, String objName, String objType, String planFl) {
        VisitPlanTaskExample example = new VisitPlanTaskExample();
        VisitPlanTaskExample.Criteria criteria = example.createCriteria();

        if (StringUtils.isNotBlank(userId)) {
            criteria.andUrserIdEqualTo(userId);
        }
        if (StringUtils.isNotBlank(objName)) {
            criteria.andObjNameLike("%" + objName + "%");
        }
        if (StringUtils.isNotBlank(planTaskStatus)) {
            criteria.andPlanTaskStatusEqualTo(planTaskStatus);
        }
        if (StringUtils.isNotBlank(objType)) {
            criteria.andObjTypeEqualTo(objType);
        }
        if (StringUtils.isNotBlank(planFl) && StringUtils.isBlank(objType)) {
            if (planFl.equals("1")) {//安全生产走访
                criteria.andObjTypeIn(Arrays.asList("1", "2"));
            } else {//网格员入户走访
                criteria.andObjTypeNotIn(Arrays.asList("1", "2"));
            }

        }
        PageHelper.startPage(pageNum, pageSize);
        List<VisitPlanTask> wszfPlanTasks = visitPlanTaskMapper.selectByExampleWithBLOBs(example);
        int count = (int) visitPlanTaskMapper.countByExample(example);

        List<VisitPlanTaskExt> wszfPlanTaskExtList = new ArrayList<VisitPlanTaskExt>();
        wszfPlanTasks.forEach(wszfPlanTask -> {
            VisitPlanTaskExt planTaskExt = new VisitPlanTaskExt();
            try {
                PropertyUtils.copyProperties(planTaskExt, wszfPlanTask);
                if (StringUtils.isNotEmpty(planTaskExt.getTaskId())) {

                    TkCommonTask tkCommonTask = tkCommonTaskMapper.selectByPrimaryKey(planTaskExt.getTaskId());
                    planTaskExt.setTkId(tkCommonTask.getTkId());
                    planTaskExt.setTkStatus(tkCommonTask.getTkStatus() == 50 ? "已完成" : "未完成");

                }
                GridRegionExample wgxxbExample = new GridRegionExample();
                wgxxbExample.createCriteria().andWgCodeEqualTo(planTaskExt.getObjWgCode());
                List<GridRegion> bsWgxxbList = gridRegionService.selectByExample(wgxxbExample);
                GridRegion bsWgxxb = bsWgxxbList.get(0);
                planTaskExt.setWgName(bsWgxxb.getWgName());//地块名称

                VisitPlan wszfPlan = visitPlanMapper.selectByPrimaryKey(wszfPlanTask.getPlanId());
                planTaskExt.setPlanTitle(wszfPlan.getPlanTitle());
                planTaskExt.setPlanTypeName(bsCommonService.getName(wszfPlan.getPlanType()));
                planTaskExt.setFormId(wszfPlan.getFormId());

                wszfPlanTaskExtList.add(planTaskExt);
            } catch (Exception e) {
                e.printStackTrace();
            }

        });


        PageInfo<VisitPlanTaskExt> pageInfo = new PageInfo<>(wszfPlanTaskExtList);
        return ZQTPageUtil.build(pageInfo, pageNum, pageSize, count);
    }
}
