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

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.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import org.jeecg.modules.stm.metric.entity.MetricTaskAlloc;
import org.jeecg.modules.stm.metric.pojo.QueryMetricTaskAllocVo;
import org.jeecg.modules.stm.metric.service.IMetricStatSetService;
import org.jeecg.modules.stm.metric.service.IMetricTaskAllocService;
import org.jeecg.modules.stm.my.service.IMyTaskService;
import org.jeecg.modules.stm.utils.MessageParam;
import org.jeecg.modules.stm.utils.SendMessageUtil;

import org.jeecg.modules.system.entity.SysUser;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @Description: 任务分配
 * @Author: jeecg-boot
 * @Date:   2023-07-15
 * @Version: V1.0
 */

@RestController
@RequestMapping("/metric/metricTaskAlloc")
@Slf4j
public class MetricTaskAllocController extends JeecgController<MetricTaskAlloc, IMetricTaskAllocService> {
	@Autowired
	private IMetricTaskAllocService metricTaskAllocService;
	@Autowired
	private ISysBaseAPI sysBaseAPI;
	@Autowired
	private ISysUserService sysUserService;
	@Autowired
	private IMyTaskService myTaskService;

	@Autowired
	private IMetricStatSetService metricStatSetService;

	//@AutoLog(value = "任务分配-分页列表查询")

	@GetMapping(value = "/list")
	public Result<IPage<QueryMetricTaskAllocVo>> queryPageList(QueryMetricTaskAllocVo queryMetricTaskAllocVo,
															   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
															   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
															   HttpServletRequest req) {

		Page<QueryMetricTaskAllocVo> page = new Page<QueryMetricTaskAllocVo>(pageNo, pageSize);
		IPage<QueryMetricTaskAllocVo> pageList = metricTaskAllocService.queryMonitorSet(page,queryMetricTaskAllocVo);
		return Result.OK(pageList);
	}


	/**
	 *   添加
	 *
	 * @param metricTaskAlloc
	 * @return
	 */
	@AutoLog(value = "任务分配-添加")

