package jnpf.personnels.controller.app.formdata;

import jnpf.base.ActionResult;
import jnpf.model.personnels.dto.staff.field.FormTypeDto;
import jnpf.model.personnels.dto.staff.field.SubFormFieldDto;
import jnpf.model.personnels.dto.staff.registerform.BankConvertDto;
import jnpf.model.personnels.dto.staff.registerform.CheckRegisterFormFillDto;
import jnpf.model.personnels.dto.staff.registerform.IdCardConverterDto;
import jnpf.model.personnels.req.registerform.OcrReq;
import jnpf.model.personnels.req.registerform.SaveAppRegisterFormDataReq;
import jnpf.model.personnels.req.registerform.SaveFormDataReq;
import jnpf.model.personnels.req.registerform.SaveMyFormDataReq;
import jnpf.personnels.service.FtbPersonnelsStaffRegistrationFormDataService;
import jnpf.personnels.utils.PersonnelCardOcr;
import jnpf.util.NoDataSourceBind;
import jnpf.util.TenantUtil;
import jnpf.util.UserProvider;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * app员工档案信息数据表模块
 *
 * @author xxxxx
 */
@RestController
@Slf4j
@RequestMapping("/app/personnels-staff-registration-form-data")
public class FtbPersonnelsStaffRegistrationFormDataAppController {

    @Autowired
    private FtbPersonnelsStaffRegistrationFormDataService registrationFormDataService;

    @Resource
    private TenantUtil tenantUtil;

    @Autowired
    private PersonnelCardOcr personnelIdCardOcr;

    @Resource
    RedissonClient redissonClient;

    /**
     * 根据租户查询入职登记表表单
     *
     * @param tenantId 租户ID
     * @return
     */
    @GetMapping("/query-registration-form/{tenantId}")
    @NoDataSourceBind
    public ActionResult<List<FormTypeDto>> queryRegistrationForm(@PathVariable("tenantId") String tenantId) {
        tenantUtil.switchTenant(tenantId);
        List<FormTypeDto> list = registrationFormDataService.queryRegistrationForm();
        return ActionResult.success(list);
    }

    /**
     * 根据邀请码查询租户ID
     *
     * @param code 邀请码
     * @return
     */
    @GetMapping("/query-registration-form/code-to-tenantId/{code}")
    @NoDataSourceBind
    public ActionResult<String> codeToTenantId(@PathVariable("code") String code) {

        String tenantId = registrationFormDataService.queryTenantIdForCode(code);
        if (StringUtils.isEmpty(tenantId)) {
            throw new RuntimeException("邀请码不正确");
        }
        return ActionResult.success("查询成功", tenantId);
    }

    /**
     * 保存登记表
     *
     * @param req 参数
     * @return {@link ActionResult}<{@link String}>
     */
    @PostMapping("/save-register/{tenantId}")
    @NoDataSourceBind
    public ActionResult<String> saveRegister(@PathVariable("tenantId") String tenantId,
                                             @Validated @RequestBody SaveAppRegisterFormDataReq req) {
        List<SubFormFieldDto> fieldValueList = req.getFieldValueList();
        SubFormFieldDto phone = fieldValueList.stream().filter(v -> v.getId().equals("phone")).findFirst().orElse(null);
        if (phone == null) {
            return ActionResult.fail("手机号不能为空");
        }
        String lockKey = "HANDLE_JOIN_JOB:" + phone.getUserValue();
        RLock lock = redissonClient.getLock(lockKey);
        try {
            boolean b = lock.tryLock(3000, TimeUnit.MILLISECONDS);
            if (!b) {return ActionResult.fail("当前人员正在填写登记表,请勿重复提交!");}
            tenantUtil.switchTenant(tenantId);
            registrationFormDataService.saveRegistrationForm(tenantId, fieldValueList,1, req.getRegisterImg(),req.getModuleId());
        }catch (Exception e){
            e.printStackTrace();
            return ActionResult.fail(e.getMessage());
        }finally {
            lock.unlock();
        }

        return ActionResult.success();
    }

    /**
     * 检测入职登记表表单是否已经填
     *
     * @param tenantId 入职登记表ID
     * @return
     */
    @GetMapping("/check-registration-form-fill/{tenantId}")
    @NoDataSourceBind
    public ActionResult<CheckRegisterFormFillDto> checkRegistrationFormFill(@PathVariable("tenantId") String tenantId,
                                                                            @RequestParam("phone") String phone) {
        tenantUtil.switchTenant(tenantId);
        CheckRegisterFormFillDto checkRegisterFormFill = registrationFormDataService.checkRegistrationFormFill(phone);
        return ActionResult.success(checkRegisterFormFill);
    }


    /**
     * 查询我的档案表单
     *
     * @return
     */
    @GetMapping("/query-my-archival-form")
    public ActionResult<List<FormTypeDto>> queryMyArchivalForm() {
        String loginUserId = UserProvider.getLoginUserId();
        List<FormTypeDto> list = registrationFormDataService.queryArchivalForm(loginUserId);

        return ActionResult.success(list);
    }


    /**
     * 保存我的档案表单数据
     *
     * @param req 参数
     * @return {@link ActionResult}<{@link String}>
     */
    @PostMapping("/save-my-archives")
    public ActionResult<String> saveMyArchives(@Validated @RequestBody SaveMyFormDataReq req) {
        String loginUserId = UserProvider.getLoginUserId();
        SaveFormDataReq saveFormDataReq = new SaveFormDataReq();
        saveFormDataReq.setUserId(loginUserId);
        saveFormDataReq.setFieldValueList(req.getFieldValueList());
        registrationFormDataService.saveArchives(saveFormDataReq);
        return ActionResult.success();
    }

    /**
     * 根据userId查询档案表单
     *
     * @param userId 用户ID
     * @return
     */
    @GetMapping("/query-archival-form/roster/{userId}")
    public ActionResult<List<FormTypeDto>> queryArchivalFormForRoster(@PathVariable("userId") String userId) {
        List<FormTypeDto> list = registrationFormDataService.queryArchivalForm(userId);

        return ActionResult.success(list);
    }

    /**
     * 保存用户的档案信息
     *
     * @param userId 用户ID
     * @return
     */
    @PostMapping("/save-archives/{userId}")
    public ActionResult<String> saveMyArchives(@PathVariable("userId") String userId, @Validated @RequestBody SaveMyFormDataReq req) {

        SaveFormDataReq saveFormDataReq = new SaveFormDataReq();
        saveFormDataReq.setUserId(userId);
        saveFormDataReq.setFieldValueList(req.getFieldValueList());
        registrationFormDataService.saveArchives(saveFormDataReq);
        return ActionResult.success();
    }


    /**
     * 身份证ocr
     *
     * @param req
     * @return
     */
    @PostMapping("/id-card-ocr")
    @NoDataSourceBind
    public ActionResult<IdCardConverterDto> idCardOcr(@RequestBody OcrReq req) {
        IdCardConverterDto dto = personnelIdCardOcr.idCardOcr(req.getImgUrl());
        return ActionResult.success(dto);
    }

    /**
     * 银行卡ocr
     *
     * @param req
     * @return
     */
    @PostMapping("/bank-ocr")
    @NoDataSourceBind
    public ActionResult<BankConvertDto> healthOcr(@RequestBody OcrReq req) {
        BankConvertDto dto = personnelIdCardOcr.bankOcr(req.getImgUrl());
        return ActionResult.success(dto);
    }
}
