package com.ruoyi.web.controller.visit;

import cn.hutool.core.date.DateUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.domain.form.MdForm;
import com.ruoyi.system.domain.form.MdFormExample;
import com.ruoyi.system.domain.grid.GridCompany;
import com.ruoyi.system.domain.grid.GridRegionUser;
import com.ruoyi.system.domain.grid.GridRegionUserExample;
import com.ruoyi.system.domain.visit.dr.*;
import com.ruoyi.system.domain.visit.dr.ext.VisitDrCheckFormExt;
import com.ruoyi.system.domain.visit.dr.ext.VisitDrDetailForApp;
import com.ruoyi.system.domain.visit.dr.ext.VisitDrGroup;
import com.ruoyi.system.domain.visit.dr.ext.VisitDrMap;
import com.ruoyi.system.domain.visit.dr.params.VisitDrCheckResultParams;
import com.ruoyi.system.domain.visit.dr.params.VisitDrParamIds;
import com.ruoyi.system.mapper.visit.dr.VisitDrCompanyDataPoolMapper;
import com.ruoyi.system.mapper.visit.dr.VisitDrUserDataPoolMapper;
import com.ruoyi.system.service.form.FormManager;
import com.ruoyi.system.service.form.MdFormService;
import com.ruoyi.system.service.grid.GridCompanyService;
import com.ruoyi.system.service.grid.GridRegionUserService;
import com.ruoyi.system.service.other.BsCommonService;
import com.ruoyi.system.service.system.ISysUserService;
import com.ruoyi.system.service.visit.dr.*;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 双随机走访服务
 *
 * @author condey
 * @version $$package: com.ruoyi.web.controller.visit, v 0.1 2024/6/12 4:35 PM condey Exp $$
 */
@Api(tags = "走访管理 - 双随机走访")
@RestController
@RequestMapping("/api/visit/doubleRandom")
public class VisitDoubleRandomController extends BaseController {

    @Autowired
    VisitDrRuleService visitDrRuleService;
    @Autowired
    VisitDrCompanyDataPoolMapper visitDrCompanyDataPoolMapper;
    @Autowired
    VisitDrUserDataPoolMapper visitDrUserDataPoolMapper;
    @Autowired
    VisitDrTaskService visitDrTaskService;
    @Autowired
    VisitDrTaskUserService visitDrTaskUserService;
    @Autowired
    VisitDrTaskCompanyService visitDrTaskCompanyService;
    @Autowired
    VisitDrCheckHistoryService visitDrCheckHistoryService;
    @Autowired
    VisitDrCheckHistoryFormService visitDrCheckHistoryFormService;
    @Autowired
    VisitDrCheckHistoryFormAttachService visitDrCheckHistoryFormAttachService;
    @Autowired
    VisitDrCheckHistoryAttachService visitDrCheckHistoryAttachService;
    @Autowired
    VisitDrCheckHistoryAttachService attachService;
    @Autowired
    GridCompanyService gridCompanyService;
    @Autowired
    GridRegionUserService gridRegionUserService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private BsCommonService bsCommonService;
    @Autowired
    private FormManager formManager;
    @Autowired
    private MdFormService mdFormService;

    ///新增双随机规则
    @PostMapping(value = "/addVisitDrRule")
    public AjaxResult addVisitDrRule(@RequestBody VisitDrRule rule) {
        String ruleId = IdUtils.fastSimpleUUID();
        rule.setId(ruleId);
        AjaxResult result = validation(rule);
        if (!result.isSuccess()) {
            return result;
        }
        //生成企业对象数据池
        AjaxResult r = generateCompanyDataPool(rule, ruleId);
        if (!r.isSuccess()) {
            return r;
        }
        //生成执法人员对象数据池
        AjaxResult re = generateUserDataPool(rule, ruleId);
        if (!re.isSuccess()) {
            return re;
        }
        //抽选表单
        if(StringUtils.isNotBlank(rule.getTemplateId())){
            rule.setExtfieldTen(rule.getTemplateId());
            List<String> formIds = new ArrayList<>();
            List<String> templateIds = Arrays.asList(rule.getTemplateId().split(","));
            for(String templateId : templateIds){
                String formId = formManager.saveFormTemplateWithWST(templateId, rule.getCreateBy());
                formIds.add(formId);
            }
            rule.setChooseForm(com.ruoyi.common.utils.StringUtils.join(formIds,","));
        }
        //将规则增加到数据库中
        int addResult = visitDrRuleService.insertSelective(rule);
        if (addResult > 0) {
            return AjaxResult.success("添加成功", ruleId);
        } else {
            visitDrCompanyDataPoolMapper.deleteAllDataByRuleId(ruleId);
            visitDrUserDataPoolMapper.deleteAllDataByRuleId(ruleId);
        }
        return AjaxResult.success();
    }

