package com.aircraft.modules.system.controller;


import com.aircraft.annotation.Log;
import com.aircraft.config.properties.RsaProperties;
import com.aircraft.exception.BadRequestException;
import com.aircraft.modules.system.domain.CnCustomer;
import com.aircraft.modules.system.domain.EmEmployees;
import com.aircraft.modules.system.domain.dto.UserPassVo;
import com.aircraft.modules.system.service.CnCustomerService;
import com.aircraft.utils.PageResult;
import com.aircraft.utils.RsaUtils;
import com.aircraft.utils.SecurityUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author cli
 * @since 2025-07-09
 */
@RestController
@RequestMapping("/cnCustomer")
@RequiredArgsConstructor
@Api(tags = "客户管理")
public class CnCustomerController {

    private static final Logger LOG = LoggerFactory.getLogger(CnCustomerController.class);
    @Autowired
    private CnCustomerService entityService;
    private final PasswordEncoder passwordEncoder;


    @Log("分页查询客户")
    @ApiOperation(value = "分页查询客户", notes = "分页查询客户")
    @RequestMapping(method = RequestMethod.GET)
    @ApiImplicitParams({@ApiImplicitParam(name = "size", value = "分页大小", paramType = "query"),
            @ApiImplicitParam(name = "current", value = "当前页面：从1开始", paramType = "query")})
    public ResponseEntity<PageResult<CnCustomer>> findByPage(final CnCustomer example, final Page page) {
        PageResult<CnCustomer>        records    = entityService.page(example,page);
        return new ResponseEntity<>(records,HttpStatus.OK);
    }

    @Log("查询单个客户")
    @ApiOperation(value = "查询单个客户")
    @RequestMapping(value = "{id}", method = {RequestMethod.GET})
    @ApiImplicitParam(name = "id", value = "客户ID", required = true, paramType = "path")
    public ResponseEntity<Object> one(@PathVariable final Integer id) {
        try {
            CnCustomer entity = entityService.getById(id);
            return new ResponseEntity<>(entity, HttpStatus.OK);
        } catch (Exception e) {
            LOG.error("查询单个客户失败", e);
            throw new RuntimeException("查询单个客户失败", e);
        }
    }

    @Log("添加客户")
    @ApiOperation(value = "添加客户")
    @RequestMapping(method = {RequestMethod.POST})
    public ResponseEntity<Object> add(@Valid @RequestBody final CnCustomer entity) {
        try {
            CnCustomer cnCustomer = entityService.findByUserName(entity.getUsername());
            if (cnCustomer != null) {
                throw new RuntimeException("用户名已存在！");
            }
            entity.setStatus("1");
            entity.setPassword(passwordEncoder.encode("123456"));
            entityService.save(entity);
            return new ResponseEntity<>("成功保存客户", HttpStatus.OK);
        } catch (Exception e) {
            LOG.error("添加客户失败", e);
            throw new RuntimeException("保存客户失败",e);
        }
    }

    @Log("修改客户")
    @ApiOperation(value = "修改客户")
    @RequestMapping(method = {RequestMethod.PUT})
    public ResponseEntity<Object> update(@Valid @RequestBody final CnCustomer entity) {
        try {
            if (null == entity.getId()) {
                throw new RuntimeException("id不能为空");
            }
            entityService.updateById(entity);
            return new ResponseEntity<>("成功修改客户", HttpStatus.OK);
        } catch (Exception e) {
            LOG.error("修改客户失败", e);
            throw new RuntimeException("修改客户失败",e);
        }
    }

    @ApiOperation(value = "全部客户")
    @RequestMapping(value = "all", method = RequestMethod.GET)
    public ResponseEntity<Object> all(CnCustomer example) {
        List<CnCustomer> entitys = entityService.list(example);
        if (null != entitys) {
            return new ResponseEntity<>(entitys, HttpStatus.OK);
        }
        return new ResponseEntity<>(Collections.emptyList(),HttpStatus.OK);
    }

    @ApiOperation("修改密码")
    @PostMapping(value = "/updatePass")
    public ResponseEntity<Object> updateUserPass(@RequestBody UserPassVo passVo) throws Exception {
        CnCustomer customer = entityService.findByUserName(SecurityUtils.getCurrentUsername());
        String oldPass = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey,passVo.getOldPass());
        String newPass = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey,passVo.getNewPass());

        if(!passwordEncoder.matches(oldPass, customer.getPassword())){
            throw new BadRequestException("修改失败，旧密码错误");
        }
        if(passwordEncoder.matches(newPass, customer.getPassword())){
            throw new BadRequestException("新密码不能与旧密码相同");
        }
        entityService.updatePass(customer.getUsername(),passwordEncoder.encode(newPass));
        return new ResponseEntity<>(HttpStatus.OK);
    }

}

