package org.springblade.modules.app.web;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springblade.common.auth.UserContext;
import org.springblade.common.auth.permission.DisableLoginVerify;
import com.wn.common.controller.BaseController;
import com.wn.common.datamodel.ResultDTO;
import org.springblade.core.redis.cache.BladeRedis;
import org.springblade.modules.app.common.dto.UserDTO;
import org.springblade.modules.app.common.enums.UserStateEnum;
import org.springblade.modules.app.common.query.SlaughterHouseQuery;
import org.springblade.modules.app.common.query.UserQuery;
import org.springblade.modules.app.common.query.WaybillClientQuery;
import org.springblade.modules.app.common.vo.*;
import org.springblade.modules.app.entity.UserDO;
import org.springblade.modules.app.manager.UserManager;
import org.springblade.modules.app.manager.WaybillManager;
import org.springblade.modules.app.service.IAppUserService;
import org.springblade.modules.app.service.IVerifyStationService;
import org.springblade.modules.app.utils.UserUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

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

/**
 * <p>
 * 用户信息表 前端控制器
 * </p>
 *
 * @author fuxinsheng
 * @since 2021-11-05
 */
@RestController
@RequestMapping("app/user")
@Api(value = "用户管理", tags = "用户管理")
public class AppUserController extends BaseController {

    @Autowired
    private UserManager userManager;

    @Autowired
    private WaybillManager waybillManager;

    @Autowired
    private IAppUserService userService;

    @Autowired
    private IVerifyStationService verifyStationService;

    @Autowired
    private UserUtils userUtils;

    @Autowired
    private HttpServletResponse httpServletResponse;

    @Autowired
    private BladeRedis bladeRedis;

    //@ApiOperation(value = "获取用户详细信息（已完成）")
    @GetMapping("/info")
    @DisableLoginVerify
    public ResponseEntity<ResultDTO<UserDTO>> getUserInfo(String token) {
        return success(userManager.getUserInfo(token));
    }

    //@ApiOperation(value = "发送短信验证码")
    @PostMapping("/sms")
    @DisableLoginVerify
    public ResponseEntity<ResultDTO<Boolean>> sendSmsCode(@RequestBody UserLoginVO userLoginVO) {
        return success(userManager.sendSmsCode(userLoginVO));
    }

    @PostMapping("/switchAutoSubmit")
    @DisableLoginVerify
    public ResponseEntity<ResultDTO<Boolean>> switchAutoSubmit(@RequestBody UserQuery userQuery) {
        UserDO user = userService.getOne(Wrappers.<UserDO>lambdaQuery().eq(UserDO::getId,userQuery.getToken()));
        if(user.getType().equals(2) || user.getType().equals(4)){
            user.setAutoSubmit(userQuery.getAutoSubmit());
            return success(userService.saveOrUpdate(user));
        }
        return failure("502","无权限");
    }





    //@ApiOperation(value = "用户登录")
    @PostMapping("/login")
    @DisableLoginVerify
    public ResponseEntity<ResultDTO<UserDTO>> login(@RequestBody UserLoginVO userLoginVO) {
//        userService.updateSupplier();
        String ipAddress = getIpAddr();
        return success(userManager.login(userLoginVO, httpServletResponse, ipAddress, getSession()));
    }

    //@ApiOperation(value = "忘记修改密码")
    @PutMapping("/password")
    @DisableLoginVerify
    public ResponseEntity<ResultDTO<Boolean>> updatePassword(@RequestBody UpdatePasswordVO updatePasswordVO) {
        return success(userManager.updatePassword(updatePasswordVO));
    }

    //@ApiOperation(value = "获取缓存密码")
    @GetMapping("/account")
    @DisableLoginVerify
    public ResponseEntity<ResultDTO<AccountInfoVo>> getAccount() {
        return success(userManager.getAccount(getSession()));
    }

    //@ApiOperation(value = "重新绑定屠宰场")
    @PostMapping("/slaughter")
    @DisableLoginVerify
    public ResponseEntity<ResultDTO<Boolean>> resubmitSlaughter(@RequestBody UserDTO userDTO) {
        return success(userManager.resubmitSlaughter(userDTO));
    }

    //@ApiOperation(value = "用户登出")
    @PostMapping("/logout")
    public ResponseEntity<ResultDTO<Boolean>> logout() {
        userManager.logout(getSession());
        return success(true);
    }

    //@ApiOperation(value = "通过手机号获取注册失败的用户信息")
    @GetMapping("/no/pass")
    @DisableLoginVerify
    public ResponseEntity<ResultDTO<UserDTO>> getNoPassUser(UserLoginVO userLoginVO) {
        return success(userManager.getNoPassUser(userLoginVO));
    }

