package com.gxwebsoft.love.controller;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.core.web.BatchParam;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.system.entity.FileRecord;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.common.system.service.UserService;
import com.gxwebsoft.love.entity.Certificate;
import com.gxwebsoft.love.param.CertificateParam;
import com.gxwebsoft.love.service.CertificateService;
import com.gxwebsoft.love.vo.idcheck.BackRecognitionResult;
import com.gxwebsoft.love.vo.idcheck.FrontRecognitionResult;
import com.gxwebsoft.love.vo.idcheck.Response;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 证件管理记录表控制器
 *
 * @author 科技小王子
 * @since 2023-06-24 11:18:52
 */
@Api(tags = "证件管理记录表管理")
@RestController
@RequestMapping("/api/love/certificate")
public class CertificateController extends BaseController {
    @Resource
    private CertificateService certificateService;


    @Resource
    private UserService userService;

    @PreAuthorize("hasAuthority('love:certificate:list')")
    @OperationLog
    @ApiOperation("分页查询证件管理记录表")
    @GetMapping("/page")
    public ApiResult<PageResult<Certificate>> page(CertificateParam param) {
        // 使用关联查询
        return success(certificateService.pageRel(param));
    }

    @PreAuthorize("hasAuthority('love:certificate:list')")
    @OperationLog
    @ApiOperation("查询全部证件管理记录表")
    @GetMapping()
    public ApiResult<List<Certificate>> list(CertificateParam param) {
        // 使用关联查询
        return success(certificateService.listRel(param));
    }

    @PreAuthorize("hasAuthority('love:certificate:list')")
    @OperationLog
    @ApiOperation("根据id查询证件管理记录表")
    @GetMapping("/{id}")
    public ApiResult<Certificate> get(@PathVariable("id") Integer id) {
        // 使用关联查询
        return success(certificateService.getByIdRel(id));
    }

    @PreAuthorize("hasAuthority('love:certificate:save')")
    @OperationLog
    @ApiOperation("添加证件管理记录表")
    @PostMapping()
    public ApiResult<?> save(@RequestBody Certificate certificate) {

        // 记录当前登录用户id
        User loginUser = getLoginUser();

        certificate.setUserId(loginUser.getUserId());
        certificate.setStatus(10);
        // 身份证认证
        if("idCard".equals(certificate.getCertificateType())){
            // 验证表单
            if (!StringUtils.hasText(certificate.getRealName())) {
                return fail("请填写真实姓名", certificate);
            }
            if (!StringUtils.hasText(certificate.getCertificateCode())) {
                return fail("请填写身份证号码", certificate);
            }

            List<FileRecord> files = JSON.parseArray(certificate.getFiles(), FileRecord.class);
            List<String> collect = files.stream().map(FileRecord::getUrl).collect(Collectors.toList());
            if (files == null || files.size() < 2) {
                return fail("请上传身份证照片", certificate);
            }

            // 验证正面
            Response<FrontRecognitionResult> front = certificateService.idcardfrontrecongnition(collect.get(0));
            if (front.getError_code() != 0) {
                return fail(front.getReason());
            }


            // 验证反面
            Response<BackRecognitionResult> back = certificateService.idcardbackrecongnition(collect.get(1));
            if (back.getError_code() != 0) {
                return fail(back.getReason());
            }

            certificate.setStatus(30);

            // 信息是否一致
            if (!certificate.getCertificateCode().equals(front.getResult().getIdcardno())) {
                return fail("认证失败", certificate);
            }
            if (!certificate.getRealName().equals(front.getResult().getName())) {
                return fail("认证失败", certificate);
            }
            User user = new User();
            user.setUserId(loginUser.getUserId());
            user.setCertification(1);
            userService.updateById(user);

        }
        // 房屋认证
        if ("house".equals(certificate.getCertificateType())) {
          if (!StringUtils.hasText(certificate.getCityByHouse())) {
            return fail("请填写房子所在城市", certificate);
          }
          List<FileRecord> files = JSON.parseArray(certificate.getFiles(), FileRecord.class);
          if (files == null || files.size() < 1) {
            return fail("请上传证件照片", certificate);
          }
        }

        // 学历认证
        if ("education".equals(certificate.getCertificateType())) {
          if (!StringUtils.hasText(certificate.getEducation())) {
            return fail("请选择学历", certificate);
          }
          if (!StringUtils.hasText(certificate.getAuthType())) {
            return fail("请选择认证方式", certificate);
          }
          if (!StringUtils.hasText(certificate.getCollege())) {
            return fail("请填写毕业院校", certificate);
          }

          List<FileRecord> files = JSON.parseArray(certificate.getFiles(), FileRecord.class);
          if (files == null || files.size() < 1) {
            return fail("请上传证件照片", certificate);
          }
        }

        // 车辆认证
        if ("car".equals(certificate.getCertificateType())) {
          if (!StringUtils.hasText(certificate.getCarBrand())) {
            return fail("请填写车辆品牌", certificate);
          }

          List<FileRecord> files = JSON.parseArray(certificate.getFiles(), FileRecord.class);
          if (files == null || files.size() < 1) {
            return fail("请上传证件照片", certificate);
          }
        }

        // 其他身份人工审核
        final Certificate one = certificateService.getOne(new LambdaQueryWrapper<Certificate>().eq(Certificate::getUserId, loginUser.getUserId()).eq(Certificate::getCertificateType, certificate.getCertificateType()));
        if (one != null) {
            certificate.setCertificateId(one.getCertificateId());
            certificateService.updateById(certificate);
        }else {
            certificateService.save(certificate);
        }

        return success("提交成功", certificate);

    }

    @PreAuthorize("hasAuthority('love:certificate:update')")
    @OperationLog
    @ApiOperation("修改证件管理记录表")
    @PutMapping()
    public ApiResult<?> update(@RequestBody Certificate certificate) {
        if (certificateService.updateById(certificate)) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('love:certificate:remove')")
    @OperationLog
    @ApiOperation("删除证件管理记录表")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        if (certificateService.removeById(id)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @PreAuthorize("hasAuthority('love:certificate:save')")
    @OperationLog
    @ApiOperation("批量添加证件管理记录表")
    @PostMapping("/batch")
    public ApiResult<?> saveBatch(@RequestBody List<Certificate> list) {
        if (certificateService.saveBatch(list)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('love:certificate:update')")
    @OperationLog
    @ApiOperation("批量修改证件管理记录表")
    @PutMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody BatchParam<Certificate> batchParam) {
        if (batchParam.update(certificateService, "certificate_id")) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('love:certificate:remove')")
    @OperationLog
    @ApiOperation("批量删除证件管理记录表")
    @DeleteMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
        if (certificateService.removeByIds(ids)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

}
