package cn.timer.api.controller.htzz;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import cn.hutool.core.util.StrUtil;
import cn.hutool.cron.CronUtil;
import cn.hutool.cron.task.Task;
import cn.timer.api.bean.htzz.HtzzAdminZzda;
import cn.timer.api.bean.htzz.HtzzAssoHtgx;
import cn.timer.api.bean.qyzx.businessService.QyzxRemainingQuantity;
import cn.timer.api.bean.yggl.YgglMainEmp;
import cn.timer.api.config.annotation.CurrentUser;
import cn.timer.api.config.annotation.UserBean;
import cn.timer.api.dao.htzz.HtzzAdminZzdaMapper;
import cn.timer.api.dto.htzz.HtzzQueryDto;
import cn.timer.api.utils.Result;
import cn.timer.api.utils.ResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(tags = "7.0合同证照")
@RestController
@Transactional
@RequestMapping(value = "/htzz", produces = { "application/json" })
public class HtzzController {

	@Autowired
	private HtzzAdminZzdaMapper htzzAdminZzdaMapper;

	// /**
	// * 新增/修改提醒组
	// */
	// @PostMapping(value = "/addTxz")
	// @ApiOperation(value = "新增提醒组", httpMethod = "POST", notes = "接口发布说明")
	// public Result<HtzzAssoZztx> addTxz(@CurrentUser UserBean userBean,
	// @RequestBody HtzzAssoZztx zztx) {
	// zztx.setLrrid(userBean.getEmpNum());
	// zztx.setLrsjTime(new Date());
	// zztx.setOrgCode(userBean.getOrgCode());
	// zztx.insertOrUpdate();
	// return ResultUtil.data(zztx, "新增/修改成功");
	// }

	/**
	 * 新增合同证件
	 * 
	 * @param userBean
	 * @param htzzAdminZzda 证照档案实体
	 * @return 新增证件结果
	 */
	@PostMapping("/addzj")
	@ApiOperation(value = "新增合同证件", httpMethod = "POST", notes = "接口发布说明")
	public Result<Object> addzj(@CurrentUser UserBean userBean, @RequestBody HtzzAdminZzda zzda) {
		Integer orgCode = userBean.getOrgCode();

		QyzxRemainingQuantity quantity = QyzxRemainingQuantity.builder().build().selectOne(
				new LambdaQueryWrapper<QyzxRemainingQuantity>().eq(QyzxRemainingQuantity::getOrgCode, orgCode)
						.eq(QyzxRemainingQuantity::getPmid, 1).gt(QyzxRemainingQuantity::getRemainder, 0));
		Date date = null;
		Integer remainder = null;
		if (quantity != null) {
			remainder = quantity.getRemainder();
			date = quantity.getExpireDate();
		}
		if (quantity == null || remainder == null || remainder <= 0) { // 判断充了钱没
			return ResultUtil.error("请充值后使用短信功能!");
		}
		if (date != null && date.getTime() <= new Date().getTime()) {
			System.err.println("企业 " + orgCode + " :短信套餐已过期");
			return ResultUtil.error("短信套餐已到期!");
		}

		zzda.setTxkgType(1);
		zzda.setLrrid(userBean.getEmpNum());
		zzda.setLrsjTime(new Date());
		zzda.setOrgCode(orgCode);
		zzda.insert();

		/**
		 * 新增通知关系表,每人一个
		 */
		YgglMainEmp emp = null;
		Integer[] ids = zzda.getIds();
		List<HtzzAssoHtgx> htgxs = new ArrayList<HtzzAssoHtgx>(ids.length);
		for (Integer id : ids) {
			QueryWrapper<YgglMainEmp> queryWrapper = new QueryWrapper<>();
			queryWrapper.select("name", "phone", "emp_num").eq("emp_num", id).eq("org_code", orgCode);
			emp = YgglMainEmp.builder().build().selectOne(queryWrapper);

			HtzzAssoHtgx htgx = HtzzAssoHtgx.builder().build();
			htgx.setHtid(zzda.getId());
			htgx.setTzrid(emp.getEmpNum());
			htgx.setName(emp.getName());
			htgx.setPhone(emp.getPhone());
			htgx.setOrgCode(orgCode);
			htgx.insert();
			htgxs.add(htgx);
		}

		return ResultUtil.datas(zzda, htgxs, "新增证件成功!");
	}

//	/**
//	 * 查询公司所有证件
//	 * 
//	 * @param userBean
//	 * @return
//	 */
//	@GetMapping("/queryzj")
//	@ApiOperation(value = "查询所有合同证件", httpMethod = "GET", notes = "接口发布说明")
//	public Result<List<HtzzAdminZzda>> queryzj(@CurrentUser UserBean userBean) {
//		Integer orgCode = userBean.getOrgCode();
//		if (orgCode != null) {
//			List<HtzzAdminZzda> htzzAdminZzda = HtzzAdminZzda.builder().orgCode(orgCode).isDelete(0)
//					.build().selectAll();
//			return ResultUtil.data(htzzAdminZzda, "查询证件成功!");
//		}
//		return ResultUtil.error("查询失败了!请检查是否登录");
//	}