    //@ApiOperation(value = "用户注册")
    @PostMapping("/register")
    @DisableLoginVerify
    public ResponseEntity<ResultDTO<String>> register(@RequestBody UserDTO userDTO) {
        return success(userManager.register(userDTO, UserStateEnum.UNCHECK.getCode()));
    }

    @GetMapping("/updatecheck")
    @DisableLoginVerify
    public ResponseEntity<ResultDTO<String>> updatecheck(@RequestBody UserDTO userDTO) {
        verifyStationService.updateVerifyStation();
        return success();
    }


    //@ApiOperation(value = "校验用户验证码", notes = "入参：用户手机号")
    @GetMapping("/sms/check")
    @DisableLoginVerify
    public ResponseEntity<ResultDTO<UserDTO>> checkSmsCode(UserLoginVO query) {
        return success(userManager.checkSmsCode(query));
    }

    //@ApiOperation(value = "根据手机号查询经纪人信息", notes = "入参：用户手机号")
    @GetMapping("/agent/phone")
    public ResponseEntity<ResultDTO<UserDTO>> getAgent(UserQuery query) {
        return success(userManager.getAgent(query));
    }


    //@ApiOperation(value = "根据手机号查询司机信息", notes = "入参：用户手机号")
    @GetMapping("/driver/phone")
    public ResponseEntity<ResultDTO<UserDTO>> getDriver(UserQuery query) {
        return success(userManager.getDriver(query));
    }

    //@ApiOperation(value = "根据名称查询屠宰场")
    @GetMapping("/slaughter/name")
    @DisableLoginVerify
    public ResponseEntity<ResultDTO<UserDTO>> getSlaughterByName(UserQuery userQuery) {
        return success(userManager.getSlaughterByName(userQuery));
    }

    //@ApiOperation(value = "获取待宰户列表")
    @GetMapping("/slaughter/house/page")
    public ResponseEntity<ResultDTO<Page<SlaughterHouseVO>>> getSlaughterHousePage(SlaughterHouseQuery query) {
        return success(userManager.getSlaughterHousePage(query));
    }

    //@ApiOperation(value = "获取待宰户详情")
    @GetMapping("/slaughter/house/{token}/{slaughterHouseId}")
    public ResponseEntity<ResultDTO<UserDTO>> getSlaughterHouse(@PathVariable Long slaughterHouseId,@PathVariable String token) {
        return success(userManager.getSlaughterHouse(slaughterHouseId,token));
    }

    //@ApiOperation(value = "新增代宰户")
    @PostMapping("/slaughter/house")
    public ResponseEntity<ResultDTO<String>> creatSlaughterHouse(@RequestBody UserDTO userDTO) {
        return success(userManager.creatSlaughterHouse(userDTO));
    }

    //@ApiOperation(value = "审批待宰户")
    @PutMapping("/slaughter/house/approval")
    public ResponseEntity<ResultDTO<Boolean>> approvalSlaughterHouse(@RequestBody ApprovalVO approvalVO) {
        return success(userManager.approvalSlaughterHouse(approvalVO));
    }

    //@ApiOperation(value = "重新提交注册")
    @PutMapping("/resubmit")
    @DisableLoginVerify
    public ResponseEntity<ResultDTO<String>> resubmitUser(@RequestBody UserDTO userDTO) {
        return success(userManager.resubmitUser(userDTO));
    }