    //查询滚动的人员和企业列表
    @GetMapping(value = "/getUserAndCompany")
    public AjaxResult getUserAndCompany(@RequestParam(value = "ruleId", required = false) String ruleId) {
        VisitDrMap map = new VisitDrMap();
        GridRegionUserExample userExample = new GridRegionUserExample();
        GridRegionUserExample.Criteria ca = userExample.createCriteria();
        ca.andIsValidEqualTo("1");
        List<GridRegionUser> regionUsers = gridRegionUserService.selectByExample(userExample);
        List<SysUser> users = new ArrayList<>();
        if(!CollectionUtils.isEmpty(regionUsers)){
            regionUsers.forEach( e ->{
                SysUser sysUser = sysUserService.selectUserById(e.getUserId());
                if(sysUser != null){
                    users.add(sysUser);
                }else{
                    SysUser user = new SysUser();
                    user.setAvatar("");
                    user.setUserId(e.getUserId());
                    user.setNickName(e.getYlzd1());
                    users.add(user);
                }
            });
        }
        map.setUserList(users);
        List<GridCompany> comList = gridCompanyService.selectCompanyForDoubleRandomLimit();
        map.setComList(comList);
        return AjaxResult.success(map);
    }

    //双随机滚动页面的停止按钮
    @GetMapping(value = "/visitDrStop")
    public AjaxResult visitDrStop(@RequestParam(value = "ruleId") String ruleId) {
        VisitDrRule rule = visitDrRuleService.selectByPrimaryKey(ruleId);
        int currentGroupNum = Integer.parseInt(rule.getChoosePeopleGroup());
        //下面进行双随机分配
        // 数据源的list
        //符合条件的企业数据
        List<VisitDrCompanyDataPool> companylist = visitDrCompanyDataPoolMapper.selectDataByRuleId(ruleId);
        //符合条件的执法人员
        List<VisitDrUserDataPool> userlist = visitDrUserDataPoolMapper.selectDataByRuleId(ruleId);
        List<VisitDrGroup> groupsList = new ArrayList<VisitDrGroup>();
        // 计算一下每组多少人
        int peoples = userlist.size() / currentGroupNum;
        // 计算一下每组多少企业
        int companys = companylist.size() / currentGroupNum;
        // 分组开始
        for (int i = 0; i < currentGroupNum; i++) {
            VisitDrGroup ssjGroup = new VisitDrGroup();
            ssjGroup.setCurrentGroup(String.valueOf(i + 1));
            ssjGroup.setCurrentGroupForms(rule.getChooseForm());
            List<VisitDrUserDataPool> userGroup = new ArrayList<VisitDrUserDataPool>();
            for (int j = 0; j < peoples; j++) {
                int random = getRandom(userlist.size());
                userGroup.add(userlist.get(random));
                userlist.remove(random);
            }
            ssjGroup.setUerPoolList(userGroup);
            List<VisitDrCompanyDataPool> companyGroup = new ArrayList<VisitDrCompanyDataPool>();
            for (int j = 0; j < companys; j++) {
                int random = getRandom(companylist.size());
                companyGroup.add(companylist.get(random));
                companylist.remove(random);
            }
            ssjGroup.setCompanyPoolList(companyGroup);
            groupsList.add(ssjGroup);
        }
        // 最后剩下的人再重新分配一遍
        for (int i = 0; i < userlist.size(); i++) {
            groupsList.get(i).getUerPoolList().add(userlist.get(i));
        }
        // 最后剩下的企业再重新分配一遍
        for (int i = 0; i < companylist.size(); i++) {
            groupsList.get(i).getCompanyPoolList().add(companylist.get(i));
        }
        if (groupsList.size() > 0) {
            createTask(ruleId, groupsList, rule.getChooseTime(), rule);
            return AjaxResult.success(groupsList);
        } else {
            return AjaxResult.error(400, "分组失败，请检查数据");
        }

    }

