package org.jeecg.modules.stm.rate.controller;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.*;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.stm.rate.entity.*;
import org.jeecg.modules.stm.rate.service.*;
import org.jeecg.modules.stm.rate.vo.*;
import org.springframework.beans.factory.annotation.Value;

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.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
 
 
import org.jeecg.common.aspect.annotation.AutoLog;


/**
 * @Description: 任务分配
 * @Author: jeecg-boot
 * @Date:   2023-09-22
 * @Version: V1.0
 */
  
@RestController
@RequestMapping("/rate/rateTask")
@Slf4j
public class RateTaskController extends JeecgController<RateTask, IRateTaskService> {
	@Value("${jeecg.path.upload}")
	private String upLoadPath;
	@Autowired
	private IRateTaskService rateTaskService;
	 @Autowired
	 private IRateTaskdeptService rateTaskdeptService;
	@Autowired
	private IRateTaskdetailService rateTaskdetailService;
	@Autowired
	private IRateStdService rateStdService;
	@Autowired
	private IRateKeyitemService rateKeyitemService;
	@Autowired
	private IRateOptService rateOptService;
	@Autowired
	private IRateTaskuserService rateTaskuserService;
	@Autowired
	private IRateDomainscoreService rateDomainscoreService;
	@Autowired
	private IRateDomaininfoService rateDomaininfoService;
	/**
	 * 分页列表查询
	 *
	 * @param rateTask
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "任务分配-分页列表查询")
	  
	@GetMapping(value = "/list")
	public Result<IPage<RateTask>> queryPageList(RateTask rateTask,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		String username=sysUser.getUsername();
		String userid=sysUser.getId();

		QueryWrapper<RateTask> queryWrapper = QueryGenerator.initQueryWrapper(rateTask, req.getParameterMap());
		Page<RateTask> page = new Page<RateTask>(pageNo, pageSize);
		//IPage<RateTask> pageList = rateTaskService.page(page, queryWrapper);
		IPage<RateTask> pageList = rateTaskService.pagePrepar(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param rateTask
	 * @return
	 */
	@AutoLog(value = "任务分配-添加")
	  
	//@RequiresPermissions("rate:rate_task:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody RateTask rateTask) {
		/**
		if(rateTask.getRateApprove().equals("false")){
			rateTask.setRateApprove("0");
		}else{
			rateTask.setRateApprove("1");
		} */
		rateTaskService.save(rateTask);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param rateTask
	 * @return
	 */
	@AutoLog(value = "任务分配-编辑")
	  