    //@ApiOperation(value = "获取用户待确认任务列表")
    @GetMapping("/task")
    public ResponseEntity<ResultDTO<List<IndexNotifyVO>>> taskList(String token) {
//        bladeRedis.set(token,"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJuYmYiOjE2NTg4MDI3NzgsInBob25lIjoiMTM1ODgyMjgyNDkiLCJleHAiOjE2NTkyMzQ3NzgsInVzZXJOYW1lIjoi5p2t5bee6IGU5ZCI6KW_5YW05pyJ6ZmQ5YWs5Y-4LjsiLCJpYXQiOjE2NTg4MDI3NzgsInVzZXJJZCI6MTUzNTE1MzQzNjI2Mzc0NzU4NSwidXNlckR0byI6IntcImFkZHJlc3NcIjpcIuaxn-a7qOi3rzg4OOWPt1wiLFwiYXJlYUlkXCI6XCIzMzAxMTBcIixcImFyZWFOYW1lXCI6XCLkvZnmna3ljLpcIixcImF1dG9TdWJtaXRcIjowLFwiYnJlZWRDb2RlXCI6XCJcIixcImJ1c2luZXNzSW5kdXN0cnlDYXRlZ3JvcnlcIjpcIuS8geS4mlwiLFwiYnVzaW5lc3NMZWdhbFBlcnNvblwiOlwi55aP5oiQXCIsXCJidXNpbmVzc0xpbmtNYW5cIjpcIueWj-aIkFwiLFwiYnVz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0cnlcIjpcIlwiLFwicG9sbHV0YW50RGlzY2hhcmdlUGVybWl0TGljZW5zZVVybFwiOlwiXCIsXCJwcm92SWRcIjpcIjMzXCIsXCJwcm92TmFtZVwiOlwi5rWZ5rGfXCIsXCJzbGF1Z2h0ZXJIb3VzZVBhcmVudElkXCI6XCIwXCIsXCJzbGF1Z2h0ZXJIb3VzZVBhcmVudE5hbWVcIjpcIlwiLFwic2xhdWdodGVySG91c2VUeXBlXCI6MCxcInN0YXRlXCI6MSxcInRyYW5zcG9ydFBlcm1pdENvZGVcIjpcIlwiLFwidHJhbnNwb3J0UGVybWl0VXJsXCI6XCJcIixcInR5cGVcIjoxLFwidXNlck5hbWVcIjpcIuadreW3nuiBlOWQiOilv-WFtOaciemZkOWFrOWPuC47XCIsXCJ2ZWhpY2xlTGljZW5zZUNvZGVcIjpcIlwiLFwidmVoaWNsZUxpY2Vuc2VVcmxcIjpcIlwiLFwidmVyc2lvblwiOjEsXCJ6bXRJZFwiOjEsXCJ6bXROYW1lXCI6XCIxMzMwNTgxMTUyM1wiLFwiem10VHlwZVwiOjYsXCJ6bXRVc2VySWRcIjoxMjAyMyxcInptdFVzZXJOYW1lXCI6XCLmnLHmna1cIn0ifQ.0mZght62Dr5ygIURBBs_2RBagY7-LUfUvL7P27duqxI");
        return success(userManager.taskList(token));
    }

    //@ApiOperation(value = "查询签订合同的养殖场列表")
    @GetMapping("/contract/farm/list/{token}/{buyerUserId}")
    public ResponseEntity<ResultDTO<List<FarmSimpleInfoVO>>> listContractFarm(@PathVariable Long buyerUserId,@PathVariable String token) {

        return success(userManager.listSimpleFarm(buyerUserId,token));
    }

    //@ApiOperation(value = "通过养殖场id查询养殖场附件信息")
    @GetMapping("/contract/farm/picture/{token}/{userId}")
    public ResponseEntity<ResultDTO<UserDTO>> getFarmPicture(@PathVariable Long userId,@PathVariable String token) {
        return success(userManager.getFarmPicture(userId,token));
    }


    //@ApiOperation(value = "通过屠宰户id查询挂靠的屠宰场信息")
    @GetMapping("/slaughter")
    public ResponseEntity<ResultDTO<UserDTO>> getSlaughterByHouse(String token) {
        return success(userManager.getSlaughterByHouse(token));
    }

    //@ApiOperation(value = "营业执照修改")
    @PutMapping("/businessLicense")
    public ResponseEntity<ResultDTO<Boolean>> businessLicenseUpdate(@RequestBody UserDTO userDTO, @ApiIgnore HttpServletRequest request) {
        Long id = userUtils.getUser(userDTO.getToken()).getId();
        Boolean result = userManager.businessLicenseUpdate(id, userDTO);
        return getResultDTOResponseEntity(request, id, result);
    }

    //@ApiOperation(value = "生猪定点屠宰许可证修改")
    @PutMapping("/slaughteringLicense")
    public ResponseEntity<ResultDTO<Boolean>> slaughteringLicenseUpdate(@RequestBody UserDTO userDTO, @ApiIgnore HttpServletRequest request) {
        Long id = userUtils.getUser(userDTO.getToken()).getId();
        Boolean result = userManager.slaughteringLicenseUpdate(id, userDTO);
        return getResultDTOResponseEntity(request, id, result);
    }

    @GetMapping("/bill/list")
    public ResponseEntity<ResultDTO<List<WaybillListVO>>> getTransportList(WaybillClientQuery waybillClientQuery) {
        return success(waybillManager.getbillList(waybillClientQuery));
    }

    private ResponseEntity<ResultDTO<Boolean>> getResultDTOResponseEntity(@ApiIgnore HttpServletRequest request, Long id, Boolean result) {
        UserDTO userDTO1 = userManager.getUserByID(id);
        HttpSession session = request.getSession();
        UserContext userContext = UserContext.custom().userId(userDTO1.getId())
                .loginName(userDTO1.getPhone()).userName(userDTO1.getUserName())
                .jsonObject(JSON.toJSONString(userDTO1)).build();
        session.setAttribute(session.getId(), userContext);
        return success(result);
    }

