package com.yeejoin.amos.boot.module.tzs.flc.biz.controller;

import com.baomidou.mybatisplus.extension.api.R;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.biz.common.entity.DataDictionary;
import com.yeejoin.amos.boot.biz.common.utils.RedisKey;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.tzs.api.service.IRegUnitInfoService;
import com.yeejoin.amos.boot.module.tzs.flc.api.dto.RegUnitInfoDto;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.model.CompanyModel;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import javax.ws.rs.DELETE;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

/**
 * 单位注册信息表
 *
 * @author system_generator
 * @date 2022-08-09
 */
@RestController
@Api(tags = "单位注册信息表Api")
@RequestMapping(value = "/reg-unit-info")
public class RegUnitInfoController extends BaseController {

    @Autowired
    IRegUnitInfoService iRegUnitInfoService;

    @Autowired
    RedisUtils redisUtils;

    @Value("${flc.sms.tempCode}")
    private String smsTempCode;

    @Value("${flc.sms.timeout:600}")
    private int timeout;


    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @PostMapping(value = "/save")
    @ApiOperation(httpMethod = "POST", value = "单位注册", notes = "单位注册")
    public ResponseModel<RegUnitInfoDto> save(@RequestBody RegUnitInfoDto model) {
        model = iRegUnitInfoService.registerUnit(model);
        return ResponseHelper.buildResponse(model);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @GetMapping(value = "/{unitCode}/check")
    @ApiOperation(httpMethod = "GET", value = "单位注册校验", notes = "单位注册校验")
    public ResponseModel<RegUnitInfoDto> unitCheck(@PathVariable String unitCode,
                                                   @RequestParam String unitType) {
        if(ValidationUtil.isEmpty(unitCode)){
            throw new BadRequest("单位编码不能为空");
        }
        RegUnitInfoDto regUnitInfoDto = iRegUnitInfoService.unitCheck(unitCode, unitType);
        return ResponseHelper.buildResponse(regUnitInfoDto);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @GetMapping(value = "/unit-type/list")
    @ApiOperation(httpMethod = "GET", value = "单位类型列表", notes = "单位类型列表")
    public ResponseModel<List<DataDictionary>> unitTypeList() {
        List<DataDictionary> result = iRegUnitInfoService.getUnitTypeList();
        return ResponseHelper.buildResponse(result);
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @GetMapping(value = "/management-unit/tree")
    @ApiOperation(httpMethod = "GET", value = "管辖机构树", notes = "管辖机构树")
    public ResponseModel<Collection> managementUnitTree() {
        Collection result = iRegUnitInfoService.getManagementUnitTree();
        return ResponseHelper.buildResponse(result);
    }


    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/{tel}/sendTelCode")
    @ApiOperation(httpMethod = "GET", value = "发送手机号验证码", notes = "发送手机号验证码")
    public ResponseModel<Boolean> sendTelCode(@PathVariable(value = "tel") String tel) {
        if (ValidationUtil.isEmpty(tel)) {
            throw new BadRequest("手机号不能为空");
        }
        try {
            Privilege.authClient.mobileVerify(tel);
        } catch (Exception e) {
            throw new RuntimeException("该手机号已注册!");
        }
        Boolean flag;
        HashMap<String, String> params = new HashMap<>();
        String code = this.getRandomCode();
        params.put("code", code);
        params.put("mobile", tel);
        params.put("smsCode", smsTempCode);
        try {
            Systemctl.smsClient.sendCommonSms(params).getResult();
            flag = true;
        } catch (Exception e) {
            throw new BadRequest("发送短信失败：" + e.getMessage());
        }
        // code 保存到缓存中
        redisUtils.set(RedisKey.FLC_USER_TEL + tel, code, timeout);
        return ResponseHelper.buildResponse(flag);
    }

    private String getRandomCode() {
        StringBuilder code = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            //每次随机出一个数字（0-9）
            int r = random.nextInt(10);
            //把每次随机出的数字拼在一起
            code.append(r);
        }
        return code.toString();

    }

    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/{tel}/{code}/verifyTelCode")
    @ApiOperation(httpMethod = "GET", value = "验证手机号验证码是否成功", notes = "验证手机号验证码是否成功")
    public ResponseModel<Boolean> verifyTelCode(@PathVariable(value = "tel") String tel, @PathVariable(value = "code") String code) {
        Boolean flag = false;
        if (ValidationUtil.isEmpty(tel) || ValidationUtil.isEmpty(code)) {
            throw new BadRequest("参数校验失败.");
        }
        if (redisUtils.hasKey(RedisKey.FLC_USER_TEL + tel)) {
            String redisCode = redisUtils.get(RedisKey.FLC_USER_TEL + tel).toString();
            if (code.equals(redisCode)) {
                flag = true;
                redisUtils.del(RedisKey.FLC_USER_TEL + tel);
            }
        }
        return ResponseHelper.buildResponse(flag);
    }

    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
    @GetMapping(value = "/{userName}/hasExistUser")
    @ApiOperation(httpMethod = "GET", value = "判断用户是否存在", notes = "判断用户是否存在")
    public ResponseModel<Boolean> hasExistUser(@PathVariable(value = "userName") String userName) {
        boolean flag = false;
        AgencyUserModel user = Privilege.agencyUserClient.queryByUserName(userName).getResult();
            if (user != null) {
            flag = true;
        }
        return ResponseHelper.buildResponse(flag);
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
    @DeleteMapping(value = "/{unitCode}/logOut")
    @ApiOperation(httpMethod = "DELETE", value = "企业注销", notes = "企业注销")
    public ResponseModel unitLogOut(@PathVariable String unitCode){
        return ResponseHelper.buildResponse(iRegUnitInfoService.unitLogOut(unitCode));
    }


}