	@RequiresPermissions("metric:metric_task_alloc:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody MetricTaskAlloc metricTaskAlloc) {
		String mtrcNos= metricTaskAlloc.getMtrcNo();
		String[] tmpAry = mtrcNos.split(",");

		QueryWrapper<MetricTaskAlloc> queryWrapper = new QueryWrapper<>();
		queryWrapper.in("mtrc_no",tmpAry);
		List<MetricTaskAlloc>  listOld = metricTaskAllocService.list(queryWrapper);
		Map<String,Integer> existMap = new HashMap<String,Integer>();

		String strRreporters = metricTaskAlloc.getReporter();
		List<String> reporters = new ArrayList<>();
		if(strRreporters!=null) {
			reporters = Arrays.asList(strRreporters.split(","));
		}
		List<Integer> deleteIdList = new ArrayList<>();
		List<String> deleteUserIdList = new ArrayList<>();
		for(int i=0;i<listOld.size();i++){
			String uid = listOld.get(i).getReporter();
			String strKey = listOld.get(i).getMtrcNo()+"_" +uid;
			existMap.put(strKey,listOld.get(i).getId());
			if(!reporters.contains(uid)) {
				deleteIdList.add(listOld.get(i).getId());
			}
			if(!deleteUserIdList.contains(uid)){
				deleteUserIdList.add(uid);
			}
		}
		if(deleteIdList.size()>0) {
			metricTaskAllocService.removeBatchByIds(deleteIdList);
		}
		if(deleteUserIdList.size()>0) {
			List<SysUser>  userDeleteList = sysUserService.listByIds(deleteUserIdList);
			for(SysUser sysUser:userDeleteList) {
				sendDeleteAllocMsg(sysUser);
			}
		}
		List<MetricTaskAlloc> mtList = new ArrayList<>();
		List<String> noSendMsgUser = new ArrayList<>()
;		for(int i=0;i<tmpAry.length;i++) {
			for(String uid:reporters) {
				MetricTaskAlloc mt = new MetricTaskAlloc();
				String strKey = tmpAry[i]+"_" +uid;
				if(existMap.get(strKey)!=null) {
					if(!noSendMsgUser.contains(uid)) {
						noSendMsgUser.add(uid);
					}
					continue;
				}
				mt.setMtrcNo(tmpAry[i]);
				mt.setAllocSta(1);
				mt.setReporter(uid);
				mtList.add(mt);
			}
		}
		metricTaskAllocService.saveOrUpdateBatch(mtList);
		List<SysUser>  userList = sysUserService.listByIds(reporters);
		for(SysUser sysUser:userList) {
			if(noSendMsgUser.contains(sysUser.getId())) {
				continue;
			}
			sendAllocMsg(sysUser);
			myTaskService.addMyTaskForMetrc(tmpAry, sysUser.getId());
		}
		return Result.OK("保存成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param metricTaskAlloc
	 * @return
	 */
	@AutoLog(value = "任务分配-编辑")

	@RequiresPermissions("metric:metric_task_alloc:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody MetricTaskAlloc metricTaskAlloc) {
		metricTaskAllocService.updateById(metricTaskAlloc);
		String uid = metricTaskAlloc.getReporter();
		String[] mtrcNos = new String[]{metricTaskAlloc.getMtrcNo()};
		myTaskService.addMyTaskForMetrc(mtrcNos,uid);
		return Result.OK("保存成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "任务分配-通过id删除")

	@RequiresPermissions("metric:metric_task_alloc:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		metricTaskAllocService.removeById(id);
		return Result.OK("删除成功!");
	}


	@PostMapping(value = "/deleteTaskAlloc")
	public Result<String> deleteTaskAlloc(@RequestBody List<String> mtrcNos) {
		if(mtrcNos!=null&&mtrcNos.size()>0) {
			QueryWrapper<MetricTaskAlloc> queryWrapper = new QueryWrapper<>();
			queryWrapper.in("mtrc_no",mtrcNos);
			metricTaskAllocService.remove(queryWrapper);
		}
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "任务分配-批量删除")

	@RequiresPermissions("metric:metric_task_alloc:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.metricTaskAllocService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "任务分配-通过id查询")

	@GetMapping(value = "/queryById")
	public Result<MetricTaskAlloc> queryById(@RequestParam(name="id",required=true) String id) {
		MetricTaskAlloc metricTaskAlloc = metricTaskAllocService.getById(id);
		if(metricTaskAlloc==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(metricTaskAlloc);
	}

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

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

	private void sendAllocMsg(SysUser sysUser) {
		MessageParam messageParam = new MessageParam();
		SendMessageUtil sendMessageUtil = new SendMessageUtil(sysBaseAPI);
		messageParam.setMsgTitle("监控任务填报通知");
		String strContent = "<a href='/metric/metricReportIndex'>您有风险监控填报任务，请及时填报！</a>";
		messageParam.setContent(strContent);
		messageParam.setReceiver(sysUser.getUsername());
		messageParam.setTemplateCode("sys_ts_note");
		messageParam.setMsgType("system");
		sendMessageUtil.sendMessage(messageParam);
	}

	private void sendDeleteAllocMsg(SysUser sysUser) {
		MessageParam messageParam = new MessageParam();
		SendMessageUtil sendMessageUtil = new SendMessageUtil(sysBaseAPI);
		messageParam.setMsgTitle("监控填报任务取消通知");
		String strContent = "您的填报工作已经取消！";
		messageParam.setContent(strContent);
		messageParam.setReceiver(sysUser.getUsername());
		messageParam.setTemplateCode("sys_ts_note");
		messageParam.setMsgType("system");
		sendMessageUtil.sendMessage(messageParam);
	}

}