    //@ApiOperation(value = "动物防疫条件合格证修改")
    @PutMapping("/antiepidemicCertificate")
    public ResponseEntity<ResultDTO<Boolean>> antiepidemicCertificateUpdate(@RequestBody UserDTO userDTO, @ApiIgnore HttpServletRequest request) {
        Long id = userUtils.getUser(userDTO.getToken()).getId();
        Boolean result = userManager.antiepidemicCertificateUpdate(id, userDTO);
        return getResultDTOResponseEntity(request, id, result);
    }

    //@ApiOperation(value = "排污许可证修改")
    @PutMapping("/pollutantsDischargeLicense")
    public ResponseEntity<ResultDTO<Boolean>> pollutantsDischargeLicenseUpdate(@RequestBody UserDTO userDTO, @ApiIgnore HttpServletRequest request) {
        Long id = userUtils.getUser(userDTO.getToken()).getId();
        Boolean result = userManager.pollutantsDischargeLicenseUpdate(id, userDTO);
        return getResultDTOResponseEntity(request, id, result);
    }

    //@ApiOperation(value = "三年无疫情证明修改")
    @PutMapping("/noEpidemicProof")
    public ResponseEntity<ResultDTO<Boolean>> noEpidemicProofUpdate(@RequestBody UserDTO userDTO, @ApiIgnore HttpServletRequest request) {
        Long id = userUtils.getUser(userDTO.getToken()).getId();
        Boolean result = userManager.noEpidemicProofUpdate(id, userDTO);
        return getResultDTOResponseEntity(request, id, result);
    }

    //@ApiOperation(value = "身份证修改")
    @PutMapping("/identityCard")
    public ResponseEntity<ResultDTO<Boolean>> identityCardUpdate(@RequestBody UserDTO userDTO, @ApiIgnore HttpServletRequest request) {
        Long id = userUtils.getUser(userDTO.getToken()).getId();
        Boolean result = userManager.identityCardUpdate(id, userDTO);
        return getResultDTOResponseEntity(request, id, result);
    }

    //@ApiOperation(value = "驾驶证修改")
    @PutMapping("/driverLicence")
    public ResponseEntity<ResultDTO<Boolean>> driverLicenceUpdate(@RequestBody UserDTO userDTO, @ApiIgnore HttpServletRequest request) {
        Long id = userUtils.getUser(userDTO.getToken()).getId();
        Boolean result = userManager.driverLicenceUpdate(id, userDTO);
        return getResultDTOResponseEntity(request, id, result);
    }

    //@ApiOperation(value = "行驶证修改")
    @PutMapping("/drivingLicence")
    public ResponseEntity<ResultDTO<Boolean>> drivingLicenceUpdate(@RequestBody UserDTO userDTO, @ApiIgnore HttpServletRequest request) {
        Long id = userUtils.getUser(userDTO.getToken()).getId();
        Boolean result = userManager.drivingLicenceUpdate(id, userDTO);
        return getResultDTOResponseEntity(request, id, result);
    }

    //@ApiOperation(value = "道路运输许可证修改")
    @PutMapping("/roadTransportLicence")
    public ResponseEntity<ResultDTO<Boolean>> roadTransportLicenceUpdate(@RequestBody UserDTO userDTO, @ApiIgnore HttpServletRequest request) {
        Long id = userUtils.getUser(userDTO.getToken()).getId();
        Boolean result = userManager.roadTransportLicenceUpdate(id, userDTO);
        return getResultDTOResponseEntity(request, id, result);
    }

    //@ApiOperation(value = "手机号修改")
    @PutMapping("/phoneNumber")
    public ResponseEntity<ResultDTO<Boolean>> phoneNumberUpdate(@RequestBody UserDTO userDTO, @ApiIgnore HttpServletRequest request) {
        Long id = userUtils.getUser(userDTO.getToken()).getId();
        Boolean result = userManager.phoneNumberUpdate(id, userDTO);
        return getResultDTOResponseEntity(request, id, result);
    }

    //@ApiOperation(value = "通过养殖场名称查询养殖场信息")
    @GetMapping("/farmInfo")
    public ResponseEntity<ResultDTO<UserDTO>> getFarmInfo(UserQuery userQuery) {
        return success(userManager.getFarmInfo(userQuery));
    }

    //@ApiOperation(value = "用户注销")
    @DeleteMapping("/cancel/{userId}")
    public ResponseEntity<ResultDTO<Boolean>> userCancel(@PathVariable Long userId) {
        return success(userManager.userCancel(userId));
    }

    //@ApiOperation(value = "密码校验")
    @GetMapping("/password/check")
    public ResponseEntity<ResultDTO<Boolean>> checkPassword(String password,String token) {
        Long id = userUtils.getUser(token).getId();
        return success(userManager.checkPassword(id, password));
    }
}