    //双随机滚动页面的推送按钮
    @GetMapping(value = "/tuiSong")
    public AjaxResult tuiSong(@RequestParam(value = "ruleId") String ruleId) {
        int result = 0;
        //根据ruleId获取到当前的规则实体
        VisitDrRuleExample ruleExample = new VisitDrRuleExample();
        VisitDrRuleExample.Criteria ruleCriteria = ruleExample.createCriteria();
        ruleCriteria.andIdEqualTo(ruleId);
        VisitDrRule ruleModel = visitDrRuleService.selectFirstByExample(ruleExample);
        //根据RuleId 获取当前规则下的任务集合
        VisitDrTaskExample example = new VisitDrTaskExample();
        VisitDrTaskExample.Criteria criteria = example.createCriteria();
        criteria.andRuleIdEqualTo(ruleId);
        List<VisitDrTask> list = visitDrTaskService.selectByExample(example);
        for (VisitDrTask l : list) {
            //根据当前任务id获取当前任务的人员
            VisitDrTaskUserExample userExample = new VisitDrTaskUserExample();
            VisitDrTaskUserExample.Criteria userCriteria = userExample.createCriteria();
            userCriteria.andTaskIdEqualTo(l.getId());
            List<VisitDrTaskUser> userList = visitDrTaskUserService.selectByExample(userExample);
            String userIdStrs = "";
            String userNameStrs = "";
            for (int a = 0; a < userList.size(); a++) {
                if (a == (userList.size() - 1)) {
                    userIdStrs += userList.get(a).getUserId();
                    userNameStrs += userList.get(a).getUserName();
                } else {
                    userIdStrs += userList.get(a).getUserId() + ",";
                    userNameStrs += userList.get(a).getUserName() + ",";
                }

            }
            //当前任务下的企业集合
            VisitDrTaskCompanyExample companyExample = new VisitDrTaskCompanyExample();
            VisitDrTaskCompanyExample.Criteria companyCriteria = companyExample.createCriteria();
            companyCriteria.andTaskIdEqualTo(l.getId());
            List<VisitDrTaskCompany> companyList = visitDrTaskCompanyService.selectByExample(companyExample);
            for (VisitDrTaskCompany company : companyList) {
                VisitDrCheckHistory checkHistory = new VisitDrCheckHistory();
                checkHistory.setId(IdUtils.fastSimpleUUID());
                checkHistory.setRuleId(ruleId);
                checkHistory.setTaskId(l.getId());
                checkHistory.setTitle(ruleModel.getTitle());
                checkHistory.setCompanyId(company.getCompanyId());
                checkHistory.setCompanyName(company.getCompanyName());
                checkHistory.setZhCreditLevel(company.getExtfieldOne());
                checkHistory.setChooseType(ruleModel.getChooseType());
                checkHistory.setChooseForm(ruleModel.getChooseForm());
                checkHistory.setChooseTime(ruleModel.getChooseTime());
                checkHistory.setTaskUserIds(userIdStrs);
                checkHistory.setTaskUsers(userNameStrs);
                checkHistory.setCheckUsers(userNameStrs);
                checkHistory.setCreateBy(ruleModel.getCreateBy());
                checkHistory.setCreateTime(ruleModel.getCreateTime());
                checkHistory.setExtfieldOne(company.getExtfieldTwo());
                checkHistory.setResult("未开始检查");

                result += visitDrCheckHistoryService.insert(checkHistory);
                //每个企业新增的时候顺便把表单插入到表单表中
                if (StringUtils.isNotBlank(ruleModel.getChooseForm())) {
                    String[] strs = ruleModel.getChooseForm().split(",");
                    for (String fo : strs) {
                        VisitDrCheckHistoryForm biaodan = new VisitDrCheckHistoryForm();
                        biaodan.setId(IdUtils.fastSimpleUUID());
                        biaodan.setHistoryId(checkHistory.getId());
                        biaodan.setFormType(fo);
                        visitDrCheckHistoryFormService.insert(biaodan);
                    }
                }
            }
        }
        if (result > 0) {
            return AjaxResult.success("推送成功,成功" + result + "条数据");
        } else {
            return AjaxResult.error(400, "推送失败，请检查数据");
        }
    }