	//@RequiresPermissions("rate:rate_task:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody RateTask rateTask) {
		/**if(rateTask.getRateApprove().equals("false")){
			rateTask.setRateApprove("0");
		}else{
			rateTask.setRateApprove("1");
		}*/
		rateTaskService.updateById(rateTask);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "任务分配-通过id删除")
	  
	//@RequiresPermissions("rate:rate_task:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		rateTaskService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "任务分配-批量删除")
	  
	//@RequiresPermissions("rate:rate_task:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.rateTaskService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "任务分配-通过id查询")
	  
	@GetMapping(value = "/queryById")
	public Result<RateTask> queryById(@RequestParam(name="id",required=true) String id) {
		RateTask rateTask = rateTaskService.getById(id);
		/**
		if(rateTask.getRateApprove().equals("0")){
			rateTask.setRateApprove("false");
		}else{
			rateTask.setRateApprove("true");
		}
		if(rateTask==null) {
			return Result.error("未找到对应数据");
		}*/
		return Result.OK(rateTask);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param rateTask
    */
   // @RequiresPermissions("rate:rate_task:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, RateTask rateTask) {
        return super.exportXls(request, rateTask, RateTask.class, "任务分配");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
   // @RequiresPermissions("rate:rate_task:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, RateTask.class);
    }


	 /**
	  *   任务分配数据初始化
	  *
	  * @param id
	  * @return
	  */
	 @AutoLog(value = "任务分配-数据初始化")
	   
	 //@RequiresPermissions("rate:rate_task:taskDeptInit")
	 @DeleteMapping(value = "/taskDeptInit")
	 public void taskDeptInit(@RequestParam(name="id",required=true) String id) {
		 rateTaskService.taskDeptInit(id);
		 //return Result.OK("success");
	 }

	 /**
	  *   通过id删除
	  *
	  * @param id
	  * @return
	  */
	 @AutoLog(value = "任务分配-发起填报")
	   
	 //@RequiresPermissions("rate:rate_task:updateRateTaskstatus")
	 @DeleteMapping(value = "/updateRateTaskstatus")
	 public Result<String> updateRateTaskstatus(@RequestParam(name="id",required=true) String id) {
		 //rateTaskService.removeById(id);
		 RateTask rateTask=new RateTask();
		 rateTask.setRateTaskstatus("4");
		 rateTask.setId(id);
		 rateTaskService.updateById(rateTask);
		 //根据任务id 。从taskdept 表中 找到责任部门，然后把任务和责任部门信息写入到评估表填报表中 。即taskdetail 中
		 RateTask rateTaskbean = rateTaskService.getById(id);

		 QueryWrapper<RateTaskdept> domainQueryWrapper  = new QueryWrapper<>();
		 domainQueryWrapper.eq("rate_task_id",id);
		 domainQueryWrapper.orderByAsc("rate_user");
		 List<RateTaskdept> domainlist = rateTaskdeptService.list(domainQueryWrapper);
		 List<String> userary = new ArrayList<>();
		 List<String> deptary = new ArrayList<>();
		 List<String> approveuserary = new ArrayList<>();
		 String usertemp="";
		 for(int m=0;m<domainlist.size();m++){
			 RateTaskdept deptben=domainlist.get(m);
			 if(deptben!=null&&deptben.getRateUser()!=null){
				 String userval=deptben.getRateUser();
			 	if(m==0){
					userary.add(userval);
					usertemp=userval;
					deptary.add(deptben.getRateDept());
					approveuserary.add(deptben.getOptionUser());
				}else{
			 		if(usertemp.equals(userval)){
			 			continue;
					}else{
						userary.add(userval);
						usertemp=userval;
						deptary.add(deptben.getRateDept());
						approveuserary.add(deptben.getOptionUser());
					}
				}
			 }else{
			 	continue;
			 }
		 }

		 for(int n=0;n<userary.size();n++){
			 RateTaskdetail rateTaskdetail = new RateTaskdetail();
			 rateTaskdetail.setDutyDept(deptary.get(n));
			 rateTaskdetail.setDutyUser(userary.get(n));
			 rateTaskdetail.setApproveuser(approveuserary.get(n));
			 rateTaskdetail.setRateApprove(rateTaskbean.getRateApprove());
			 rateTaskdetail.setRateDept(rateTaskbean.getRateDept());
			 rateTaskdetail.setRateTaskstatus(rateTaskbean.getRateTaskstatus());//4 未填报
			 rateTaskdetail.setRateUser(rateTaskbean.getRateUser());
			 rateTaskdetail.setRemark(rateTaskbean.getRemark());
			 rateTaskdetail.setRuleId(rateTaskbean.getRuleId());
			 rateTaskdetail.setSysOrgCode(rateTaskbean.getSysOrgCode());
			 rateTaskdetail.setTaskEndtime(rateTaskbean.getTaskEndtime());
			 rateTaskdetail.setTaskName(rateTaskbean.getTaskName());
			 rateTaskdetail.setTaskYear(rateTaskbean.getTaskYear());
			 rateTaskdetail.setCreateTime(rateTaskbean.getCreateTime());
			 rateTaskdetail.setCreateBy(rateTaskbean.getCreateBy());
			 rateTaskdetail.setRateTaskId(rateTaskbean.getId());


			 rateTaskdetailService.save(rateTaskdetail);
		 }

		 return Result.OK("发起填报成功!");
	 }


	  
	@RequestMapping(value = "/rateKeyItemTreeList", method = RequestMethod.GET)
	public Result<RateKeyIWriVo> rateKeyItemTreeList(String id){
		//System.out.println("why id------------------------- -------------------"+id);
		//传进来的 是 rate_taskdetail 表的 id ，需要使用 该bean 的 rule_id 规则id 。然后去 rate_domain 表中层层生成 评估要素 树图
		RateTaskdetail taskdetail = rateTaskdetailService.getById(id);
		String rateTaskId=taskdetail.getRateTaskId();
		String ruleId=taskdetail.getRuleId();
		//RateKeyIWriVo rateStdPfVo = rateTaskService.rateKeyItemTreeListByid(id,rateTaskId,ruleId);
		//按二次分配用户取
		RateKeyIWriVo rateStdPfVo = rateTaskService.rateKeyItemTreeListByidUser(id,rateTaskId,ruleId);

		return Result.OK(rateStdPfVo);
	}




	  
	@RequestMapping(value = "/rateStdOptionList", method = RequestMethod.GET)
	public Result<List<RateStdOptionVo>> rateStdOptionList(String key){
		List<RateStdOptionVo> list = rateStdService.rateStdOptionList(key);
		return Result.OK(list);
	}

	  
	@RequestMapping(value = "/rateKeyItemFileList", method = RequestMethod.GET)
	public Result<List<RateStdOptionVo>> rateKeyItemFileList(String key){
		List<RateStdOptionVo> list = rateKeyitemService.rateKeyItemFileList(key);
		return Result.OK(list);
	}

	  
	@RequestMapping(value = "/addRate", method = RequestMethod.POST)
	public Result<String> addRate(@RequestBody RateTbVo rateTbVo){
	 	/**
		double numf=-2D;
		double num=-1D;
		double num0=0D;
		double num1=1D;
		System.out.println("--------------------------------");
		if(numf>num){
			System.out.println("1===========   -2>-1");
		}else{
			System.out.println("1===========   -2<-1");
		}
		if(numf>num0){
			System.out.println("2===========   -2>0");
		}else{
			System.out.println("2===========   -2<0");
		}

		if(numf>num1){
			System.out.println("3===========   -2>1");
		}else{
			System.out.println("3===========   -2<1");
		}

		double jdznumf = Math.abs(numf);
		*/



		rateTaskService.addRate(rateTbVo);
		return Result.OK("保存成功");
	}

	  
	@RequestMapping(value = "/addRateOk", method = RequestMethod.POST)
	public Result<String> addRateOk(@RequestBody RateTbVo rateTbVo){
	 	//在填报完成里做维度的计算。 然后在这里做任务的分的合计
		rateTaskService.addRateOk(rateTbVo);
		String task_id = rateTbVo.getId();
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		String userid=sysUser.getId();


		QueryWrapper<RateTaskdetail> rateTaskdetailQueryWrapper = new QueryWrapper<>();
		rateTaskdetailQueryWrapper.eq("rate_task_id",task_id);
		rateTaskdetailQueryWrapper.eq("duty_user",userid);
		RateTaskdetail rateTaskdetail = rateTaskdetailService.getOne(rateTaskdetailQueryWrapper);
		rateTaskdetail.setRateTaskstatus("6");//已填报
		rateTaskdetailService.updateById(rateTaskdetail);
         //ratedept 里查询任务的用户，看这些任务是否都填报完成
		QueryWrapper<RateTaskuser> domainQueryWrapper  = new QueryWrapper<>();
		domainQueryWrapper.eq("rate_task_id",task_id);
		domainQueryWrapper.orderByAsc("rate_user");
		List<RateTaskuser> domainlist = rateTaskuserService.list(domainQueryWrapper);
		boolean isTbend =true;
		for(int i=0;i<domainlist.size();i++){
			RateTaskuser taskdept=domainlist.get(i);
			String taskuserid=taskdept.getRateUser();
			QueryWrapper<RateTaskdetail> tworateTaskdetailQueryWrapper = new QueryWrapper<>();
			tworateTaskdetailQueryWrapper.eq("rate_task_id",taskdept.getRateTaskId());
			tworateTaskdetailQueryWrapper.eq("duty_user",taskuserid);
			RateTaskdetail towrateTaskdetail = rateTaskdetailService.getOne(tworateTaskdetailQueryWrapper);
			String tasktatus = towrateTaskdetail.getRateTaskstatus();
			if(!tasktatus.equals("6")){
				isTbend = false;
			}

		}
		RateTask rateTask = rateTaskService.getById(task_id);
		RateTask rateTaskno =new RateTask();
		rateTaskno.setId(task_id);


		if(isTbend){
			//任务表更新状态

			if(rateTask.getRateApprove().equals("1")){
				//需要审批
				rateTaskno.setRateTaskstatus("6");
			}else {
				//不需要审批
				rateTaskno.setRateTaskstatus("11"); //未评分
			}
		}else{
			rateTaskno.setRateTaskstatus("5");
		}
		rateTaskService.updateById(rateTaskno);

		return Result.OK("填报完成");
	}


	  
	@RequestMapping(value = "/approverateKeyItemTreeList", method = RequestMethod.GET)
	public Result<RateKeyIWriVo> approverateKeyItemTreeList(String id){
		//System.out.println("why id------------------------- -------------------"+id);
		//传进来的 是 rate_taskdetail 表的 id ，需要使用 该bean 的 rule_id 规则id 。然后去 rate_domain 表中层层生成 评估要素 树图
		RateTaskdetail taskdetail = rateTaskdetailService.getById(id);
		String rateTaskId=taskdetail.getRateTaskId();
		String ruleId=taskdetail.getRuleId();
		//RateKeyIWriVo rateStdPfVo = rateTaskService.approverateKeyItemTreeListByid(id,rateTaskId,ruleId,taskdetail.getDutyUser());
		RateKeyIWriVo rateStdPfVo = rateTaskService.approverateKeyItemTreeListByidUser(id,rateTaskId,ruleId,taskdetail.getDutyUser());

		return Result.OK(rateStdPfVo);
	}

	  
	@RequestMapping(value = "/addAppRate", method = RequestMethod.POST)
	public Result<String> addAppRate(@RequestBody RateTbVo rateTbVo){
		rateTaskService.addRate(rateTbVo);
		rateTaskService.addAppRate(rateTbVo);
		return Result.OK("保存成功");
	}

	  
	@RequestMapping(value = "/addAppRateOk", method = RequestMethod.POST)
	public Result<String> addAppRateOk(@RequestBody RateTbVo rateTbVo){
		rateTaskService.addRateOk(rateTbVo);
		rateTaskService.addAppRate(rateTbVo);

		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		String username=sysUser.getUsername();

		QueryWrapper<RateOpt> rateOptQueryWrapper = new QueryWrapper<>();
		rateOptQueryWrapper.eq("task_id",rateTbVo.getId());
		rateOptQueryWrapper.eq("approveuser",username);
		List<RateOpt> list = rateOptService.list(rateOptQueryWrapper);
		boolean isappokend = true;  //可全部通过
		boolean isappend =true; //是否审批完成
		for(int i=0;i<list.size();i++){
			RateOpt rateOpt = list.get(i);
			String appstatus = rateOpt.getApprovestatus();
			if(appstatus!=null&&appstatus.equals("8")){

			}else if(appstatus!=null&&appstatus.equals("9")){
				isappokend=false;
			}else{
				isappokend=false;
				isappend =false;

			}
		}
		if(!isappend){
			throw new JeecgBootException("存在未完成的审核项，请检查");
		}

		RateTaskdetail rateTaskdetail =new RateTaskdetail();
		rateTaskdetail.setId(rateTbVo.getTaskdetailid());

		//如果全部审核 完，isappokend 为真； 说明都通过了
		//如果全部审核完，但是  isappreturn 为真，说明 都驳回了
		if(isappokend&&isappend){
			//任务明细表可设置任务状态为通过
			rateTaskdetail.setRateTaskstatus("8");

		}else if(isappend&&!isappokend){
			//审批完成，有驳回，
			rateTaskdetail.setRateTaskstatus("9"); //有驳回
		}
		rateTaskdetailService.updateById(rateTaskdetail);

		boolean  istaskdetailappok=true;
		boolean  istaskdetailappend=true;
		QueryWrapper<RateTaskdetail> rateTaskdetailQueryWrapper = new QueryWrapper<>();
		rateTaskdetailQueryWrapper.eq("rate_task_id",rateTbVo.getId());
		List<RateTaskdetail> RateTaskdetaillist = rateTaskdetailService.list(rateTaskdetailQueryWrapper);
		for(int j=0;j<RateTaskdetaillist.size();j++){
			RateTaskdetail RateTaskdetail=RateTaskdetaillist.get(j);
			String zt=RateTaskdetail.getRateTaskstatus();
			if(zt.equals("4")||zt.equals("5")||zt.equals("6")||zt.equals("7")){
				istaskdetailappend = false;
			}else if(zt.equals("9")){
				istaskdetailappok = false;
			}

		}

		RateTask rateTask = new RateTask();
		rateTask.setId(rateTbVo.getId());
		if(istaskdetailappok&&istaskdetailappend){
			//任务表更新状态  审核完了，且都通过
			rateTask.setRateTaskstatus("11");
		}else if(!istaskdetailappok&&istaskdetailappend){
			rateTask.setRateTaskstatus("9");
		}
		rateTaskService.updateById(rateTask);



		return Result.OK("审核完成");
	}


	  
	@GetMapping(value = "/domainScorelist")
	public Result<IPage<RateTaskOptVo>> queryDomainScoreUserPageList(String taskid,
                                                                     @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                                     @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                                                     HttpServletRequest req) {

		pageSize =65536;
		Page<RateTaskOptVo> page = new Page<RateTaskOptVo>(pageNo, pageSize);
		IPage<RateTaskOptVo> pageList = rateTaskService.queryDomainScoreUser(page, taskid);
		return Result.OK(pageList);
	}

	/**
	 * 分页列表查询
	 *
	 * @param rateTask
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "任务分配-分页列表查询")
	  
	@GetMapping(value = "/ratelist")
	public Result<IPage<RateTask>> queryPageRateList(RateTask rateTask,
												 @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
												 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
												 HttpServletRequest req) {
		QueryWrapper<RateTask> queryWrapper = QueryGenerator.initQueryWrapper(rateTask, req.getParameterMap());
		Page<RateTask> page = new Page<RateTask>(pageNo, pageSize);
		queryWrapper.inSql("rate_taskstatus","11,12,13");
		IPage<RateTask> pageList = rateTaskService.pagePrepar(page, queryWrapper);
		return Result.OK(pageList);
	}


	  
	@RequestMapping(value = "/raterateKeyItemTreeList", method = RequestMethod.GET)
	public Result<RateKeyIWriVo> raterateKeyItemTreeList(String id){
		//System.out.println("why id------------------------- -------------------"+id);
		//传进来的 是 任务id taskid

		RateKeyIWriVo rateStdPfVo = rateTaskService.raterateKeyItemTreeListByid(id);
		return Result.OK(rateStdPfVo);
	}

	  
	@RequestMapping(value = "/addRateRate", method = RequestMethod.POST)
	public Result<String> addRateRate(@RequestBody RateTbVo rateTbVo){
		rateTaskService.addRateRate(rateTbVo);

		RateTask rateTaskbean =rateTaskService.getById(rateTbVo.getId());
		if(rateTaskbean.getRateTaskstatus().equals("11")){
			RateTask rateTask = new RateTask();
			rateTask.setId(rateTbVo.getId());

			rateTask.setRateTaskstatus("12");

			rateTaskService.updateById(rateTask);
		}


		return Result.OK("保存成功");
	}

	  
	@RequestMapping(value = "/addRateRateOk", method = RequestMethod.POST)
	public Result<String> addRateRateOk(@RequestBody RateTbVo rateTbVo){
		String  pfmodel = rateTbVo.getPfmodel();
		rateTaskService.addRateRate(rateTbVo);

		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		String username=sysUser.getUsername();

		QueryWrapper<RateOpt> rateOptQueryWrapper = new QueryWrapper<>();
		rateOptQueryWrapper.eq("task_id",rateTbVo.getId());
		rateOptQueryWrapper.isNull("score");
		List<RateOpt> list = rateOptService.list(rateOptQueryWrapper);
		if(list.size()>0){
			throw new JeecgBootException("存在未完成的评分项，请检查");
		}
		//应该按维度得到维度的分，然后，将各维度的分数给合计，
		List<RateStaiVo> stailist = rateTaskService.queryTaskDomainScoreList(rateTbVo.getId());
		for(int j=0;j<stailist.size();j++){
			RateStaiVo stai=stailist.get(j);

			RateDomainscore domainscorebean = new RateDomainscore();

			QueryWrapper<RateDomainscore> rateDomaininscoreQueryWrapper = new QueryWrapper<>();
			rateDomaininscoreQueryWrapper.eq("ratedomain_id",stai.getTaskid());
			rateDomaininscoreQueryWrapper.eq("rate_task_id",rateTbVo.getId());
			RateDomainscore domainscore = rateDomainscoreService.getOne(rateDomaininscoreQueryWrapper);
			if(domainscore.getLimitstatus()!=null&&domainscore.getLimitstatus().equals("1")){
				//
				RateDomaininfo domaniinfo = rateDomaininfoService.getById(domainscore.getRatedomainId());
				if(stai.getValue()>domaniinfo.getScoremax()){
					domainscorebean.setRatescore(domaniinfo.getScoremax());
				}else{
					domainscorebean.setRatescore(stai.getValue());
				}

			}else{
				domainscorebean.setRatescore(stai.getValue());
			}
			domainscorebean.setRatescoreof(stai.getStvalue());
			domainscorebean.setId(domainscore.getId());
			rateDomainscoreService.updateById(domainscorebean);





		}
		/**
		QueryWrapper<RateOpt> rateOptQuerytwoWrapper = new QueryWrapper<>();
		rateOptQuerytwoWrapper.select("sum(score) as score,sum(scoreof) as scoreof");
		rateOptQuerytwoWrapper.eq("task_id",rateTbVo.getId());
		RateOpt rateOpt =rateOptService.getOne(rateOptQuerytwoWrapper);
		*/

		QueryWrapper<RateDomainscore> rateOptQuerytwoWrapper = new QueryWrapper<>();
		//rateOptQuerytwoWrapper.select("sum(ratescore) as ratescore,sum(ratescoreof) as ratescoreof");
		rateOptQuerytwoWrapper.select("ROUND(SUM(ratescore),2) as ratescore , ROUND(SUM(ratescoreof),2) as ratescoreof");
		rateOptQuerytwoWrapper.eq("rate_task_id",rateTbVo.getId());
		RateDomainscore rateOpt =rateDomainscoreService.getOne(rateOptQuerytwoWrapper);

		double getpf = rateOpt.getRatescore();
		double koupf = rateOpt.getRatescoreof();





		RateTask rateTask = new RateTask();
		rateTask.setId(rateTbVo.getId());
		rateTask.setRateTaskstatus("13");
		rateTask.setRatescore(getpf);
		rateTask.setRatescoreof(koupf);

		rateTaskService.updateById(rateTask);



		return Result.OK("评分完成");
	}


	  
	@RequestMapping(value = "/pfrateStdOptionList", method = RequestMethod.GET)
	public Result<List<RateStdOptionVo>> pfrateStdOptionList(String key){
		List<RateStdOptionVo> list = rateStdService.pfrateStdOptionList(key);
		return Result.OK(list);
	}

	/**
	 * 分页列表查询
	 *
	 * @param rateTask
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "评估结果-分页列表查询")
	  
	@GetMapping(value = "/rateReslist")
	public Result<IPage<RateTask>> queryPageRateResList(RateTask rateTask,
													 @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
													 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
													 HttpServletRequest req) {
		QueryWrapper<RateTask> queryWrapper = QueryGenerator.initQueryWrapper(rateTask, req.getParameterMap());
		Page<RateTask> page = new Page<RateTask>(pageNo, pageSize);
		queryWrapper.eq("rate_taskstatus","13");
		IPage<RateTask> pageList = rateTaskService.pagePrepar(page, queryWrapper);
		return Result.OK(pageList);
	}

	  
	@GetMapping(value = "/domainResScorelist")
	public Result<IPage<RateTaskOptVo>> queryDomainResScoreUserPageList(String taskid,
																	 @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
																	 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
																	 HttpServletRequest req) {
		pageSize = 65535;
		Page<RateTaskOptVo> page = new Page<RateTaskOptVo>(pageNo, pageSize);
		IPage<RateTaskOptVo> pageList = rateTaskService.queryDomainResScoreUser(page, taskid);
		return Result.OK(pageList);
	}


	/**
	 * 导出excel
	 *
	 * @param response
	 * @param taskid
	 */
	// @RequiresPermissions("rate:rate_task:exportResXls")
	@RequestMapping(value = "/exportResXls")
	public void  exportResXls(String taskid, HttpServletResponse response) {
		String title ="评估结果";
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		// Step.2 获取导出数据
		List<RateTaskOptVo > exportList = rateTaskService.queryDomainResTabScoreUser(taskid);

		try {
			// 创建Excel的工作书册 Workbook,对应到一个excel文档
			HSSFWorkbook wb = new HSSFWorkbook();

			// 创建Excel的工作sheet,对应到一个excel文档的tab
			HSSFSheet sheet = wb.createSheet("sheet1");

			// 设置excel每列宽度
			sheet.setColumnWidth(0, 4000);
			sheet.setColumnWidth(1, 10000);
			sheet.setColumnWidth(2, 16000);
			sheet.setColumnWidth(3, 4000);
			sheet.setColumnWidth(4, 4000);
			sheet.setColumnWidth(5, 4000);
			sheet.setColumnWidth(6, 10000);
			/**

			sheet.setColumnWidth(7, 4000);
			sheet.setColumnWidth(8, 4000);
			sheet.setColumnWidth(9, 4000);
			sheet.setColumnWidth(10, 4000);
			sheet.setColumnWidth(11, 4000);
			 */

			HSSFFont font = wb.createFont();
			font.setFontHeightInPoints((short)12);
			font.setFontName("宋体");

			HSSFCellStyle style = wb.createCellStyle();
			//style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//水平居中
			//style.setFillForegroundColor(HSSFColor.LIGHT_TURQUOISE.index);//背景色

			style.setFont(font);// 设置字体
			Double fen=0D;
            Double defen=0D;
            Double koufen=0D;
			// 创建Excel的sheet的一行
			HSSFRow row = sheet.createRow(0);
			row.setHeight((short) 400);// 设定行的高度
			// 创建一个Excel的单元格
			HSSFCell cell = row.createCell(0);
			cell.setCellStyle(style);
			cell.setCellValue("领域");
			HSSFCell cell1 = row.createCell(1);
			cell1.setCellValue("子领域");
			cell1.setCellStyle(style);
			HSSFCell cell2 = row.createCell(2);
			cell2.setCellValue("评估要素");
			cell2.setCellStyle(style);
			HSSFCell cell3 = row.createCell(3);
			cell3.setCellValue("分值");
			cell3.setCellStyle(style);
			HSSFCell cell4 = row.createCell(4);
			cell4.setCellValue("得分");
			cell4.setCellStyle(style);
			HSSFCell cell5 = row.createCell(5);
			cell5.setCellValue("扣分");
			cell5.setCellStyle(style);
			HSSFCell cell6 = row.createCell(6);
			cell6.setCellValue("扣分原因");
			cell6.setCellStyle(style);
			int rowid=1;
			for(int i=0;i<exportList.size();i++){
				RateTaskOptVo rateTaskOptVo = exportList.get(i);
				// 创建Excel的sheet的一行
				HSSFRow rowbean = sheet.createRow(rowid);
				rowbean.setHeight((short) 400);// 设定行的高度
				// 创建一个Excel的单元格
				HSSFCell rowcell = rowbean.createCell(0);
				rowcell.setCellStyle(style);
				rowcell.setCellValue(rateTaskOptVo.getRatedomain());
				HSSFCell rowcell1 = rowbean.createCell(1);
				rowcell1.setCellValue(rateTaskOptVo.getSondomain());
				rowcell1.setCellStyle(style);
				HSSFCell rowcell2 = rowbean.createCell(2);
				rowcell2.setCellValue(rateTaskOptVo.getKeyitem());
				rowcell2.setCellStyle(style);
				HSSFCell rowcell3 = rowbean.createCell(3);
				rowcell3.setCellValue(rateTaskOptVo.getKeyitemscore());
				rowcell3.setCellStyle(style);
				HSSFCell rowcell4 = rowbean.createCell(4);
				rowcell4.setCellValue(rateTaskOptVo.getScore());
				rowcell4.setCellStyle(style);
				HSSFCell rowcell5 = rowbean.createCell(5);
				rowcell5.setCellValue(rateTaskOptVo.getScoreof());
				rowcell5.setCellStyle(style);
				HSSFCell rowcell6 = rowbean.createCell(6);
				rowcell6.setCellValue(rateTaskOptVo.getRateremark());
				rowcell6.setCellStyle(style);
				fen=fen+Double.parseDouble(rateTaskOptVo.getKeyitemscore());
				defen=defen+Double.parseDouble(rateTaskOptVo.getScore());
				koufen=koufen+Double.parseDouble(rateTaskOptVo.getScoreof());


				rowid++;

			}

			QueryWrapper<RateDomainscore> rateDomainscoreQueryWrapper = new QueryWrapper<>();
			rateDomainscoreQueryWrapper.select("sum(ratescore) as ratescore");

			rateDomainscoreQueryWrapper.eq("rate_task_id",taskid);

			RateDomainscore rateUserscore = rateDomainscoreService.getOne(rateDomainscoreQueryWrapper);


			HSSFRow rowbeanhj = sheet.createRow(rowid);
			rowbeanhj.setHeight((short) 400);// 设定行的高度
			// 创建一个Excel的单元格
			HSSFCell hjrowcell = rowbeanhj.createCell(0);
			hjrowcell.setCellStyle(style);
			hjrowcell.setCellValue("合计");

			HSSFCell hjrowcell3 = rowbeanhj.createCell(3);
			hjrowcell3.setCellValue(fen.toString());
			hjrowcell3.setCellStyle(style);
			HSSFCell hjrowcell4 = rowbeanhj.createCell(4);
			//hjrowcell4.setCellValue(defen.toString());
			hjrowcell4.setCellValue(rateUserscore.getRatescore().toString());
			hjrowcell4.setCellStyle(style);
			HSSFCell hjrowcell5 = rowbeanhj.createCell(5);
			hjrowcell5.setCellValue(koufen.toString());
			hjrowcell5.setCellStyle(style);











		response.setContentType("application/octet-stream;charset=UTF-8");
		//String fileName = new String(filename.getBytes("gb2312"), "iso8859-1");
		response.setHeader("Content-disposition", "attachment");
		OutputStream ouputStream = response.getOutputStream();
		wb.write(ouputStream);
		//ouputStream.write(buffer);
		ouputStream.flush();
		ouputStream.close();
	} catch (Exception e) {
		e.printStackTrace();

	}


	}



	  
	@RequestMapping(value = "/rateStaiList", method = RequestMethod.GET)
	public Result<List<RateStaiVo>> rateStaiList(String taskid){
		List<RateStaiVo> list = rateTaskService.queryDomainStaiList(taskid);
		//List<RateStaiVo> list2 = rateTaskService.queryDomainScoreList(taskid);
		//List<RateStaiVo> list = new ArrayList<>();
		//list.addAll(list1);
		//list.addAll(list2);
		/**
		 List list =new ArrayList();
		 RateStaiVo vo=new RateStaiVo();
		 vo.setName("A");
		 vo.setValue(1D);
		 list.add(vo);
		 RateStaiVo vo2=new RateStaiVo();
		 vo2.setName("B");
		 vo2.setValue(10D);
		 list.add(vo2);
		 */
		return Result.OK(list);
	}

	  
	@RequestMapping(value = "/rateStaikeyitemList", method = RequestMethod.GET)
	public Result<List<RateStaiVo>> rateStaikeyitemList(String taskid){
		List<RateStaiVo> list = rateTaskService.querykeyitemStaiList(taskid);

		return Result.OK(list);
	}

	  
	@RequestMapping(value = "/rateStaiRatioList", method = RequestMethod.GET)
	public Result<List<RateStaiVo>> rateStaiRatioList(String taskid){
		List<RateStaiVo> list = rateTaskService.queryDomainScoreRatioList(taskid);
		//List<RateStaiVo> list2 = rateTaskService.queryDomainRatioList(taskid);
		//List<RateStaiVo> list = new ArrayList<>();
		//list.addAll(list1);
		//list.addAll(list2);
		return Result.OK(list);
	}


	  
	@RequestMapping(value = "/raterateKeyItemTreeViewList", method = RequestMethod.GET)
	public Result<RateKeyIWriVo> raterateKeyItemTreeViewList(String id){
		//System.out.println("why id------------------------- ---------------View----"+id);
		//传进来的 是 任务id taskid

		RateKeyIWriVo rateStdPfVo = rateTaskService.raterateKeyItemTreeViewListByid(id);
		return Result.OK(rateStdPfVo);
	}


	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "任务分配-发起填报2")
	  
	//@RequiresPermissions("rate:rate_task:updateUserRateTaskstatus")
	@DeleteMapping(value = "/updateUserRateTaskstatus")
	public Result<String> updateUserRateTaskstatus(@RequestParam(name="id",required=true) String id) {
		//判断是否都用户分配完成
		QueryWrapper<RateTaskuser> rateTaskuserQueryWrapper  = new QueryWrapper<>();
		rateTaskuserQueryWrapper.eq("rate_task_id",id);
		rateTaskuserQueryWrapper.isNull("rate_user");
		List<RateTaskuser> userlist = rateTaskuserService.list(rateTaskuserQueryWrapper);
		if(userlist.size()>0){
			return Result.error("填报人未分配完毕。请分配填报人!");

		}else {


			//rateTaskService.removeById(id);
			RateTask rateTask = new RateTask();
			rateTask.setRateTaskstatus("4");
			rateTask.setId(id);
			rateTaskService.updateById(rateTask);
			//根据任务id 。从taskdept 表中 找到责任部门，然后把任务和责任部门信息写入到评估表填报表中 。即taskdetail 中
			RateTask rateTaskbean = rateTaskService.getById(id);

			QueryWrapper<RateTaskuser> domainQueryWrapper = new QueryWrapper<>();
			domainQueryWrapper.eq("rate_task_id", id);
			domainQueryWrapper.orderByAsc("rate_user");
			List<RateTaskuser> domainlist = rateTaskuserService.list(domainQueryWrapper);
			List<String> userary = new ArrayList<>();
			List<String> deptary = new ArrayList<>();
			List<String> approveuserary = new ArrayList<>();
			String usertemp = "";
			for (int m = 0; m < domainlist.size(); m++) {
				RateTaskuser deptben = domainlist.get(m);
				if (deptben != null && deptben.getRateUser() != null) {
					String userval = deptben.getRateUser();
					if (m == 0) {
						userary.add(userval);
						usertemp = userval;
						deptary.add(deptben.getRateDept());
						approveuserary.add(deptben.getOptionUser());
					} else {
						if (usertemp.equals(userval)) {
							continue;
						} else {
							userary.add(userval);
							usertemp = userval;
							deptary.add(deptben.getRateDept());
							approveuserary.add(deptben.getOptionUser());
						}
					}
				} else {
					continue;
				}
			}

			for (int n = 0; n < userary.size(); n++) {
				RateTaskdetail rateTaskdetail = new RateTaskdetail();
				rateTaskdetail.setDutyDept(deptary.get(n));
				rateTaskdetail.setDutyUser(userary.get(n));
				rateTaskdetail.setApproveuser(approveuserary.get(n));
				rateTaskdetail.setRateApprove(rateTaskbean.getRateApprove());
				rateTaskdetail.setRateDept(rateTaskbean.getRateDept());
				rateTaskdetail.setRateTaskstatus(rateTaskbean.getRateTaskstatus());//4 未填报
				rateTaskdetail.setRateUser(rateTaskbean.getRateUser());
				rateTaskdetail.setRemark(rateTaskbean.getRemark());
				rateTaskdetail.setRuleId(rateTaskbean.getRuleId());
				rateTaskdetail.setSysOrgCode(rateTaskbean.getSysOrgCode());
				rateTaskdetail.setTaskEndtime(rateTaskbean.getTaskEndtime());
				rateTaskdetail.setTaskName(rateTaskbean.getTaskName());
				rateTaskdetail.setTaskYear(rateTaskbean.getTaskYear());
				rateTaskdetail.setCreateTime(rateTaskbean.getCreateTime());
				rateTaskdetail.setCreateBy(rateTaskbean.getCreateBy());
				rateTaskdetail.setRateTaskId(rateTaskbean.getId());


				rateTaskdetailService.save(rateTaskdetail);
			}

			return Result.OK("发起填报成功!");
		}
	}


	@RequestMapping(value = "/rateStaiSum", method = RequestMethod.GET)
	public Result<RateStaiVo> rateStaiSum(String taskid){
		List<RateStaiVo> list = rateTaskService.queryDomainStaiList(taskid);
		Double sumtj=0d;
		for(int i=0;i<list.size();i++){
			RateStaiVo svo=list.get(i);
			sumtj=sumtj+svo.getValue();

		}
		RateStaiVo vo=new RateStaiVo();
		vo.setValue(sumtj);
		return Result.OK(vo);
	}


}
