package org.springblade.modules.wgr.info.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.excel.util.ExcelUtil;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.constant.BladeConstant;
import org.springblade.core.tool.utils.BeanUtil;
import org.springblade.core.tool.utils.DateUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.csInfo.utils.ExcelUtils;
import org.springblade.modules.rwxffkb.entity.RwxffkbEntity;
import org.springblade.modules.rwxffkb.service.IRwxffkbService;
import org.springblade.modules.system.entity.Dept;
import org.springblade.modules.system.service.IDeptService;
import org.springblade.modules.wgr.info.entity.WgrInfoEntity;
import org.springblade.modules.wgr.info.excel.WgrInfoExcel;
import org.springblade.modules.wgr.info.service.IWgrInfoService;
import org.springblade.modules.wgr.info.vo.WgrInfoVO;
import org.springblade.modules.wgr.info.wrapper.WgrInfoWrapper;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 出入境_外国人信息表 控制器
 *
 * @author BladeX
 * @since 2023-12-04
 */
@RestController
@AllArgsConstructor
@RequestMapping("blade-wgrinfo/wgrinfo")
@Api(value = "出入境_外国人信息表", tags = "出入境_外国人信息表接口")
public class WgrInfoController extends BladeController {

	private final IWgrInfoService wgrinfoService;

	private final IDeptService deptService;

	private final IRwxffkbService rwxffkbService;

	private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

	/**
	 * 出入境_外国人信息表 详情
	 */
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入wgrinfo")
	public R<WgrInfoVO> detail(WgrInfoEntity wgrinfo) {
		WgrInfoEntity detail = wgrinfoService.getOne(Condition.getQueryWrapper(wgrinfo));
		return R.data(WgrInfoWrapper.build().entityVO(detail));
	}
	/**
	 * 出入境_外国人信息表 分页
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入wgrinfo")
	public R<IPage<WgrInfoVO>> list(@ApiIgnore @RequestParam Map<String, Object> wgrinfo, Query query) {
		IPage<WgrInfoEntity> pages = wgrinfoService.page(Condition.getPage(query), Condition.getQueryWrapper(wgrinfo, WgrInfoEntity.class));
		return R.data(WgrInfoWrapper.build().pageVO(pages));
	}

	/**
	 * 出入境_外国人信息表 自定义分页
	 */
	@GetMapping("/page")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入wgrinfo")
	public R<IPage<WgrInfoVO>> page(@RequestParam Map<String, Object> params, Query query) {
		Dept dept = deptService.getDeptCategory(AuthUtil.getDeptId().split(",")[0]);
		params.put("deptCategory", dept.getDeptCategory());
		params.put("deptId", AuthUtil.getDeptId());
		IPage<WgrInfoVO> pages = wgrinfoService.selectWgrInfoPage(Condition.getPage(query), params);
		return R.data(pages);
	}

	/**
	 * 获取部门列表
	 */
	/*@GetMapping("/getChildren")
	public R getChildren() {
		List<Dept> dept = deptService.getDeptChildren(Long.valueOf(AuthUtil.getDeptId().split(",")[0]));
		return R.data(dept);
	}*/

	/**
	 * 下发任务
	 */
//	@PostMapping("/createRw")
//	public R createRw(@RequestParam Map<String, Object> params) {
//		RwxffkbEntity rw = new RwxffkbEntity();
//		rw.setRwly("wgr_info");
//		rw.setRwmc("外国人核查：" + params.get("ywxm"));
//		rw.setRwid(Long.valueOf(params.get("id").toString()));
//		rw.setRwxfsj(new Date());
//		rw.setSssq(Long.valueOf(params.get("deptId").toString()));
//		rw.setRwlx("外国人核查");
//		return R.data(rwxffkbService.save(rw));
//	}

	/**
	 * 出入境_外国人信息表 新增
	 */
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入wgrinfo")
	public R save(@Valid @RequestBody WgrInfoEntity wgrinfo) {
		return R.status(wgrinfoService.save(wgrinfo));
	}

	/**
	 * 出入境_外国人信息表 修改
	 */
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入wgrinfo")
	public R update(@Valid @RequestBody WgrInfoEntity wgrinfo) {
		if (null != wgrinfo.getDeptId()) {
			// deptCategory 4=市局 5=分局 6=派出所 7=社区
			Dept dept = deptService.getDeptCategory(AuthUtil.getDeptId().split(",")[0]);
			if (dept.getDeptCategory() == 4) {
				wgrinfo.setSsfjBm(wgrinfo.getDeptId());
			} else if (dept.getDeptCategory() == 5) {
				wgrinfo.setSspcsBm(wgrinfo.getDeptId());
			} else if (dept.getDeptCategory() == 6) {
				RwxffkbEntity rw = new RwxffkbEntity();
				rw.setRwly("wgr_info");
				rw.setRwmc("外国人核查：" + wgrinfo.getYwxm());
				rw.setRwid(wgrinfo.getId());
				rw.setRwxfsj(new Date());
				rw.setSssq(wgrinfo.getDeptId());
				rw.setRwlx("外国人核查");
				rwxffkbService.save(rw);
				wgrinfo.setSssqBm(wgrinfo.getDeptId());
			}
		}
		return R.status(wgrinfoService.updateById(wgrinfo));
	}

