package digital.laboratory.platform.entrustment.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import digital.laboratory.platform.common.core.util.R;
import digital.laboratory.platform.common.log.annotation.SysLog;
import digital.laboratory.platform.common.mybatis.security.service.DLPUser;
import digital.laboratory.platform.entrustment.entity.Deliverer;
import digital.laboratory.platform.entrustment.service.DelivererService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.List;


/**
 * 送检员
 *
 * @author Zhang Xiaolong created at  2022-08-16
 * @describe 送检员 前端控制器
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/papp/entrustment/deliverer" )
@Api(value = "deliverer", tags = "008-送检员管理")
public class DelivererController {

    private final  DelivererService delivererService;

	/**
	 * 通过id查询送检员
	 * @param id id
	 * @return R
	 */
	@ApiOperation(value = "通过id查询", notes = "通过id查询")
	@GetMapping("/{id}" )
//	@PreAuthorize("@pms.hasPermission('entrustment_deliverer_get')" )
	public R getById(@PathVariable("id" ) String id, HttpServletRequest theHttpServletRequest) {
		Principal principal = theHttpServletRequest.getUserPrincipal();
		DLPUser dlpUser = (DLPUser) ((OAuth2Authentication) principal).getUserAuthentication().getPrincipal();

		Deliverer deliverer = delivererService.getById(id);
		if (deliverer != null) {
			if (StrUtil.equalsIgnoreCase(dlpUser.getId(), deliverer.getOwnerUserId())) {
				return R.ok(deliverer);
			}
			else {
				return R.failed(String.format("你没有权限访问id为 %s 的送检员的数据", id));
			}
		}
		else {
			return R.failed(String.format("没有找到id为 %s 的送检员", id));
		}
	}

	/**
	 * 列表查询
	 * @param name 查询条件
	 * @return
	 */
	@ApiOperation(value = "列表查询", notes = "列表查询\n" +
			"参数:\n" +
			"<pre>\n" +
			"name 送检员名字, 可以模糊查询, 支持 like %name% " +
			"</pre>\n" +
			"")
	@GetMapping("/list" )
//	@PreAuthorize("@pms.hasPermission('entrustment_deliverer_get')" )
	public R getDelivererList(@RequestParam(value = "name", required = false)String name, HttpServletRequest theHttpServletRequest) {
		Principal principal = theHttpServletRequest.getUserPrincipal();
		DLPUser dlpUser = (DLPUser) ((OAuth2Authentication) principal).getUserAuthentication().getPrincipal();
		//deliverer.setOwnerUserId(dlpUser.getId());

		List<Deliverer> list = delivererService.list(Wrappers.<Deliverer>query()
				.eq("owner_user_id", dlpUser.getId())       // 只查询当前用户拥有的送检员
				.like(StrUtil.isNotBlank(name), "name", name)
				.orderByDesc("name")
		);
		return R.ok(list);
	}


	/**
     * 分页查询
     * @param page 分页对象
     * @param deliverer 送检员
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page" )
//    @PreAuthorize("@pms.hasPermission('entrustment_deliverer_get')" )
    public R getDelivererPage(Page page, Deliverer deliverer, HttpServletRequest theHttpServletRequest) {
	    Principal principal = theHttpServletRequest.getUserPrincipal();
	    DLPUser dlpUser = (DLPUser) ((OAuth2Authentication) principal).getUserAuthentication().getPrincipal();
	    deliverer.setOwnerUserId(dlpUser.getId());

	    return R.ok(delivererService.page(page, Wrappers.<Deliverer>query()
			    .eq("owner_user_id", dlpUser.getId())       // 只查询当前用户拥有的送检员
			    .like(StrUtil.isNotBlank(deliverer.getName()), "name", deliverer.getName())
			    .orderByDesc("name")
	    ));
    }


    /**
     * 新增送检员
     * @param deliverer 送检员
     * @return R
     */
    @ApiOperation(value = "新增送检员", notes = "新增送检员")
    @SysLog("新增送检员" )
    @PostMapping
//    @PreAuthorize("@pms.hasPermission('entrustment_deliverer_add')" )
    public R postAddObject(@RequestBody Deliverer deliverer, HttpServletRequest theHttpServletRequest) {
	    Principal principal = theHttpServletRequest.getUserPrincipal();
	    DLPUser dlpUser = (DLPUser) ((OAuth2Authentication) principal).getUserAuthentication().getPrincipal();
	    deliverer.setOwnerUserId(dlpUser.getId());
		deliverer.setId(IdWorker.get32UUID().toUpperCase());

		if (delivererService.save(deliverer)) {
			return R.ok(deliverer, "新增送检员成功");
		}
		else {
			return R.failed(deliverer, "新增送检员失败");
		}

    }

    /**
     * 修改送检员
     * @param deliverer 送检员
     * @return R
     */
    @ApiOperation(value = "修改送检员", notes = "修改送检员")
    @SysLog("修改送检员" )
    @PutMapping
//    @PreAuthorize("@pms.hasPermission('entrustment_deliverer_edit')" )
    public R putUpdateById(@RequestBody Deliverer deliverer, HttpServletRequest theHttpServletRequest) {
	    Principal principal = theHttpServletRequest.getUserPrincipal();
	    DLPUser dlpUser = (DLPUser) ((OAuth2Authentication) principal).getUserAuthentication().getPrincipal();

	    Deliverer oldDeliverer = delivererService.getById(deliverer.getId());
	    if (oldDeliverer != null) {
		    if (StrUtil.equalsIgnoreCase(dlpUser.getId(), oldDeliverer.getOwnerUserId())) {
			    deliverer.setOwnerUserId(dlpUser.getId());
			    return R.ok(delivererService.updateById(deliverer));
		    }
		    else {
			    return R.failed(String.format("你没有权限修改id为 %s 的送检员的数据", deliverer.getId()));
		    }
	    }
	    else {
		    return R.failed(String.format("没有找到id为 %s 的送检员", deliverer.getId()));
	    }
    }

    /**
     * 通过id删除送检员
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除送检员", notes = "通过id删除送检员")
    @SysLog("通过id删除送检员" )
    @DeleteMapping("/{id}" )
//    @PreAuthorize("@pms.hasPermission('entrustment_deliverer_del')" )
    public R deleteById(@PathVariable String id, HttpServletRequest theHttpServletRequest) {
	    Principal principal = theHttpServletRequest.getUserPrincipal();
	    DLPUser dlpUser = (DLPUser) ((OAuth2Authentication) principal).getUserAuthentication().getPrincipal();

	    Deliverer oldDeliverer = delivererService.getById(id);
	    if (oldDeliverer != null) {
		    if (StrUtil.equalsIgnoreCase(dlpUser.getId(), oldDeliverer.getOwnerUserId())) {
			    if (delivererService.removeById(id)) {
				    return R.ok(oldDeliverer, "送检员删除成功");
			    }
			    else {
				    return R.failed(oldDeliverer, "送检员删除失败");
			    }
		    }
		    else {
			    return R.failed(String.format("你没有权限删除id为 %s 的送检员", id));
		    }
	    }
	    else {
		    return R.failed(String.format("没有找到id为 %s 的送检员", id));
	    }
    }

}
