package cn.iocoder.yudao.module.app.customer;

import cn.iocoder.yudao.framework.common.exception.ServiceException;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.custom.service.CustomerMainService;
import cn.iocoder.yudao.module.custom.vo.CustomerMainSaveReqVO;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.UserDTO;
import cn.iocoder.yudao.module.system.service.auth.AdminAuthService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
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.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import static cn.iocoder.yudao.common.BaseConstants.SIGN_CREATE;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.error;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

/**
 * 客户管理
 *
 * @author : http://www.chiner.pro
 * @date : 2024-7-31
 */
@RestController
@RequestMapping("/base/custom-app")
@Tag(name = "客户管理-小程序端接口")
@Validated
public class CustomerAPI {
    @Resource
    private CustomerMainService customerMainService;
    @Resource
    private AdminAuthService loginService;
    @Resource
    private AdminUserApi adminUserApi;

    /**
     * 新增客户
     *
     * @param saveReqVO 保存客户信息扩展实体
     * @return cn.iocoder.yudao.framework.common.pojo.CommonResult<java.lang.Boolean>
     * @author PQZ
     * @date 15:42 2024/8/1
     **/
    @PostMapping("/register")
    @Operation(summary = "客户自行注册")
    public CommonResult<?> createCustomerMain(@Valid @RequestBody CustomerMainSaveReqVO saveReqVO, HttpServletRequest request) {
        //      获取当前登录用户
        LoginUser loginUser = SecurityFrameworkUtils.getLoginUser();
        saveReqVO.setUserId(loginUser.getId());
        saveReqVO.setPhoneNumber(adminUserApi.getUser(loginUser.getId()).getMobile());
        //客户类型，统一为私人客户
        saveReqVO.setTypeCode("01");
        //客户来源，统一为04-维修
        saveReqVO.setDataFrom("04");
        //注册方式，统一为自主创建
        saveReqVO.setInviterType("01");
        try {
            UserDTO userDTO = customerMainService.saveCustomer(saveReqVO,SIGN_CREATE);
            //注册并登录
            return success(userDTO);
        }catch (ServiceException e){
            return error(e);
        }
    }
}
