package io.renren.modules.sys.controller;

import io.renren.common.constant.Constant;
import io.renren.common.page.PageData;
import io.renren.common.utils.Result;
import io.renren.common.validator.AssertUtils;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.AddGroup;
import io.renren.common.validator.group.DefaultGroup;
import io.renren.common.validator.group.UpdateGroup;
import io.renren.modules.sys.dao.SysDictDataDao;
import io.renren.modules.sys.dto.AppSysLoanApplyDTO;
import io.renren.modules.sys.dto.AppSysLoanApplyRecordDTO;
import io.renren.modules.sys.dto.AppSysUserDTO;
import io.renren.modules.sys.service.AppSysLoanApplyService;
import io.renren.modules.sys.service.AppSysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.*;


/**
 * APP系统用户贷款申请表
 *
 * @author Mark sunlightcs@gmail.com
 * @since 1.0.0 2022-05-11
 */
@RestController
@RequestMapping("sys/appsysloanapply")
@Api(tags="APP系统用户贷款申请表")
public class AppSysLoanApplyController {
    @Autowired
    private AppSysLoanApplyService appSysLoanApplyService;
    @Autowired
    private AppSysUserService appSysUserService;
    @Autowired
    private SysDictDataDao sysDictDataDao;


    @GetMapping("getLoanList")
    @ApiOperation("查询借款记录(我的)")
    public Result<List<AppSysLoanApplyRecordDTO>> getLoanList(Long appUserId){
        Map<String, Object> params = new HashMap<>();
        params.put("app_user_id", appUserId);
        List<AppSysLoanApplyDTO> list = appSysLoanApplyService.list(params);
        if (!CollectionUtils.isEmpty(list)){
            List<AppSysLoanApplyRecordDTO> recordDTOList = new ArrayList<>();
            for (AppSysLoanApplyDTO appSysLoanApplyDTO:list){
                AppSysLoanApplyRecordDTO recordDTO = new AppSysLoanApplyRecordDTO();
                BeanUtils.copyProperties(appSysLoanApplyDTO,recordDTO);
                AppSysUserDTO appSysUserDTO = appSysUserService.get(appSysLoanApplyDTO.getAppUserId());
                recordDTO.setRealName(appSysUserDTO!=null?appSysUserDTO.getRealName():null);
                //借款期限
                String period = sysDictDataDao.getDictDataByTypeAndDictValue("app_loan_period",appSysLoanApplyDTO.getPeriod());
                recordDTO.setPeriod(period);
                //借款状态
                String status = sysDictDataDao.getDictDataByTypeAndDictValue("app_loan_status",appSysLoanApplyDTO.getStatus());
                recordDTO.setStatus(status);
                recordDTOList.add(recordDTO);
            }
            return new Result<List<AppSysLoanApplyRecordDTO>>().ok(recordDTOList);
        }

        return new Result<List<AppSysLoanApplyRecordDTO>>().ok(null);
    }

    @GetMapping("getLoanStep")
    @ApiOperation("查询贷款申请信息（包括当前完成步骤）")
    public Result<AppSysLoanApplyDTO> getLoanStep(Long appUserId){
        Map<String, Object> params = new HashMap<>();
        params.put("app_user_id", appUserId);
        List<AppSysLoanApplyDTO> list = appSysLoanApplyService.list(params);
        if (!CollectionUtils.isEmpty(list)){
            return new Result<AppSysLoanApplyDTO>().ok(list.get(0));
        }else{
            return new Result<AppSysLoanApplyDTO>().ok(null);
        }
    }



    @PostMapping("save")
    @ApiOperation("保存贷款申请")
    public Result save(@RequestBody AppSysLoanApplyDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
        dto.setApplyDate(new Date());
        dto.setCreateDate(new Date());
        dto.setUpdateDate(new Date());
        appSysLoanApplyService.save(dto);

        return new Result();
    }

    @PostMapping("update")
    @ApiOperation("修改贷款申请")
    public Result update(@RequestBody AppSysLoanApplyDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);
        Integer step = dto.getStep();
        dto.setStep(null);
        dto.setUpdateDate(new Date());
        appSysLoanApplyService.update(dto);
        appSysLoanApplyService.updateLoanStep(dto.getAppUserId(),step);

        return new Result();
    }

    @GetMapping("page")
//    @ApiOperation("分页")
    @ApiImplicitParams({
        @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query",required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType="String") ,
        @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType="String")
    })
    public Result<PageData<AppSysLoanApplyDTO>> page(@ApiIgnore @RequestParam Map<String, Object> params){
        PageData<AppSysLoanApplyDTO> page = appSysLoanApplyService.page(params);

        return new Result<PageData<AppSysLoanApplyDTO>>().ok(page);
    }

    @GetMapping("{id}")
//    @ApiOperation("信息")
    public Result<AppSysLoanApplyDTO> get(@PathVariable("id") Long id){
        AppSysLoanApplyDTO data = appSysLoanApplyService.get(id);

        return new Result<AppSysLoanApplyDTO>().ok(data);
    }

    @DeleteMapping
//    @ApiOperation("删除")
    public Result delete(@RequestBody Long[] ids){
        //效验数据
        AssertUtils.isArrayEmpty(ids, "id");

        appSysLoanApplyService.delete(ids);

        return new Result();
    }

}