package org.jeecg.modules.stm.project.create.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
 
 
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.modules.stm.act.check.entity.StCaMainCheck;
import org.jeecg.modules.stm.act.check.service.IStCaMainCheckService;
import org.jeecg.modules.stm.act.collection.entity.StCaMainRelCollection;
import org.jeecg.modules.stm.act.collection.service.IStCaMainRelCollectionService;
import org.jeecg.modules.stm.act.main.entity.StCaMain;
import org.jeecg.modules.stm.act.main.service.IStCaMainService;
import org.jeecg.modules.stm.project.create.entity.*;
import org.jeecg.modules.stm.project.create.service.*;
import org.jeecg.modules.stm.project.create.vo.PrepareConfigVo;
import org.jeecg.modules.stm.project.create.vo.StProjectCheckBatchVo;
import org.jeecg.modules.stm.project.create.vo.StProjectGatherBatchVo;
import org.jeecg.modules.stm.project.create.vo.StProjectInterviewBatchVo;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.service.ISysDepartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import org.jeecg.modules.stm.utils.UserUtil;

import jakarta.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.stream.Collectors;

  
@RestController
@RequestMapping("/project.create/stProjectPrepare")
@Slf4j
public class StProjectPrepareController {

    @Autowired
    private IStProjectPerpetrateService iStProjectPerpetrateService;

    @Autowired
    private IStProjectCheckService iStProjectCheckService;

    @Autowired
    private IStCaMainService iStCaMainService;

    @Autowired
    private IStProjectGatherService iStProjectGatherService;

    @Autowired
    private IStProjectInterviewService iStProjectInterviewService;

    @Autowired
    private ISysDepartService iSysDepartService;
    @Autowired
    private IStCaMainRelCollectionService stCaMainRelCollectionService;