    //获取双随机任务列表
    @GetMapping(value = "/getVisitDrTaskList")
    public AjaxResult getVisitDrTaskList(@RequestParam(value = "loginUserId", required = false) String loginUserId,
                                         @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                         @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                         @RequestParam(value = "title", required = false) String title,
                                         @RequestParam(value = "checkType", required = false) String checkType,
                                         @RequestParam(value = "startTime", required = false) String startTime,
                                         @RequestParam(value = "endTime", required = false) String endTime,
                                         @RequestParam(value = "checkResult", required = false) String checkResult,
                                         @RequestParam(value = "companyName", required = false) String companyName,
                                         @RequestParam(value = "companyId", required = false) String companyId,
                                         @RequestParam(value = "taskUsers", required = false) String taskUsers) {

        PageHelper.startPage(pageNum, pageSize);
        VisitDrCheckHistoryExample checkHistoryExample = new VisitDrCheckHistoryExample();
        VisitDrCheckHistoryExample.Criteria criteria = checkHistoryExample.createCriteria();
        if (StringUtils.isNotBlank(loginUserId)) {
            criteria.andTaskUserIdsLike("%" + loginUserId + "%");
        }
        if (StringUtils.isNotBlank(title)) {
            criteria.andTitleLike("%" + title + "%");
        }
        if (StringUtils.isNotBlank(checkType)) {
            criteria.andChooseTypeEqualTo(checkType);
        }
        if (StringUtils.isNotBlank(startTime)) {
            criteria.andChooseTimeBetween(startTime, endTime);
        }
        if (StringUtils.isNotBlank(checkResult)) {
            if ("未开始检查".equals(checkResult)) {
                criteria.andResultEqualTo(checkResult);
            } else {
                criteria.andResultNotEqualTo("未开始检查");
            }
        }
        if (StringUtils.isNotBlank(companyName)) {
            criteria.andCompanyNameLike("%" + companyName + "%");
        }
        if (StringUtils.isNotBlank(companyId)) {
            criteria.andCompanyIdEqualTo(companyId);
        }
        if (StringUtils.isNotBlank(taskUsers)) {
            criteria.andTaskUsersLike("%" + taskUsers + "%");
        }
        checkHistoryExample.setOrderByClause(" create_time desc");
        List<VisitDrCheckHistory> list = visitDrCheckHistoryService.selectByExample(checkHistoryExample);

        PageInfo<VisitDrCheckHistory> pageInfo = new PageInfo<>(list);
        return AjaxResult.success(pageInfo);
    }

    //获取双随机任务列表
    @GetMapping(value = "/getVisitDrTaskList_old")
    public AjaxResult getVisitDrTaskList_old(@RequestParam(value = "loginUserId", required = false) String loginUserId,
                                             @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                             @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                             @RequestParam(value = "title", required = false) String title) {

        PageHelper.startPage(pageNum, pageSize);
        VisitDrCheckHistoryExample checkHistoryExample = new VisitDrCheckHistoryExample();
        VisitDrCheckHistoryExample.Criteria criteria = checkHistoryExample.createCriteria();
        if (StringUtils.isNotBlank(loginUserId)) {
            criteria.andTaskUserIdsLike("%" + loginUserId + "%");
        }
        if (StringUtils.isNotBlank(title)) {
            criteria.andTitleLike("%" + title + "%");
        }
        checkHistoryExample.setOrderByClause(" create_time desc");
        List<VisitDrCheckHistory> list = visitDrCheckHistoryService.selectByExample(checkHistoryExample);
        PageInfo<VisitDrCheckHistory> pageInfo = new PageInfo<>(list);
        return AjaxResult.success(pageInfo);
    }

    //获取双随机任务详情
    @GetMapping(value = "/getVisitDrTaskDetail")
    public AjaxResult getVisitDrTaskDetail(@RequestParam(value = "checkId") String checkId) {
        VisitDrCheckHistory checkHistory = visitDrCheckHistoryService.selectByPrimaryKey(checkId);
        VisitDrTaskUserExample userExample = new VisitDrTaskUserExample();
        VisitDrTaskUserExample.Criteria userCriteria = userExample.createCriteria();
        userCriteria.andTaskIdEqualTo(checkHistory.getTaskId());
        List<VisitDrTaskUser> userList = visitDrTaskUserService.selectByExample(userExample);
        if (checkHistory != null) {
            checkHistory.setUserList(userList);
        }
        List<VisitDrCheckFormExt> formExtList = new ArrayList<>();
        if (StringUtils.isNotBlank(checkHistory.getChooseForm())) {
            List<String> formIds = Arrays.asList(checkHistory.getChooseForm().split(","));
            for(String formId : formIds){
                VisitDrCheckHistoryFormExample example = new VisitDrCheckHistoryFormExample();
                VisitDrCheckHistoryFormExample.Criteria criteria = example.createCriteria();
                criteria.andHistoryIdEqualTo(checkId);
                criteria.andFormTypeEqualTo(formId);
                VisitDrCheckHistoryForm form = visitDrCheckHistoryFormService.selectFirstByExample(example);
                if (form != null) {
                    VisitDrCheckFormExt formExt = new VisitDrCheckFormExt();
                    BeanUtils.copyProperties(form, formExt);
                    MdForm mdForm = mdFormService.selectByPrimaryKey(formId);
                    formExt.setFormName(mdForm == null ?"":mdForm.getName());
                    formExtList.add(formExt);
                }
            }
        }
        if (StringUtils.isNotBlank(checkHistory.getChooseType())) {
            String name = bsCommonService.getName(checkHistory.getChooseType());
            checkHistory.setChooseTypeValue(name);
        }
        //双随机任务附件
        VisitDrCheckHistoryAttachExample attachExample = new VisitDrCheckHistoryAttachExample();
        VisitDrCheckHistoryAttachExample.Criteria attachCriter = attachExample.createCriteria();
        attachCriter.andCheckIdEqualTo(checkHistory.getId());
        List<VisitDrCheckHistoryAttach> attachList = attachService.selectByExample(attachExample);
        if (attachList.size() > 0) {
            checkHistory.setCheckHistoryAttachList(attachList);
        }
        VisitDrDetailForApp visitDrDetailForApp = new VisitDrDetailForApp();
        BeanUtils.copyProperties(checkHistory, visitDrDetailForApp);
        visitDrDetailForApp.setCheckHistoryFormList(formExtList);
        return AjaxResult.success(visitDrDetailForApp);
    }

