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

import com.alibaba.fastjson.JSON;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
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.ymt.flc.api.dto.RegUnitInfoDto;
import com.yeejoin.amos.boot.module.ymt.flc.api.service.IRegUnitInfoService;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
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.*;
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 javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 单位注册信息表
 *
 * @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) {
    	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 = "/creatQrCode")
    @ApiOperation(httpMethod = "GET", value = "单位历史数据根据统一信用代码生成二维码", notes = "单位历史数据根据统一信用代码生成二维码")
    public ResponseModel<Object> creatQrCode() {
        return ResponseHelper.buildResponse(iRegUnitInfoService.creatQrCode());
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @PostMapping(value = "/submit")
    @ApiOperation(httpMethod = "POST", value = "", notes = "")
    public ResponseModel<Object> submit(@RequestParam(value = "pageId") long pageId,
                                                   @RequestParam(value = "taskId",required = false) String taskId,
                                                   @RequestParam(value = "planInstanceId",required = false) String planInstanceId,
                                                   @RequestParam(value = "topic",required = false) String topic,
                                                   @RequestParam(value = "tableName",required = false) String tableName,
                                                   @RequestBody Map<String, Object> kv
                                                   ) throws Exception {
        return ResponseHelper.buildResponse(iRegUnitInfoService.submit(pageId, taskId, planInstanceId, topic, tableName, kv));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @RequestMapping(value = "/adminInfo", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "查询企业管理员信息", notes = "查询企业管理员信息")
    public ResponseModel<RegUnitInfoDto> adminInfo() {
        ReginParams reginParams = JSON.parseObject(redisUtils.get(RedisKey.buildReginKey(RequestContext.getExeUserId(), RequestContext.getToken())).toString(), ReginParams.class);
        String unitCode = null;
        if (ObjectUtils.isEmpty(reginParams)) {
            return null;
        } else {
            unitCode = reginParams.getUserModel().getCompanys().get(0).getCompanyCode();
        }
        return ResponseHelper.buildResponse(iRegUnitInfoService.adminInfo(unitCode));
    }

    @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("单位编码不能为空");
        }    
        try {
           RegUnitInfoDto regUnitInfoDto = iRegUnitInfoService.unitCheck(unitCode, unitType,companyName);
           return ResponseHelper.buildResponse(regUnitInfoDto);
        }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 = "/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)
    @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,
                                                        @RequestParam(required = false) String cityCode) {
        Collection result = iRegUnitInfoService.getManagementUnitTree(orgCode, cityCode);
        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));
    }


}