	/**
	 * 出入境_外国人信息表 市局直接下发任务到社区
	 */
	@Transactional
	@PostMapping("/rwxf")
	public R rwxf(@Valid @RequestBody WgrInfoEntity wgrinfo) {
		if (null != wgrinfo && null != wgrinfo.getSsfjBm() && null != wgrinfo.getSspcsBm() && null != wgrinfo.getSssqBm()) {
			RwxffkbEntity rw = new RwxffkbEntity();
			rw.setRwly("wgr_info");
			rw.setRwmc("外国人核查：" + wgrinfo.getYwxm());
			rw.setRwid(wgrinfo.getId());
			rw.setRwxfsj(new Date());
			rw.setSssq(wgrinfo.getSssqBm());
			rw.setRwlx("外国人核查");
			rwxffkbService.save(rw);
			return R.status(wgrinfoService.updateById(wgrinfo));
		}
		return R.fail("获取参数失败");
	}

	/**
	 * 批量下发
	 */
	@Transactional
	@PostMapping("/plxf")
	public R plxf(@RequestParam String ids) {
		String[] idList = ids.split(",");
		for (String id : idList) {
			wgrinfoService.plxf(id);
		}
		return R.success("操作成功");
	}

	/**
	 * 出入境_外国人信息表 新增或修改
	 */
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "新增或修改", notes = "传入wgrinfo")
	public R submit(@Valid @RequestBody WgrInfoEntity wgrinfo) {
		return R.status(wgrinfoService.saveOrUpdate(wgrinfo));
	}

	/**
	 * 出入境_外国人信息表 删除
	 */
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "逻辑删除", notes = "传入ids")
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		return R.status(wgrinfoService.deleteLogic(Func.toLongList(ids)));
	}

	/**
	 * 模板下载
	 */
	@PostMapping("/template-downLoad")
	public void csxzmb(HttpServletResponse response) {
		List<Object> head = Arrays.asList("证件号码", "证件种类", "国家地区", "英文姓名", "性别", "出生日期", "居留事由", "居住地详细地址", "居住地所在区县", "录入时间", "联系电话", "居留证许可(签证)号码", "工作单位");
		List<List<Object>> list = new ArrayList<>();
		list.add(head);
		ExcelUtils.export(response, "外国人模板", list);
	}

	/**
	 * 外国人导入
	 */
	/*@Transactional
	@PostMapping("/import-wgrinfo")
	public R importWgrinfo(MultipartFile file) {
		List<WgrInfoExcel> list = ExcelUtil.read(file, WgrInfoExcel.class);
		int insert = 0;
		int update = 0;
		for (WgrInfoExcel wgrInfoExcel : list) {
			if (StringUtils.isBlank(wgrInfoExcel.getGjdq()) || StringUtils.isBlank(wgrInfoExcel.getYwxm()) || StringUtils.isBlank(wgrInfoExcel.getCsrq())) {
				return R.fail("国家地区/英文姓名/出生日期 不能为空");
			}
			Dept dept = deptService.selectFjNameByJzdqx(wgrInfoExcel.getJzdqx());
			if (dept == null){
				return R.fail("居住地所在区县与分局名称不对应，请修改后重新导入");
			}
			int isExist = wgrinfoService.getIsExist(wgrInfoExcel);
			try {
				Date csrqDate = sdf.parse(wgrInfoExcel.getCsrq().replaceAll("/", "-"));
				wgrInfoExcel.setCsrq(sdf.format(csrqDate));
			} catch (ParseException e) {
				e.printStackTrace();
				return R.fail(wgrInfoExcel.getYwxm() + "出生日期格式不正确");
			}
			if (isExist == 0) {
				WgrInfoEntity wgrInfo = new WgrInfoEntity();
				BeanUtil.copy(wgrInfoExcel, wgrInfo);
				wgrinfoService.save(wgrInfo);
				insert++;
			} else {
				wgrinfoService.updateWgrinfo(wgrInfoExcel);
				update++;
			}
		}
		return R.data("更新" + update + "条，新增" + insert + "条");
	}*/

	/**
	 * 导出数据
	 */
	@GetMapping("/export-wgrinfo")
	@ApiOperationSupport(order = 9)
	@ApiOperation(value = "导出数据", notes = "传入wgrinfo")
	public void exportWgrInfo(@ApiIgnore @RequestParam Map<String, Object> wgrinfo, BladeUser bladeUser, HttpServletResponse response) {
		QueryWrapper<WgrInfoEntity> queryWrapper = Condition.getQueryWrapper(wgrinfo, WgrInfoEntity.class);
		//if (!AuthUtil.isAdministrator()) {
		//	queryWrapper.lambda().eq(WgrInfo::getTenantId, bladeUser.getTenantId());
		//}
		queryWrapper.lambda().eq(WgrInfoEntity::getIsDeleted, BladeConstant.DB_NOT_DELETED);
		List<WgrInfoExcel> list = wgrinfoService.exportWgrInfo(queryWrapper);
		ExcelUtil.export(response, "出入境_外国人信息表数据" + DateUtil.time(), "出入境_外国人信息表数据表", list, WgrInfoExcel.class);
	}

}