    //提交检查结果
    @PostMapping(value = "/submitCheckResult")
    public AjaxResult submitCheckResult(@RequestBody VisitDrCheckResultParams checkResult) {
        if (!StringUtils.isNotBlank(checkResult.getCheckId())) {
            return AjaxResult.error(400, "检查记录id不能为空");
        }
        VisitDrCheckHistory checkModel = visitDrCheckHistoryService.selectByPrimaryKey(checkResult.getCheckId());
        //1、将随机案件实体的附件插入数据库
        if (checkResult.getCheckHistoryAttachList() != null) {
            if (checkResult.getCheckHistoryAttachList().size() > 0) {
                for (VisitDrCheckHistoryAttach checkHistoryAttach : checkResult.getCheckHistoryAttachList()) {
                    checkHistoryAttach.setId(IdUtils.fastSimpleUUID());
                    checkHistoryAttach.setCheckId(checkResult.getCheckId());
                    checkHistoryAttach.setCreateTime(DateUtil.format(LocalDateTime.now(), "yyyy-MM-dd HH:mm:ss"));
                    visitDrCheckHistoryAttachService.insert(checkHistoryAttach);
                }
            }
        }
        //2、将实体的表单以及表单附件信息插入数据库
        if (checkResult.getCheckHistoryFormList() != null) {
            if (checkResult.getCheckHistoryFormList().size() > 0) {
                for (VisitDrCheckHistoryForm checkHistoryForm : checkResult.getCheckHistoryFormList()) {
                    VisitDrCheckHistoryForm checkHistoryFormModel = visitDrCheckHistoryFormService.selectByPrimaryKey(checkHistoryForm.getId());
                    checkHistoryFormModel.setCheckContent(checkHistoryForm.getCheckContent());
                    checkHistoryFormModel.setCheckResult(checkHistoryForm.getCheckResult());
                    checkHistoryFormModel.setRemark(checkHistoryForm.getRemark());
                    visitDrCheckHistoryFormService.updateByPrimaryKey(checkHistoryFormModel);
                    if (checkHistoryForm.getAttaches() != null) {
                        if (checkHistoryForm.getAttaches().size() > 0) {
                            for (VisitDrCheckHistoryFormAttach formAttach : checkHistoryForm.getAttaches()) {
                                formAttach.setId(IdUtils.fastSimpleUUID());
                                formAttach.setFormTypeId(checkHistoryForm.getId());
                                formAttach.setCreateTime(DateUtil.format(LocalDateTime.now(), "yyyy-MM-dd HH:mm:ss"));
                                visitDrCheckHistoryFormAttachService.insert(formAttach);
                            }
                        }
                    }
                }
            }
        }
        //3、最后更新实体表签名之类的信息
        checkModel.setCheckedObject(checkResult.getCheckedObject());
        checkModel.setTelephone(checkResult.getTelephone());
        checkModel.setAddress(checkResult.getAddress());
        checkModel.setCheckUsers(checkResult.getCheckUsers());
        checkModel.setCheckTime(checkResult.getCheckTime());
        checkModel.setExtfieldTwo(checkResult.getExtfieldTwo());
        checkModel.setExtfieldThree(checkResult.getExtfieldThree());
        checkModel.setExtfieldFour(checkResult.getExtfieldFour());
        checkModel.setResult(checkResult.getResult());
        checkModel.setExtfieldFive(checkResult.getExtfieldFive());
        visitDrCheckHistoryService.updateByPrimaryKey(checkModel);
        return AjaxResult.success();
    }