	/**
	 * 按条件搜索(关键字、到期时间)
	 * 
	 * @param userBean
	 * @return
	 */
	@GetMapping("/queryht")
	@ApiOperation(value = "按条件搜索(关键字、到期时间)", httpMethod = "GET", notes = "接口发布说明")
	public Result<Object> queryht(@CurrentUser UserBean userBean, HtzzQueryDto htzzQueryDto) {
		String e = htzzQueryDto.getEndTime();
		String q = htzzQueryDto.getQuery();
		Page<HtzzAdminZzda> page = new Page<HtzzAdminZzda>(
				htzzQueryDto.getCurrentPage() == null ? 1 : htzzQueryDto.getCurrentPage(),
				htzzQueryDto.getTotalPage() == null ? 10 : htzzQueryDto.getTotalPage());

		QueryWrapper<HtzzAdminZzda> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("lrrid", userBean.getEmpNum()).eq("org_code", userBean.getOrgCode())
				.select("id", "zjmc", "czry", "czrdh", "fzrq", "yxdqr", "txkg_type").eq("is_delete", 0)
				.gt(!StrUtil.hasBlank(e), "yxdqr", !StrUtil.hasBlank(e) ? e : "9999-01-01 00:00:00")
				.and(!StrUtil.hasBlank(q), wq -> wq.like("zjmc", q).or().like("czry", q)).orderByDesc("lrsj_time");

		IPage<HtzzAdminZzda> zPage = HtzzAdminZzda.builder().build().selectPage(page, queryWrapper);
		List<HtzzAdminZzda> zccrkgls = zPage.getRecords();
		zPage.getCurrent();
		zPage.getPages();
		zPage.getTotal();
		zPage.getSize();
		return ResultUtil.data(zPage, zccrkgls, "搜索成功");
	}

	/**
	 * 根据id查合同
	 * 
	 * @param id
	 * @return
	 */
	@PostMapping(value = "/queryHt/{id}")
	@ApiOperation(value = "根据id查合同", httpMethod = "POST", notes = "接口发布说明")
	public Result<Object> queryHt(@CurrentUser UserBean userBean, @PathVariable Integer id) {
		List<Object> list = new ArrayList<Object>();
		list.add(HtzzAdminZzda.builder().build().selectOne(new QueryWrapper<HtzzAdminZzda>()
				.eq("org_code", userBean.getOrgCode()).eq("is_delete", 0).eq("id", id)));
		QueryWrapper<HtzzAssoHtgx> q = new QueryWrapper<HtzzAssoHtgx>();
		q.select("id", "name").eq("htid", id);
		List<HtzzAssoHtgx> htgx = HtzzAssoHtgx.builder().build().selectList(q);
		for (HtzzAssoHtgx gx : htgx) {
			String name = gx.getName();
			list.add(name);
		}
		return ResultUtil.data(list);
	}

	/**
	 * 根据id删除合同
	 * 
	 * @param id
	 * @return
	 */
	@DeleteMapping(value = "/delHt")
	@ApiOperation(value = "根据id删除合同", httpMethod = "DELETE", notes = "接口发布说明")
	public Result<Object> delHt(@CurrentUser UserBean userBean, @RequestParam Integer htid) {
		// 删除提醒关系
		HtzzAssoHtgx.builder().build()
				.delete(new QueryWrapper<HtzzAssoHtgx>().eq("org_code", userBean.getOrgCode()).eq("htid", htid));
		// 设置证照删除状态
		return ResultUtil.data(HtzzAdminZzda.builder().id(htid).isDelete(1).build().updateById());
	}

	/**
	 * 修改提醒状态
	 * 
	 * @param id
	 * @return
	 */
	@PostMapping(value = "/changeTx")
	@ApiOperation(value = "修改提醒状态", httpMethod = "POST", notes = "接口发布说明")
	public Result<Object> changeTx(@CurrentUser UserBean userBean, @RequestParam Integer htid) {

		QueryWrapper<HtzzAdminZzda> queryWrapper = new QueryWrapper<>();
		queryWrapper.select("txkg_type").eq("id", htid);
		HtzzAdminZzda zzda = HtzzAdminZzda.builder().build().selectOne(queryWrapper);

		UpdateWrapper<HtzzAdminZzda> updateWrapper = new UpdateWrapper<>();
		updateWrapper.eq("id", htid);
		HtzzAdminZzda w = HtzzAdminZzda.builder().orgCode(userBean.getOrgCode()).id(htid)
				.txkgType(zzda.getTxkgType() == 0 ? 1 : 0).build();
		htzzAdminZzdaMapper.update(w, updateWrapper);
		return ResultUtil.success("修改成功");

	}

	/**
	 * 查詢全部員工id、姓名
	 * 
	 * @param id
	 * @return
	 */
	@GetMapping(value = "/queryYg")
	@ApiOperation(value = "查詢全部員工id、姓名", httpMethod = "GET", notes = "接口发布说明")
	public Result<Object> queryYg(@CurrentUser UserBean userBean) {
		return ResultUtil.data(YgglMainEmp.builder().build().selectList(
				new QueryWrapper<YgglMainEmp>().select("emp_num", "name").eq("org_code", userBean.getOrgCode())));
	}

	@GetMapping(value = "/test")
	@ApiOperation(value = "test", httpMethod = "GET", notes = "接口发布说明")
	public Result<Void> test(String schedulingPattern) {
		CronUtil.schedule("*/2 * * 24 * *", new Task() {
			@Override
			public void execute() {
				System.out.println("start:" + new Date());
			}
		});

		CronUtil.setMatchSecond(true);
		CronUtil.start();
		return ResultUtil.success("操作成功");
	}

}