    @Autowired
    private IStCaMainCheckService stCaMainCheckService;

      
    @GetMapping(value = "/perpetratePageList")
    public Result<IPage<StProjectPerpetrate>> perpetratePageList(StProjectPerpetrate stProjectPerpetrate,
                                                                 @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                                 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                                                 HttpServletRequest req) {
        QueryWrapper<StProjectPerpetrate> queryWrapper = QueryGenerator.initQueryWrapper(stProjectPerpetrate, req.getParameterMap());
        Page<StProjectPerpetrate> page = new Page<StProjectPerpetrate>(pageNo, pageSize);
        IPage<StProjectPerpetrate> pageList = iStProjectPerpetrateService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

      
    @GetMapping(value = "/queryPerpetratePageList")
    public Result<List<StProjectPerpetrate>> queryPerpetratePageList(StProjectPerpetrate stProjectPerpetrate,HttpServletRequest req) {
        QueryWrapper<StProjectPerpetrate> queryWrapper = QueryGenerator.initQueryWrapper(stProjectPerpetrate, req.getParameterMap());
        List<StProjectPerpetrate> pageList = iStProjectPerpetrateService.list(queryWrapper);
        return Result.OK(pageList);
    }

      
    @GetMapping(value = "/checklist")
    public Result<IPage<StProjectCheck>> queryCheckPageList(StProjectCheck stProjectCheck,
                                                            @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                            @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                                            HttpServletRequest req) {
        QueryWrapper<StProjectCheck> queryWrapper = QueryGenerator.initQueryWrapper(stProjectCheck, req.getParameterMap());
        String domainCode = req.getParameter("domainCode");
        if(StringUtils.isNotEmpty(domainCode)){
            QueryWrapper<StCaMain> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.select("CA_NO");
            queryWrapper1.eq("DOMAIN_CODE",domainCode);
            List<StCaMain> caMainList = iStCaMainService.list(queryWrapper1);
            if(CollectionUtils.isEmpty(caMainList)){
                queryWrapper.eq("CA_NO", "noExist");
            }else {
                List<String> caNos = caMainList.stream().map(StCaMain::getCaNo).collect(Collectors.toList());
                queryWrapper.in("CA_NO", caNos);
            }
        }
        Page<StProjectCheck> page = new Page<StProjectCheck>(pageNo, pageSize);
        IPage<StProjectCheck> pageList = iStProjectCheckService.page(page, queryWrapper);
        return Result.OK(pageList);
    }


      
    @GetMapping(value = "/gatherlist")
    public Result<IPage<StProjectGather>> queryGatherlistPageList(StProjectGather stProjectGather,
                                                                  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                                  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                                                  HttpServletRequest req) {
        QueryWrapper<StProjectGather> queryWrapper = QueryGenerator.initQueryWrapper(stProjectGather, req.getParameterMap());
        Page<StProjectGather> page = new Page<StProjectGather>(pageNo, pageSize);
        IPage<StProjectGather> pageList = iStProjectGatherService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

      
    @GetMapping(value = "/interviewlist")
    public Result<IPage<StProjectInterview>> queryInterviewlistPageList(StProjectInterview stProjectInterview,
                                                                        @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                                        @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                                                        HttpServletRequest req) {
        QueryWrapper<StProjectInterview> queryWrapper = QueryGenerator.initQueryWrapper(stProjectInterview, req.getParameterMap());
        Page<StProjectInterview> page = new Page<StProjectInterview>(pageNo, pageSize);
        IPage<StProjectInterview> pageList = iStProjectInterviewService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

      
    @GetMapping(value = "/queryNoCheckCount")
    public Result<Long> queryNoCheckCount(Integer projectCreId){
        QueryWrapper<StProjectCheck> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("PROJECT_CRE_ID",projectCreId);
        queryWrapper.eq("CONFIG_STATUS","0");
        long count = iStProjectCheckService.count(queryWrapper);
        return Result.OK(count);
    }

      
    @GetMapping(value = "/queryNoDutyCount")
    public Result<Long> queryNoDutyCount(Integer projectCreId){
        QueryWrapper<StProjectCheck> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("PROJECT_CRE_ID",projectCreId);
        queryWrapper.eq("DUTY_STATUS","0");
        long count = iStProjectCheckService.count(queryWrapper);
        return Result.OK(count);
    }

      
    @GetMapping(value = "/queryNoGatherCount")
    public Result<Long> queryNoGatherCount(Integer projectCreId){
        QueryWrapper<StProjectGather> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("PROJECT_CRE_ID",projectCreId);
        queryWrapper.eq("DUTY_STATUS","0");
        long count = iStProjectGatherService.count(queryWrapper);
        return Result.OK(count);
    }

      
    @GetMapping(value = "/queryNoInterviewCount")
    public Result<Long> queryNoInterviewCount(Integer projectCreId){
        QueryWrapper<StProjectInterview> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("PROJECT_CRE_ID",projectCreId);
        queryWrapper.eq("DUTY_STATUS","0");
        long count = iStProjectInterviewService.count(queryWrapper);
        return Result.OK(count);
    }

    @AutoLog(value = "项目实施人员信息-添加")
      
    @RequiresPermissions("project.create:st_project_cre:add")
    @PostMapping(value = "/addPerpetrate")
    public Result<String> addPerpetrate(@RequestBody StProjectPerpetrate stProjectPerpetrate) {
        iStProjectPerpetrateService.save(stProjectPerpetrate);
        return Result.OK("添加成功！");
    }
    @PostMapping(value = "/addBatchProjectCheck")
    public Result<String> addBatchProjectCheck(@RequestBody JSONObject jsonObject) {
        JSONArray cnosAry = jsonObject.getJSONArray("canos");
        Integer projectCreId = jsonObject.getInteger("projectCreId");
        if(cnosAry!=null&&cnosAry.size()>0){
            QueryWrapper<StProjectCheck> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.eq("project_cre_id", projectCreId);
            queryWrapper2.in("ca_no", cnosAry);
            List<StProjectCheck>  listExit = iStProjectCheckService.list(queryWrapper2);

            Map<String,StProjectCheck> existMap = new HashMap<>();
            for(int j=0;j<listExit.size();j++) {
                StProjectCheck check = listExit.get(j);
                existMap.put(check.getProjectCreId()+"_"+check.getCaNo(),check);
            }

            QueryWrapper<StCaMainCheck> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("ca_no", cnosAry);
            List<StCaMainCheck>  listStMainCheck = stCaMainCheckService.list(queryWrapper);
            List<StProjectCheck> list = new ArrayList();

            Map<String,String> contentMap = new HashMap<>();
            for(int j=0;j<listStMainCheck.size();j++) {
                StCaMainCheck check = listStMainCheck.get(j);
                contentMap.put(check.getCaNo(),check.getCheckContent());
            }

            for(int i=0;i<cnosAry.size();i++){
                String caNo = cnosAry.getString(i);
                StProjectCheck stProjectCheck = existMap.get(projectCreId+"_"+caNo);
                if(stProjectCheck!=null) {
                    continue;
                }
                StProjectCheck stpCheck = new StProjectCheck();
                stpCheck.setProjectCreId(projectCreId);
                stpCheck.setConfigStatus("0");
                stpCheck.setCheckContent(contentMap.get(caNo));
                stpCheck.setCaNo(caNo);
                list.add(stpCheck);
            }
            if(list.size()>0) {
                iStProjectCheckService.saveBatch(list);
            }
        }
        return Result.OK("添加成功！");
    }

    @PostMapping(value = "/addByActCollenct")
    public Result<String> addByActCollenct(@RequestBody JSONObject jsonObject) {
        Integer projectCreId = jsonObject.getIntValue("projectCreId");
        JSONArray cnosArray = jsonObject.getJSONArray("cnos");
        if(cnosArray!=null&&cnosArray.size()>0){
            QueryWrapper<StCaMainRelCollection> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("collection_no",cnosArray);
            List<StCaMainRelCollection> listActRel =  stCaMainRelCollectionService.list(queryWrapper);

            List<StProjectCheck> list = new ArrayList();
            List<String> listActNo = new ArrayList();
            for(int i=0;i<listActRel.size();i++){
                listActNo.add(listActRel.get(i).getCaNo());
            }
            if(listActNo.size()>0) {
                QueryWrapper<StProjectCheck> queryWrapper2 = new QueryWrapper<>();
                queryWrapper2.eq("project_cre_id",projectCreId);
                queryWrapper2.in("ca_no",listActNo);

                List<StProjectCheck>  listExit = iStProjectCheckService.list(queryWrapper2);
                Map<String,StProjectCheck> existMap = new HashMap<>();
                for(int j=0;j<listExit.size();j++) {
                    StProjectCheck check = listExit.get(j);
                    existMap.put(check.getProjectCreId()+"_"+check.getCaNo(),check);
                }

                QueryWrapper<StCaMainCheck> queryWrapper3 = new QueryWrapper<>();
                queryWrapper3.in("ca_no", listActNo);
                List<StCaMainCheck>  listStMainCheck = stCaMainCheckService.list(queryWrapper3);
                Map<String,String> contentMap = new HashMap<>();
                for(int j=0;j<listStMainCheck.size();j++) {
                    StCaMainCheck check = listStMainCheck.get(j);
                    contentMap.put(check.getCaNo(),check.getCheckContent());
                }

                for(int i=0;i<listActNo.size();i++){
                    StProjectCheck stProjectCheck = existMap.get(projectCreId+"_"+ listActNo.get(i));
                    if(stProjectCheck!=null) {
                        continue;
                    }
                    StProjectCheck stpCheck = new StProjectCheck();
                    stpCheck.setProjectCreId(projectCreId);
                    stpCheck.setConfigStatus("0");
                    stpCheck.setCheckContent(contentMap.get(listActNo.get(i)));
                    stpCheck.setCaNo(listActNo.get(i));
                    list.add(stpCheck);

                }
                iStProjectCheckService.saveBatch(list);
            }
        }
        return Result.OK("添加成功！");
    }


    @AutoLog(value = "项目实施人员信息-通过id删除")
      
    @RequiresPermissions("project.create:st_project_cre:delete")
    @DeleteMapping(value = "/deletePerpetrate")
    public Result<String> deletePerpetrate(@RequestParam(name="id",required=true) String id) {
        iStProjectPerpetrateService.removeById(id);
        return Result.OK("删除成功!");
    }

    @DeleteMapping(value = "/deleteProjectCheck")
    public Result<String> deleteProjectCheck(@RequestParam(name="id",required=true) String id) {
        iStProjectCheckService.removeById(id);
        return Result.OK("删除成功!");
    }

    @AutoLog(value = "配置检查方法")
      
    @RequiresPermissions("project.create:st_project_cre:delete")
    @PostMapping(value = "/editProjectCheck")
    public Result<String> editProjectCheck(@RequestBody StProjectCheck stProjectCheck) {
       iStProjectCheckService.editProjectCheck(stProjectCheck);
        return Result.OK("配置成功!");
    }

    @AutoLog(value = "配置责任分工")
      
    @RequiresPermissions("project.create:st_project_cre:delete")
    @PostMapping(value = "/editProjectDutyCheck")
    public Result<String> editProjectDutyCheck(@RequestBody StProjectCheck stProjectCheck) {
        String userCode = UserUtil.getUserCode();
        if(stProjectCheck.getId()==null){
           throw new JeecgBootException("检查方法未发现，请刷新重试");
        }else {
            stProjectCheck.setUpdatedUser(userCode);
            stProjectCheck.setDutyStatus("1");
            iStProjectCheckService.updateById(stProjectCheck);
        }
        return Result.OK("分配成功!");
    }

    @AutoLog(value = "配置责任分工")
      
    @RequiresPermissions("project.create:st_project_cre:delete")
    @PostMapping(value = "/batchEditProjectDutyCheck")
    public Result<String> batchEditProjectDutyCheck(@RequestBody StProjectCheckBatchVo stProjectCheckBatchVo) {
        if(stProjectCheckBatchVo.getIds()==null){
            throw new JeecgBootException("检查方法未发现，请刷新重试");
        }else {
            iStProjectCheckService.batchEditProjectDutyCheck(stProjectCheckBatchVo);
        }
        return Result.OK("批量分配成功!");
    }

    @AutoLog(value = "配置责任分工")
      
    @RequiresPermissions("project.create:st_project_cre:delete")
    @PostMapping(value = "/editProjectGatherCheck")
    public Result<String> editProjectGatherCheck(@RequestBody StProjectGather stProjectGather) {
        String userCode = UserUtil.getUserCode();
        if(stProjectGather.getId()==null){
            throw new JeecgBootException("配置信息采集未发现，请刷新重试");
        }else {
            String depId = stProjectGather.getDepId();
            SysDepart sysDepart = iSysDepartService.getById(depId);
            if(sysDepart!=null){
                stProjectGather.setDepName(sysDepart.getDepartName());
            }else{
                stProjectGather.setDepName("-");
            }
            stProjectGather.setUpdatedUser(userCode);
            stProjectGather.setDutyStatus("1");
            iStProjectGatherService.updateById(stProjectGather);
        }
        return Result.OK("分配成功!");
    }

    @AutoLog(value = "配置责任分工")
      
    @RequiresPermissions("project.create:st_project_cre:delete")
    @PostMapping(value = "/upFileProjectGatherCheck")
    public Result<String> upFileProjectGatherCheck(@RequestBody StProjectGather stProjectGather) {
        String userCode = UserUtil.getUserCode();
        if(stProjectGather.getId()==null){
            throw new JeecgBootException("配置信息采集未发现，请刷新重试");
        }else {
            stProjectGather.setUpdatedUser(userCode);
            stProjectGather.setHasFile("1");
            iStProjectGatherService.updateById(stProjectGather);
        }
        return Result.OK("上传成功!");
    }

    @AutoLog(value = "配置责任分工")
      
    @RequiresPermissions("project.create:st_project_cre:delete")
    @PostMapping(value = "/batchEditProjectGatherCheck")
    public Result<String> batchEditProjectGatherCheck(@RequestBody StProjectGatherBatchVo stProjectGatherBatchVo) {
        if(stProjectGatherBatchVo.getIds()==null){
            throw new JeecgBootException("配置信息采集未发现，请刷新重试");
        }else {
            iStProjectGatherService.batchEditProjectGatherCheck(stProjectGatherBatchVo);
        }
        return Result.OK("批量分配成功!");
    }

    @AutoLog(value = "配置责任分工")
      
    @RequiresPermissions("project.create:st_project_cre:delete")
    @PostMapping(value = "/editProjectPlan")
    public Result<String> editProjectPlan(@RequestBody StProjectInterview stProjectInterview) {
        String userCode = UserUtil.getUserCode();
        if(stProjectInterview.getId()==null){
            throw new JeecgBootException("配置信息采集未发现，请刷新重试");
        }else {
            String depId = stProjectInterview.getInterviewDepId();
            SysDepart sysDepart = iSysDepartService.getById(depId);
            if(sysDepart!=null){
                stProjectInterview.setInterviewDepName(sysDepart.getDepartName());
            }else{
                stProjectInterview.setInterviewDepName("-");
            }
            stProjectInterview.setUpdatedUser(userCode);
            stProjectInterview.setDutyStatus("1");
            iStProjectInterviewService.updateById(stProjectInterview);
        }
        return Result.OK("分配成功!");
    }

    @AutoLog(value = "配置责任分工")
      
    @RequiresPermissions("project.create:st_project_cre:delete")
    @PostMapping(value = "/batchEditProjectPlan")
    public Result<String> batchEditProjectPlan(@RequestBody StProjectInterviewBatchVo stProjectInterviewBatchVo) {
        if(stProjectInterviewBatchVo.getIds()==null){
            throw new JeecgBootException("检查方法未发现，请刷新重试");
        }else {
            iStProjectInterviewService.batchEditProjectPlan(stProjectInterviewBatchVo);
        }
        return Result.OK("批量分配成功!");
    }

    @RequiresPermissions("project.create:st_project_cre:exportXls")
    @RequestMapping(value = "/exportGatherXls")
    public ModelAndView exportGatherXls(HttpServletRequest request, StProjectGather stProjectGather) {
        return iStProjectGatherService.exportGatherXls(request, stProjectGather);
    }

    @RequiresPermissions("project.create:st_project_cre:exportXls")
    @RequestMapping(value = "/exportInterviewXls")
    public ModelAndView exportInterviewXls(HttpServletRequest request, StProjectInterview stProjectInterview) {
        return iStProjectInterviewService.exportInterviewXls(request, stProjectInterview);
    }

    @GetMapping(value = "/viewPrepareConfig")
    public Result<PrepareConfigVo> viewPrepareConfig(Integer projectCreId){
        PrepareConfigVo prepareConfigVo = new PrepareConfigVo();
        if(projectCreId!=null){
            IStProjectOrgService iStProjectOrgService = SpringContextUtils.getBean(IStProjectOrgService.class);
            List<String> orgNames = iStProjectOrgService.listNamesByProjectCreId(projectCreId);
            prepareConfigVo.setOrgNames(StringUtils.join(orgNames,","));

            IStProjectUserService iStProjectUserService = SpringContextUtils.getBean(IStProjectUserService.class);
            List<String> userNames = iStProjectUserService.listNamesByProjectCreId(projectCreId);
            prepareConfigVo.setUserNames(StringUtils.join(userNames,","));

            IStProjectSysService iStProjectSysService = SpringContextUtils.getBean(IStProjectSysService.class);
            List<String> sysNames = iStProjectSysService.listNamesByProjectCreId(projectCreId);
            prepareConfigVo.setSysNames(StringUtils.join(sysNames,","));

            IStProjectOutsourcerService iStProjectOutsourcerService = SpringContextUtils.getBean(IStProjectOutsourcerService.class);
            List<String> outerNames = iStProjectOutsourcerService.listNamesByProjectCreId(projectCreId);
            prepareConfigVo.setOuterNames(StringUtils.join(outerNames,","));

            IStProjectXmService iStProjectXmService = SpringContextUtils.getBean(IStProjectXmService.class);
            List<String> xmNames = iStProjectXmService.listNamesByProjectCreId(projectCreId);
            prepareConfigVo.setXmNames(StringUtils.join(xmNames,","));
        }
        return Result.OK(prepareConfigVo);
    }

      
    @GetMapping(value = "/viewAct")
    public Result<IPage<StCaMainRelCollection>> viewAct(StProjectAct stProjectAct,
                                                        @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                        @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                                        HttpServletRequest req) {
        Integer projectCreId = stProjectAct.getProjectCreId();
        IStProjectActService iStProjectActService = SpringContextUtils.getBean(IStProjectActService.class);
        QueryWrapper<StProjectAct> stProjectActQueryWrapper = new QueryWrapper<>();
        stProjectActQueryWrapper.eq("PROJECT_CRE_ID",projectCreId);
        StProjectAct stProjectAct1 = iStProjectActService.getOne(stProjectActQueryWrapper);
        if(stProjectAct1==null){
            return Result.OK(null);
        }
        QueryWrapper<StCaMainRelCollection> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("COLLECTION_NO",stProjectAct1.getCollectionNo());
        Page<StCaMainRelCollection> page = new Page<StCaMainRelCollection>(pageNo, pageSize);
        IStCaMainRelCollectionService stCaMainRelCollectionService = SpringContextUtils.getBean(IStCaMainRelCollectionService.class);
        IPage<StCaMainRelCollection> pageList = stCaMainRelCollectionService.page(page, queryWrapper);
        return Result.OK(pageList);
    }
}
