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

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.typroject.tyboot.core.foundation.context.RequestContext;
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 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.biz.service.impl.StartPlatformTokenService;
import com.yeejoin.amos.boot.module.tzs.flc.api.dto.RegUnitInfoDto;
import com.yeejoin.amos.boot.module.tzs.flc.api.service.IRegUnitInfoService;
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;

/**
 * 单位注册信息表
 *
 * @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;
    
    @Autowired
    StartPlatformTokenService startPlatformTokenService;


    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @PostMapping(value = "/save")
    @ApiOperation(httpMethod = "POST", value = "单位注册", notes = "单位注册")
    public ResponseModel<RegUnitInfoDto> save(@RequestBody RegUnitInfoDto model) {
    	try {
    	   model = iRegUnitInfoService.registerUnit(model);
    	   return ResponseHelper.buildResponse(model);
		} catch (Exception e) {
			ResponseModel<RegUnitInfoDto> response = new ResponseModel<>();
			HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
			response.setResult(null);
			response.setDevMessage(e.getMessage());
			response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
			response.setTraceId(RequestContext.getTraceId());
			response.setPath(request.getServletPath());
			return response;
		}
       
    }

    @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,
                                                   @RequestParam String companyName) {
        if (ValidationUtil.isEmpty(unitCode)) {
            throw new BadRequest("单位编码不能为空");
        }
        if (!ValidationUtil.isEmpty(companyName)) {
        	  startPlatformTokenService.getToken();
        	  FeignClientResult<CompanyModel> result =Privilege.companyClient.queryByCompanyName(companyName);
        	  if(result.getResult()!=null) 
        	  {
        		  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(@RequestParam(required = false)String orgCode) {
        Collection result = iRegUnitInfoService.getManagementUnitTree(orgCode);
        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) throws Exception {
        if (ValidationUtil.isEmpty(tel)) {
            throw new BadRequest("手机号不能为空");
        }
        Boolean isReg = (Boolean) Privilege.authClient.mobileVerify(tel).getResult();
        if (isReg) {
            throw new RuntimeException("该手机号已注册!");
        }
        Boolean isExist = iRegUnitInfoService.checkRepeatPhone(tel);
        if (isExist) {
            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) {
        // 1.先看平台是否已经存在相同用户名用户
        AgencyUserModel user = Privilege.agencyUserClient.queryByUserName(userName).getResult();
        if (user != null) {
            return ResponseHelper.buildResponse(false);
        }
        // 2.再校验本地是否，有其他企业注册过
        return ResponseHelper.buildResponse(iRegUnitInfoService.checkRepeatAccount(userName));
    }


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


}
