package org.jeecg.modules.system.app.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.utils.UuidUtils;
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.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DictAnnotationUtil;
import org.jeecg.modules.system.app.entity.AppInsure;
import org.jeecg.modules.system.app.entity.InsurePrice;
import org.jeecg.modules.system.app.service.IAppInsureService;
import org.jeecg.modules.system.app.service.IInsurePriceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

/**
 * @Description: 保险表
 * @Author: jeecg-boot
 * @Date:   2025-07-03
 * @Version: V1.0
 */
@Tag(name="保险表")
@RestController
@RequestMapping("/app/appInsure")
@Slf4j
public class AppInsureController extends JeecgController<AppInsure, IAppInsureService> {
	@Autowired
	private IAppInsureService appInsureService;

	@Autowired
	IInsurePriceService iInsurePriceService;
	
	/**
	 * 分页列表查询
	 *
	 * @param appInsure
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "保险表-分页列表查询")
	@Operation(summary="保险表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<AppInsure>> queryPageList(AppInsure appInsure,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
        QueryWrapper<AppInsure> queryWrapper = QueryGenerator.initQueryWrapper(appInsure, req.getParameterMap());
		Page<AppInsure> page = new Page<AppInsure>(pageNo, pageSize);
		IPage<AppInsure> pageList = appInsureService.page(page, queryWrapper);
		if (pageList!=null&&pageList.getRecords()!=null){
			for (AppInsure record : pageList.getRecords()) {
				List<InsurePrice> list = iInsurePriceService.list(new QueryWrapper<InsurePrice>().lambda().eq(InsurePrice::getInsureId, record.getId()).eq(InsurePrice::getDelFlag,0).orderByAsc(InsurePrice::getInsureDay) );
				record.setPriceDataList(list);
			}
		}
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param appInsure
	 * @return
	 */
	@AutoLog(value = "保险表-添加")
	@Operation(summary="保险表-添加")
	@PostMapping(value = "/add")
	@Transactional
	public Result<String> add(@RequestBody AppInsure appInsure) {
		if (appInsure.getPriceDataList()==null||appInsure.getPriceDataList().size()!=5){
			return Result.error("保险期限价格错误");
		}
		LoginUser principal = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		appInsure.setOrgCode(principal.getOrgCode());
		appInsure.setTenantId(principal.getOrgId());
		appInsureService.save(appInsure);
		for (InsurePrice insurePrice : appInsure.getPriceDataList()) {
			insurePrice.setInsureId(appInsure.getId());
			insurePrice.setId(UuidUtils.getUUID());
		}
		iInsurePriceService.saveBatch(appInsure.getPriceDataList());
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param appInsure
	 * @return
	 */
	@AutoLog(value = "保险表-编辑")
	@Operation(summary="保险表-编辑")
	@Transactional
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody AppInsure appInsure) {
		if (appInsure.getPriceDataList()==null||appInsure.getPriceDataList().size()!=5){
			return Result.error("保险期限价格错误");
		}
		appInsureService.updateById(appInsure);
		iInsurePriceService.updateBatchById(appInsure.getPriceDataList());
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "保险表-通过id删除")
	@Operation(summary="保险表-通过id删除")
	@DeleteMapping(value = "/delete")
	@Transactional
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		appInsureService.removeById(id);
		iInsurePriceService.remove(new QueryWrapper<InsurePrice>().lambda().eq(InsurePrice::getInsureId,id));
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "保险表-批量删除")
	@Operation(summary="保险表-批量删除")
	@RequiresPermissions("org.jeecg.modules.app:nm_insure:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.appInsureService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "保险表-通过id查询")
	@Operation(summary="保险表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<AppInsure> queryById(@RequestParam(name="id",required=true) String id) {
		AppInsure appInsure = appInsureService.getById(id);
		if(appInsure==null) {
			return Result.error("未找到对应数据");
		}
		List<InsurePrice> list = iInsurePriceService.list(new QueryWrapper<InsurePrice>().lambda().eq(InsurePrice::getInsureId, appInsure.getId()).eq(InsurePrice::getDelFlag,0) .orderByAsc(InsurePrice::getInsureDay) );
		appInsure.setPriceDataList(list);
		return Result.OK(appInsure);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param appInsure
    */
    @RequiresPermissions("org.jeecg.modules.app:nm_insure:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, AppInsure appInsure) {
        return super.exportXls(request, appInsure, AppInsure.class, "保险表");
    }

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

	 /**
	  * 分页列表查询
	  *
	  */
	 //@AutoLog(value = "保险表-分页列表查询")
	 @Operation(summary="保险表-根据保险公司id分页列表查询")
	 @GetMapping(value = "/findByList")
	 public Result<List<AppInsure>> findByList(@RequestParam(name="insuranceName",required=true) String insuranceName) {
		 LambdaQueryWrapper<AppInsure> query = new LambdaQueryWrapper<>();
		 List<AppInsure> list = appInsureService.list( query
				 .eq(AppInsure::getStatus, 0).eq(AppInsure::getInsuranceName,insuranceName));
		 DictAnnotationUtil.translateDictList(list);
		 return Result.OK(list);
	 }

	@Operation(summary="保险表-列表查询")
	@GetMapping(value = "/findList")
	public Result<List<AppInsure>> findList() {
		LambdaQueryWrapper<AppInsure> query = new LambdaQueryWrapper<>();
		List<AppInsure> list = appInsureService.list( query
				.eq(AppInsure::getStatus, 0));
		DictAnnotationUtil.translateDictList(list);
		return Result.OK(list);
	}
}
