package org.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 io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
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.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
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.stm.metric.entity.MetricTaskAlloc;
import org.stm.metric.pojo.QueryMetricTaskAllocVo;
import org.stm.metric.service.IMetricMonitorSetService;
import org.stm.metric.service.IMetricStatSetService;
import org.stm.metric.service.IMetricTaskAllocService;
import org.stm.my.entity.MyTask;
import org.stm.my.service.IMyTaskService;
import org.stm.utils.MessageParam;
import org.stm.utils.SendMessageUtil;

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

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

/**
 * @Description: 任务分配
 * @Author: jeecg-boot
 * @Date:   2023-07-15
 * @Version: V1.0
 */
@Api(tags="任务分配")
@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 = "任务分配-分页列表查询")
	@ApiOperation(value="任务分配-分页列表查询", notes="任务分配-分页列表查询")
	@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 = "任务分配-添加")
	@ApiOperation(value="任务分配-添加", notes="任务分配-添加")
	@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 = "任务分配-编辑")
	@ApiOperation(value="任务分配-编辑", notes="任务分配-编辑")
	@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删除")
	@ApiOperation(value="任务分配-通过id删除", notes="任务分配-通过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 = "任务分配-批量删除")
	@ApiOperation(value="任务分配-批量删除", notes="任务分配-批量删除")
	@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查询")
	@ApiOperation(value="任务分配-通过id查询", notes="任务分配-通过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);
	}

}
