package org.jeecg.modules.itdmFirstPage.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.itdmFirstPage.convert.ItdmTaskConvert;
import org.jeecg.modules.itdmFirstPage.entity.ItdmTask;
import org.jeecg.modules.itdmFirstPage.service.IItdmTaskService;

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.modules.itdmFirstPage.vo.ItdmTaskListVO;
import org.jeecg.modules.system.entity.SysUserRole;
import org.jeecg.modules.system.service.ISysRoleService;
import org.jeecg.modules.system.service.ISysUserRoleService;
import org.jeecg.modules.weituo.entity.ItdmWeituoInfo;
import org.jeecg.modules.weituo.service.IItdmWeituoInfoService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
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.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 任务表
 * @Author: jeecg-boot
 * @Date:   2023-06-03
 * @Version: V1.0
 */
@Api(tags="任务表")
@RestController
@RequestMapping("/itdmFirstPage/itdmTask")
@Slf4j
public class ItdmTaskController extends JeecgController<ItdmTask, IItdmTaskService> {
	@Autowired
	private IItdmTaskService itdmTaskService;
	@Autowired
	private ISysUserRoleService sysUserRoleService;
	@Autowired
	private ISysRoleService roleService;
	@Autowired
	private IItdmWeituoInfoService weituoInfoService;


	 /**
      * 分页列表查询
      *
      * @param itdmTask
      * @param pageNo
      * @param pageSize
      * @param req
      * @return
      */
	//@AutoLog(value = "任务表-分页列表查询")
	@ApiOperation(value="任务表-分页列表查询", notes="任务表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<List<ItdmTaskListVO>> queryPageList(ItdmTask itdmTask,
												 @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
												 @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
												 HttpServletRequest req) {
		LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		String realName = loginUser.getRealname(); // 登录人姓名

		if(!realName.equals("管理员")){
			itdmTask.setTaskUser(realName);

			SysUserRole userRole = new SysUserRole();
			userRole.setUserId(loginUser.getId());
			Wrapper<SysUserRole> userRoleWrapper = new QueryWrapper<>(userRole);
			List<SysUserRole> userRoleList = sysUserRoleService.list(userRoleWrapper);
			if(userRoleList != null && !userRoleList.isEmpty() && userRoleList.get(0)!=null){
				List<String> roles = userRoleList.stream().map(i->{
					return roleService.getById(i.getRoleId()).getRoleName();
				}).collect(Collectors.toList());

				String role = roles.get(0); // 登录人角色，一般只有一个
				itdmTask.setTaskRole(role);
				if(role.equals("经理") || role.equals("计划员")) itdmTask.setTaskUser(null);
			}
		}

		QueryWrapper<ItdmTask> queryWrapper = QueryGenerator.initQueryWrapper(itdmTask, req.getParameterMap());
		List<ItdmTask> pageList = itdmTaskService.list(queryWrapper);
		List<ItdmTaskListVO> list = pageList.stream().map(i->{
			ItdmWeituoInfo weituoInfo = weituoInfoService.getById(i.getWeituoId());
			String weituoNo = weituoInfo.getWeituoNo();
			String weituoClient = weituoInfo.getWeituoClient();
			return ItdmTaskConvert.INSTANCE.convert(i,weituoNo,weituoClient);
		}).collect(Collectors.toList());
		return Result.OK(list);
	}
//	public Result<IPage<ItdmTask>> queryPageList(ItdmTask itdmTask,
//								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
//								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
//								   HttpServletRequest req) {
//		LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//		String realName = loginUser.getRealname(); // 登录人姓名
//
//		if(!realName.equals("管理员")){
//			itdmTask.setTaskUser(realName);
//
//			SysUserRole userRole = new SysUserRole();
//			userRole.setUserId(loginUser.getId());
//			Wrapper<SysUserRole> userRoleWrapper = new QueryWrapper<>(userRole);
//			List<SysUserRole> userRoleList = sysUserRoleService.list(userRoleWrapper);
//			if(userRoleList != null && !userRoleList.isEmpty() && userRoleList.get(0)!=null){
//				List<String> roles = userRoleList.stream().map(i->{
//					return roleService.getById(i.getRoleId()).getRoleName();
//				}).collect(Collectors.toList());
//
//				String role = roles.get(0); // 登录人角色，一般只有一个
//				itdmTask.setTaskRole(role);
//			}
//		}
//
//		QueryWrapper<ItdmTask> queryWrapper = QueryGenerator.initQueryWrapper(itdmTask, req.getParameterMap());
//		Page<ItdmTask> page = new Page<ItdmTask>(pageNo, pageSize);
//		IPage<ItdmTask> pageList = itdmTaskService.page(page, queryWrapper);
//		return Result.OK(pageList);
//	}

	/**
	 *   添加
	 *
	 * @param itdmTask
	 * @return
	 */
	@AutoLog(value = "任务表-添加")
	@ApiOperation(value="任务表-添加", notes="任务表-添加")
	//@RequiresPermissions("org.jeecg.modules:itdm_task:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody ItdmTask itdmTask) {
		itdmTaskService.save(itdmTask);
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param itdmTask
	 * @return
	 */
	@AutoLog(value = "任务表-编辑")
	@ApiOperation(value="任务表-编辑", notes="任务表-编辑")
	//@RequiresPermissions("org.jeecg.modules:itdm_task:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody ItdmTask itdmTask) {
		itdmTaskService.updateById(itdmTask);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "任务表-通过id删除")
	@ApiOperation(value="任务表-通过id删除", notes="任务表-通过id删除")
	//@RequiresPermissions("org.jeecg.modules:itdm_task:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		itdmTaskService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "任务表-批量删除")
	@ApiOperation(value="任务表-批量删除", notes="任务表-批量删除")
	//@RequiresPermissions("org.jeecg.modules:itdm_task:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.itdmTaskService.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<ItdmTask> queryById(@RequestParam(name="id",required=true) String id) {
		ItdmTask itdmTask = itdmTaskService.getById(id);
		if(itdmTask==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(itdmTask);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param itdmTask
    */
    //@RequiresPermissions("org.jeecg.modules:itdm_task:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ItdmTask itdmTask) {
        return super.exportXls(request, itdmTask, ItdmTask.class, "任务表");
    }

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

}