    @RequestMapping(value = "delVisitDrRecord", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult delVisitDrRecord(@RequestBody VisitDrParamIds paramIds) {
        try {
            int a = visitDrCheckHistoryService.deleteByPrimaryKeys(paramIds.getIds());
            for (String id : paramIds.getIds()) {
                // 删除主表的附件
                VisitDrCheckHistoryAttachExample example1 = new VisitDrCheckHistoryAttachExample();
                VisitDrCheckHistoryAttachExample.Criteria criteria1 = example1.createCriteria();
                criteria1.andCheckIdEqualTo(id);
                visitDrCheckHistoryAttachService.deleteByExample(example1);

                // 删除从表的表单
                VisitDrCheckHistoryFormExample example2 = new VisitDrCheckHistoryFormExample();
                VisitDrCheckHistoryFormExample.Criteria criteria2 = example2.createCriteria();
                criteria2.andHistoryIdEqualTo(id);
                List<VisitDrCheckHistoryForm> lists = visitDrCheckHistoryFormService.selectByExample(example2);
                visitDrCheckHistoryFormService.deleteByExample(example2);

                // 删除表单的附件
                if (lists != null && lists.size() > 0) {
                    for (VisitDrCheckHistoryForm list : lists) {
                        VisitDrCheckHistoryFormAttachExample example3 = new VisitDrCheckHistoryFormAttachExample();
                        VisitDrCheckHistoryFormAttachExample.Criteria criteria3 = example3.createCriteria();
                        criteria3.andFormTypeIdEqualTo(list.getId());
                        visitDrCheckHistoryFormAttachService.deleteByExample(example3);
                    }
                }
            }
            if (a > 0) {
                return AjaxResult.success("删除成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(500, "服务器内部错误");
        }
        return AjaxResult.error(500, "删除失败");
    }

    //==================================私有方法private==================================================
    //生成任务并把分组数据插入到数据库
    private void createTask(String ruleId, List<VisitDrGroup> groupsList, String time, VisitDrRule rule) {

        for (VisitDrGroup group : groupsList) {
            VisitDrTask task = new VisitDrTask();
            String taskId = IdUtils.fastSimpleUUID();
            task.setId(taskId);
            task.setRuleId(ruleId);
            task.setGroupNum(group.getCurrentGroup());
            task.setCreateTime(DateUtil.format(LocalDateTime.now(), "yyyy-MM-dd HH:mm:ss"));
            task.setIsCheck("0");
            task.setIsValid("0");
            task.setCheckTime(time);
            task.setCreateBy(rule.getCreateBy());
            task.setCreateTime(rule.getCreateTime());

            //每组向用户和企业实例表插入数据
            for (VisitDrUserDataPool user : group.getUerPoolList()) {
                VisitDrTaskUser ssjTaskUser = new VisitDrTaskUser();
                ssjTaskUser.setId(IdUtils.fastSimpleUUID());
                ssjTaskUser.setTaskId(taskId);
                ssjTaskUser.setUserId(user.getUserId());
                ssjTaskUser.setUserName(user.getUserName());
                ssjTaskUser.setUserCode(user.getUserCode());
                ssjTaskUser.setUserImg(user.getUserImg());
                ssjTaskUser.setAddTime(DateUtil.format(LocalDateTime.now(), "yyyy-MM-dd HH:mm:ss"));
                visitDrTaskUserService.insert(ssjTaskUser);
            }
            for (VisitDrCompanyDataPool company : group.getCompanyPoolList()) {
                VisitDrTaskCompany ssjTaskCompany = new VisitDrTaskCompany();
                ssjTaskCompany.setId(IdUtils.fastSimpleUUID());
                ssjTaskCompany.setTaskId(taskId);
                ssjTaskCompany.setCompanyId(company.getCompanyId());
                ssjTaskCompany.setCompanyName(company.getCompanyName());
                ssjTaskCompany.setExtfieldOne(company.getExtfieldOne());
                ssjTaskCompany.setExtfieldTwo(company.getExtfieldTwo());
                ssjTaskCompany.setAddTime(DateUtil.format(LocalDateTime.now(), "yyyy-MM-dd HH:mm:ss"));
                visitDrTaskCompanyService.insert(ssjTaskCompany);
            }
            visitDrTaskService.insert(task);
            //清除数据池中间表的数据
            visitDrCompanyDataPoolMapper.deleteAllDataByRuleId(ruleId);
            visitDrUserDataPoolMapper.deleteAllDataByRuleId(ruleId);
        }
    }


    /**
     * 获取随机数
     */
    private int getRandom(int i) {
        Random r = new Random();
        return r.nextInt(i);
    }

    /**
     * 生成符合条件的企业数据
     */
    private AjaxResult generateCompanyDataPool(VisitDrRule rule, String ruleId) {
        //首选清空临时表数据
        visitDrCompanyDataPoolMapper.deleteAllDataByRuleId(ruleId);
//        if (StringUtils.isNotBlank(rule.getIsChooseCreditRatio())) {
//            if (rule.getIsChooseCreditRatio().equals("1")) {
//                int companyNum = Integer.parseInt(rule.getChooseCompanyNum());
//                //综合信用为A的企业数量
//                int companyCreditANum = (int) Math.round(companyNum * (Double.parseDouble(rule.getCreditA()) / 100));
//                int companyCreditBNum = (int) Math.round(companyNum * (Double.parseDouble(rule.getCreditB()) / 100));
//                int companyCreditCNum = (int) Math.round(companyNum * (Double.parseDouble(rule.getCreditC()) / 100));
//                int companyCreditDNum = (int) Math.round(companyNum * (Double.parseDouble(rule.getCreditD()) / 100));
//            }
//        }

        //不加任何条件抽取企业数据池
        List<GridCompany> list = new ArrayList<>();
        if (StringUtils.isNotBlank(rule.getChooseCompanyType())) {
            doRandom(rule, list);
        } else {
            list = gridCompanyService.selectByRandom(Integer.parseInt(rule.getChooseCompanyNum()), null);

        }
        if (list.size() != Integer.parseInt(rule.getChooseCompanyNum())) {
            for (int i = 0; i <= 20; i++) {
                list.clear();
                if (StringUtils.isNotBlank(rule.getChooseCompanyType())) {
                    doRandom(rule, list);
                } else {
                    list = gridCompanyService.selectByRandom(Integer.parseInt(rule.getChooseCompanyNum()), null);
                    if (list.size() >= Integer.parseInt(rule.getChooseCompanyNum())) {
                        break;
                    }
                }
            }
        }

        if (list.size() < Integer.parseInt(rule.getChooseCompanyNum())) {
            return AjaxResult.error(400, "符合条件的企业小于抽取企业数量");
        } else {
            for (GridCompany company : list) {
                VisitDrCompanyDataPool dataPool = new VisitDrCompanyDataPool();
                dataPool.setId(IdUtils.fastSimpleUUID());
                dataPool.setRuleId(ruleId);
                dataPool.setCompanyId(company.getId());
                dataPool.setCompanyName(company.getCompanyName());
                //dataPool.setExtfieldOne(company.getZhCreditLevel());
                dataPool.setExtfieldTwo(company.getCreditCode());
                visitDrCompanyDataPoolMapper.insert(dataPool);
            }

        }
        return AjaxResult.success();
    }

    private void doRandom(VisitDrRule rule, List<GridCompany> list) {
        String[] typeStringList = rule.getChooseCompanyType().split(",");
        for (String chooseType : typeStringList) {
            List<GridCompany> listTemp = gridCompanyService.selectByRandom(Integer.parseInt(rule.getChooseCompanyNum()) - list.size(), chooseType);
            list.addAll(listTemp);
            if (list.size() >= Integer.parseInt(rule.getChooseCompanyNum())) {
                break;
            }
        }
    }

    /**
     * 生成符合条件的执法人员数据
     */
    private AjaxResult generateUserDataPool(VisitDrRule rule, String ruleId) {
        //首选清空临时表数据
        visitDrUserDataPoolMapper.deleteAllDataByRuleId(ruleId);

        List<GridRegionUser> list = gridRegionUserService.selectRandom(Integer.parseInt(rule.getChoosePeopleNum()));

        if (list.size() < Integer.parseInt(rule.getChoosePeopleNum())) {
            visitDrCompanyDataPoolMapper.deleteAllDataByRuleId(ruleId);
            return AjaxResult.build(400, "符合条件的执法人员小于抽取执法人员数量");
        } else {
            for (GridRegionUser user : list) {

                SysUser sysUser = sysUserService.selectUserById(user.getUserId());
                VisitDrUserDataPool dataPool = new VisitDrUserDataPool();
                dataPool.setId(IdUtils.fastSimpleUUID());
                dataPool.setRuleId(ruleId);
                dataPool.setUserCode(user.getUserId());
                dataPool.setUserId(user.getUserId());
                dataPool.setUserImg(sysUser != null?sysUser.getAvatar():"");
                dataPool.setUserName(user.getYlzd1());
                visitDrUserDataPoolMapper.insert(dataPool);
            }
            return AjaxResult.success();
        }
    }

    /**
     * 表单验证
     */
    private AjaxResult validation(VisitDrRule rule) {

        if (!StringUtils.isNotBlank((rule.getTitle()))) {
            return AjaxResult.error(400, "请输入标题");
        }
        if (!StringUtils.isNotBlank(rule.getChoosePeopleNum())) {
            return AjaxResult.error(400, "执法人员数不能为空");
        } else {
            //判断所选人数和数据库中的总人数
            GridRegionUserExample userExample = new GridRegionUserExample();
            GridRegionUserExample.Criteria ca = userExample.createCriteria();
            ca.andIsValidEqualTo("1");
            int userCount = gridRegionUserService.countByExample(userExample);
            if (Integer.parseInt(rule.getChoosePeopleNum()) > userCount) {
                return AjaxResult.build(400, "输入的执法人员数大于符合条件的执法人员数");
            }
        }
        if (!StringUtils.isNotBlank(rule.getChoosePeopleGroup())) {
            return AjaxResult.error(400, "组数不能为空");
        }
        if (Integer.parseInt(rule.getChoosePeopleGroup()) > Integer.parseInt(rule.getChoosePeopleNum())) {
            return AjaxResult.error(400, "组数不能大于执法人员数");
        }
        //勾选了综合信用比例
        if (StringUtils.isNotBlank(rule.getIsChooseCreditRatio())) {
            if (rule.getIsChooseCreditRatio().equals("1")) {
                if (!StringUtils.isNotBlank(rule.getCreditA())) {
                    return AjaxResult.error(400, "综合信用比例为A的百分比值可以为0,但不能为空");
                }
                if (!StringUtils.isNotBlank(rule.getCreditB())) {
                    return AjaxResult.error(400, "综合信用比例为A的百分比值可以为0,但不能为空");
                }
                if (!StringUtils.isNotBlank(rule.getCreditC())) {
                    return AjaxResult.error(400, "综合信用比例为A的百分比值可以为0,但不能为空");
                }
                if (!StringUtils.isNotBlank(rule.getCreditD())) {
                    return AjaxResult.error(400, "综合信用比例为A的百分比值可以为0,但不能为空");
                }
                if ((Integer.parseInt(rule.getCreditA()) + Integer.parseInt(rule.getCreditB()) + Integer.parseInt(rule.getCreditC()) + Integer.parseInt(rule.getCreditD())) != 100) {
                    return AjaxResult.error(400, "综合信用比例为ABCD的百分比值相加要为100");
                }
            }
        }
        //抽查企业对象数要大于组数
        if (!StringUtils.isNotBlank(rule.getChooseCompanyNum())) {
            return AjaxResult.error(400, "抽查企业对象数不能为空");
        } else {

            if (Integer.parseInt(rule.getChooseCompanyNum()) < Integer.parseInt(rule.getChoosePeopleGroup())) {
                return AjaxResult.error(400, "抽查企业对象数不能小于分组数");
            }
        }
        return AjaxResult.success();
    }

    @GetMapping("/app/checkStatistics")
    public AjaxResult getAppCheckStatistics(@RequestParam(value = "startDate", required = false)String startDate,
                                                      @RequestParam(value = "endDate", required = false)String endDate){
        LoginUser sysUser = getLoginUser();
        VisitDrCheckHistoryExample checkHistoryExample = new VisitDrCheckHistoryExample();
        VisitDrCheckHistoryExample.Criteria criteria = checkHistoryExample.createCriteria();
        criteria.andCheckUsersLike("%" + sysUser.getUser().getNickName() + "%");
        if (StringUtils.isNotBlank(startDate)) {
            criteria.andChooseTimeBetween(startDate, endDate);
        }
        int all = visitDrCheckHistoryService.countByExample(checkHistoryExample);
        criteria.andResultNotEqualTo("未开始检查");
        int done = visitDrCheckHistoryService.countByExample(checkHistoryExample);
        Map<String,Integer> map = new HashMap<>();
        map.put("all", all);
        map.put("done", done);
        return AjaxResult.success(map);
    }
}
