package com.yeejoin.amos.boot.module.ugp.biz.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.sun.org.apache.xpath.internal.objects.XObject;
import com.yeejoin.amos.boot.biz.common.bo.CompanyBo;
import com.yeejoin.amos.boot.biz.common.bo.DepartmentBo;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.bo.RoleBo;
import com.yeejoin.amos.boot.biz.common.constants.CommonConstant;
import com.yeejoin.amos.boot.biz.common.utils.RedisKey;

import com.baomidou.mybatisplus.core.metadata.IPage;

import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.common.api.dto.OrgUsrDto;
import com.yeejoin.amos.boot.module.common.api.entity.OrgUsr;
import com.yeejoin.amos.boot.module.common.biz.service.impl.OrgUsrServiceImpl;
import com.yeejoin.amos.boot.module.ugp.api.Enum.CompanyTypeEnum;
import com.yeejoin.amos.boot.module.ugp.api.constants.XJConstant;
import com.yeejoin.amos.boot.module.ugp.api.entity.Company;
import com.yeejoin.amos.boot.module.ugp.api.mapper.CompanyMapper;
import com.yeejoin.amos.boot.module.ugp.biz.service.impl.OrgServiceImpl;

import com.yeejoin.amos.component.feign.config.TokenOperation;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.component.robot.AmosRequestContext;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.*;
import com.yeejoin.amos.feign.privilege.util.DesUtil;


import com.yeejoin.amos.feign.systemctl.Systemctl;
import com.yeejoin.amos.feign.systemctl.model.RegionModel;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.RestController;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import java.util.*;

import com.yeejoin.amos.boot.module.ugp.biz.service.impl.CompanyServiceImpl;
import org.springframework.web.multipart.MultipartFile;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.utils.Bean;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
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 org.springframework.beans.factory.annotation.Autowired;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.module.ugp.api.dto.CompanyDto;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.foundation.enumeration.UserType;

/**
 * 企业信息表
 *
 * @author system_generator
 * @date 2022-09-22
 */
@RestController
@Api(tags = "企业信息表Api")
@RequestMapping(value = "/company")
public class CompanyController extends BaseController {

    @Autowired
    CompanyServiceImpl companyServiceImpl;
	@Autowired(required = false)
	CompanyMapper companyMapper;
	@Autowired
	OrgUsrServiceImpl iOrgUsrService;
	@Autowired
	OrgServiceImpl orgServiceImpl;

	@Value("${amos.secret.key}")
	String secretKey;

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

//	@Value("${ugp.user.name}")
//	private String ugpUserName;
//
//	@Value("${ugp.user.pwd}")
//	private String ugpUserPwd;

	/**
	 * saveUserRedis设置过期时间
	 */
	@Value("${redis.cache.failure.time}")
	private Long redisRegionTimeSecond;

	@Autowired
	RedisUtils redisUtils;


    /**
     * 新增企业信息表
     *
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
	@PostMapping(value = "/save")
	@ApiOperation(httpMethod = "POST", value = "新增企业信息表", notes = "新增企业信息表")
	public ResponseModel<CompanyDto> save(@RequestBody CompanyDto model) {
	    model = companyServiceImpl.createWithModel(model);
	    return ResponseHelper.buildResponse(model);
	}

	/**
     * 根据sequenceNbr更新
     *
     * @param sequenceNbr 主键
     * @return
     */
	@TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
	@PutMapping(value = "/{sequenceNbr}")
	@ApiOperation(httpMethod = "PUT", value = "根据sequenceNbr更新企业信息表", notes = "根据sequenceNbr更新企业信息表")
	public ResponseModel<CompanyDto> updateBySequenceNbrCompany(@RequestBody CompanyDto model,@PathVariable(value = "sequenceNbr") Long sequenceNbr) {
	    model.setSequenceNbr(sequenceNbr);
	    return ResponseHelper.buildResponse(companyServiceImpl.updateWithModel(model));
	}

	/**
     * 根据sequenceNbr删除
     *
     * @param sequenceNbr 主键
     * @return
     */
    @TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
    @DeleteMapping(value = "/{sequenceNbr}")
    @ApiOperation(httpMethod = "DELETE", value = "根据sequenceNbr删除企业信息表", notes = "根据sequenceNbr删除企业信息表")
    public ResponseModel<Boolean> deleteBySequenceNbr(HttpServletRequest request, @PathVariable(value = "sequenceNbr") Long sequenceNbr){
        return ResponseHelper.buildResponse(companyServiceImpl.removeById(sequenceNbr));
    }

    /**
     * 根据sequenceNbr查询
     *
	 * @param sequenceNbr  主键
     * @return
     */
	@TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
	@GetMapping(value = "/{sequenceNbr}")
	@ApiOperation(httpMethod = "GET",value = "根据sequenceNbr查询单个企业信息表",  notes = "根据sequenceNbr查询单个企业信息表")
	public ResponseModel<CompanyDto> selectOne(@PathVariable Long sequenceNbr) {
	    return ResponseHelper.buildResponse(companyServiceImpl.queryBySeq(sequenceNbr));
	}

	/**
     * 列表分页查询
     *
     * @param current 当前页
     * @param current 每页大小
     * @return
     */
	@TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
	@PostMapping(value = "/page")
	@ApiOperation(httpMethod = "GET",value = "企业信息表分页查询",  notes = "企业信息表分页查询")
	public ResponseModel<IPage<CompanyDto>> queryForPage(@RequestParam(value = "current") int current,@RequestParam
                    (value = "size") int size,@RequestBody Company company) {
		return ResponseHelper.buildResponse(companyServiceImpl.queryCompanyPage(current,size,company));
	}

	/**
	 * 列表全部数据查询
     *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth=false)
	@ApiOperation(httpMethod = "GET",value = "企业信息表列表全部数据查询",   notes = "企业信息表列表全部数据查询")
	@GetMapping(value = "/list")
	public ResponseModel<List<CompanyDto>> selectForList() {
	    return ResponseHelper.buildResponse(companyServiceImpl.queryForCompanyList());
	}
	/**
	 * 修改企业信息
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
	@ApiOperation(httpMethod = "Post",value = "修改企业信息",   notes = "修改企业信息")
	@PostMapping(value = "/modifyCompanyInfo")
	public ResponseModel<Boolean> modifyCompanyInfo(@RequestBody CompanyDto company) {

		return ResponseHelper.buildResponse(companyServiceImpl.updateById(company.getCompany()));

	}
	/**
	 * 查看企业信息详情
	 *
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
	@ApiOperation(httpMethod = "GET",value = "查看企业信息详情",   notes = "查看企业信息详情")
	@GetMapping(value = "/getCompanyInfo")
	public ResponseModel<Company> getCompanyInfo(Company companyList)  {

		return ResponseHelper.buildResponse(companyMapper.selectById(companyList));

	}
	/**
	 * 企业审核
	 * 根据sequenceNbr更新，审核通过后的企业调用平台接口创建单位及管理员，并存业务的cb_org_usr表
	 * @param sequenceNbr 主键
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
	@PostMapping(value = "check")
	@ApiOperation(httpMethod = "POST", value = "根据sequenceNbr更新，并创建单位及管理员", notes = "根据sequenceNbr更新，并创建单位及管理员")
	public ResponseModel<Boolean> companyCheck(@RequestBody CompanyDto model,Long sequenceNbr,String bizOrgType) throws Exception{
		return ResponseHelper.buildResponse(companyServiceImpl.companyCheck(model,sequenceNbr,bizOrgType));
	}

	@TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
	@PostMapping(value = "test")
	@ApiOperation(httpMethod = "Post", value = "（测试）存储动态表单", notes = "（测试）存储动态表单")
	public ResponseModel<OrgUsrDto> getInfo(@RequestBody JSONObject jsonObject, String bizOrgType,String sequenceNbr){
		return ResponseHelper.buildResponse(orgServiceImpl.dataHandling(jsonObject,bizOrgType,sequenceNbr));
	}

	/***
	 * 部門新增或更新
	 * @param jsonObject 表单数据
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
	@PostMapping(value = "department")
	@ApiOperation(httpMethod = "POST", value = "部門新增或更新", notes = "部門新增或更新")
	public ResponseModel<Boolean> getInfo(@RequestBody JSONObject jsonObject, @RequestParam(required = false) String sequenceNbr) {
		return ResponseHelper.buildResponse(companyServiceImpl.saveDepartment(jsonObject,sequenceNbr));
	}

	/***
	 * 分页获取当前登录人所在单位下的所有部门
	 * @param
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
	@GetMapping(value = "/deptList")
	@ApiOperation(httpMethod = "GET", value = "分页获取当前登录人所在单位下的所有部门", notes = "分页获取当前登录人所在单位下的所有部门")
	public ResponseModel<IPage> getDept(String size, String current) {
		Page<OrgUsr> page = new Page<>();
		page.setSize(Long.parseLong(size));
		page.setCurrent(Long.parseLong(current));
		return ResponseHelper.buildResponse(orgServiceImpl.getCompanyDept(page));
	}

	/***
	 * 获取当前登录人所在单位下的所有部门（全部）
	 * @param
	 * @return
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
	@GetMapping(value = "/dept")
	@ApiOperation(httpMethod = "GET", value = "获取当前登录人所在单位下的所有部门（全部）", notes = "获取当前登录人所在单位下的所有部门（全部）")
	public ResponseModel<List> getDept() {
		Page<OrgUsr> page = new Page<>(0,Long.MAX_VALUE);
		return ResponseHelper.buildResponse(orgServiceImpl.getCompanyDept(page).getRecords());
	}


	/**
	 * 企业注册：获取单位类型
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
	@GetMapping(value = "/getType")
	@ApiOperation(httpMethod = "Get", value = "", notes = "")
	public ResponseModel<List> getType(){
		return ResponseHelper.buildResponse(CompanyTypeEnum.mapList);
	}


	/**
	 * 获取组织机构树
	 *
	 * @return
	 */
	@TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/region/tree")
	@ApiOperation(httpMethod = "GET", value = "获取组织机构树", notes = "获取组织机构树")
	public ResponseModel<Collection<RegionModel>> getRegionTree() {
		RequestContext.setAppKey("AMOS_STUDIO");
		RequestContext.setProduct("AMOS_STUDIO_WEB");
		RequestContext.setToken(requestContext.getToken());
		return  ResponseHelper.buildResponse(Systemctl.regionClient.queryForTree(null).getResult());
	}

	/**
	 * 判断用户是否存在
	 *
	 * @return
	 */
	@TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/hasExistUser/{adminLoginName}")
	@ApiOperation(httpMethod = "GET", value = "判断用户是否存在", notes = "判断用户是否存在")
	public ResponseModel<Boolean> hasExistUser( @PathVariable(value = "adminLoginName") String adminLoginName) {
		Boolean flag = false;
		Company company = companyServiceImpl.getOne(new LambdaQueryWrapper<Company>().eq(Company::getAdminLoginName,adminLoginName));
		if(!ValidationUtil.isEmpty(company)) {
			flag = true;
		}
		return ResponseHelper.buildResponse(flag);
	}

	/**
	 * 管理员身份证图片上传 无token
	 *
	 * @return
	 */
	@TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
	@PostMapping(value = "/uploadFile")
	@ApiOperation(httpMethod = "POST", value = "管理员身份证图片上传 无token", notes = "管理员身份证图片上传 无token")
	public ResponseModel<String> uploadFile(@ApiParam(value = "文件", required = true)@RequestParam MultipartFile adminLicensePic) {
		if (ValidationUtil.isEmpty(adminLicensePic)){
			throw new BadRequest("参数校验失败.");
		}
		RequestContext.setAppKey("AMOS_STUDIO");
		RequestContext.setProduct("AMOS_STUDIO_WEB");
		RequestContext.setToken(requestContext.getToken());
		FeignClientResult<Map<String, String>> date = Systemctl.fileStorageClient.updateCommonFile(adminLicensePic);
		String urlString="";
		if (date != null) {
			Map<String, String> map = date.getResult();
			Iterator<String> it = map.keySet().iterator();
			while (it.hasNext()) {
				urlString=it.next();
			}
		}
		return ResponseHelper.buildResponse(urlString);
	}

	@Autowired
	AmosRequestContext requestContext;

//	public void setRequestContext() {
//		RequestContext.setAppKey("AMOS_STUDIO");
//		RequestContext.setProduct("AMOS_STUDIO_WEB");
//		RequestContext.setToken(requestContext.getToken());
//		// 需要登录后台账号
//		RequestContext.setAppKey("AMOS_STUDIO");
//		RequestContext.setProduct("AMOS_STUDIO_WEB");
//		if(redisUtils.hasKey(RedisKey.CTI_USER_TOKEN)) {
//			// 验证token
//			boolean validToken = TokenOperation.refresh(redisUtils.get(RedisKey.CTI_USER_TOKEN).toString());
//			// 登陆
//			if(!validToken) {
//				this.loginCtiUser();
//			}
//		} else { // 登陆
//			this.loginCtiUser();
//		}
//		String ctiToken = redisUtils.get(RedisKey.CTI_USER_TOKEN).toString();
//		RequestContext.setToken(ctiToken);
//		try {
//			FeignClientResult<AgencyUserModel> agencyUserModel = Privilege.agencyUserClient.queryByUserName(ugpUserName);
//			AgencyUserModel userModel = agencyUserModel.getResult();
//			RequestContext.setExeUserId(userModel.getUserId());
//			saveUserRedis(userModel, ctiToken);
//		} catch (Exception e) {
//			//删除失效token缓存
//			throw new RuntimeException(e.getMessage());
//		}

//	}
//
//	private void loginCtiUser() {
//		String passwd = DesUtil.encode(ugpUserPwd, "qaz");
//		IdPasswordAuthModel loninData = new IdPasswordAuthModel();
//		loninData.setLoginId(ugpUserName);
//		loninData.setPassword(passwd);
//		FeignClientResult loginResult = Privilege.authClient.idpassword(loninData);
//		if(loginResult.getStatus() == 200) {
//			HashMap resultMap = (HashMap) loginResult.getResult();
//			redisUtils.set(RedisKey.CTI_USER_TOKEN,  resultMap.get("token").toString(), redisRegionTimeSecond);
//		}
//	}
//
//	private void saveUserRedis(AgencyUserModel user, String token) {
//		String authToken = RedisKey.buildReginKey(user.getUserId(), token);
//		if (redisUtils.hasKey(authToken)) {
//			return;
//		}
//		CompanyBo company = new CompanyBo();
//		DepartmentBo department = new DepartmentBo();
//		RoleBo role = new RoleBo();
//		CompanyModel companyM = user.getCompanys() != null ? user.getCompanys().get(0) : null ;
//		Bean.copyExistPropertis(companyM, company);
//		Map<Long, List<DepartmentModel>> mapDepartments = user.getCompanyDepartments();
//		DepartmentModel departmentM = companyM != null ? mapDepartments.get(companyM.getSequenceNbr()).get(0) : null ;
//		Bean.copyExistPropertis(departmentM, department);
//		Map<Long, List<RoleModel>> roles = user.getOrgRoles();
//		Long sequenceNbr;
//		if (departmentM == null) {
//			sequenceNbr = null;
//		} else {
//			sequenceNbr = departmentM.getSequenceNbr();
//		}
//		RoleModel roleM = null;
//		if (sequenceNbr == null) {
//			roleM = companyM != null ?roles.get(companyM.getSequenceNbr()).get(0) : null;
//		} else {
//			roleM = roles.get(sequenceNbr).get(0);
//		}
//		Bean.copyExistPropertis(roleM, role);
//		ReginParams reginParams = new ReginParams();
//		reginParams.setCompany(company);
//		reginParams.setRole(role);
//		reginParams.setDepartment(department);
//		reginParams.setUserModel(user);
//		redisUtils.set(authToken, JSONObject.toJSONString(reginParams), redisRegionTimeSecond);
//	}

	/**
	 * 判断手机号是否已经注册
	 *
	 * @return
	 */
	@TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/hasExistPhone/{adminTel}")
	@ApiOperation(httpMethod = "GET", value = "判断手机号是否已经注册", notes = "判断手机号是否已经注册")
	public ResponseModel<Boolean> hasExistPhone( @PathVariable(value = "adminTel") String adminTel) {
		Boolean flag = false;
		Company company = companyServiceImpl.getOne(new LambdaQueryWrapper<Company>().eq(Company::getAdminTel,adminTel));
		if(!ValidationUtil.isEmpty(company)) {
			flag = true;
		}
		return ResponseHelper.buildResponse(flag);
	}

	/**
	 * 判断组织机构是否存在
	 *
	 * @return
	 */
	@TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/hasExistUnit/{creditCode}")
	@ApiOperation(httpMethod = "GET", value = "判断组织机构是否存在", notes = "判断组织机构是否存在")
	public ResponseModel<Boolean> hasExistUnit( @PathVariable(value = "creditCode") String creditCode) {
		Boolean flag = false;
		LambdaQueryWrapper<Company> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(Company::getCreditCode,creditCode);
		Company company = companyServiceImpl.getOne(wrapper);
//		Company company = companyServiceImpl.getOne(new LambdaQueryWrapper<Company>().eq(Company::getCreditCode,creditCode));
		if(!ValidationUtil.isEmpty(company)) {
			flag = true;
		}
		return ResponseHelper.buildResponse(flag);
	}

	/**
	 * 发送手机号验证码
	 *
	 * @return
	 */
	@TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/sendTelCode/{tel}")
	@ApiOperation(httpMethod = "GET", value = "发送手机号验证码", notes = "发送手机号验证码")
	public ResponseModel<Boolean> sendTelCode( @PathVariable(value = "tel") String adminTel) {
		if (ValidationUtil.isEmpty(adminTel)) {
			throw new BadRequest("参数校验失败.");
		}
		Boolean flag = false;
		HashMap<String, String> params = new HashMap<>();
		String code = this.getRandomCode();
		params.put("code",code);
		params.put("mobile",adminTel);
		params.put("smsCode", smsTempCode);
		try {
			Systemctl.smsClient.sendCommonSms(params).getResult();
			flag = true;
		} catch (Exception e) {
			throw new BadRequest("发送短信失败：" + e.getMessage());
		}
		// code 保存到缓存中
		redisUtils.set(XJConstant.UGP_USER_TEL + adminTel, code);
		return ResponseHelper.buildResponse(flag);
	}


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

	}

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

	}


	/**
	 * 验证手机号验证码是否成功
	 *
	 * @return
	 */
	@TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/tset")
	@ApiOperation(httpMethod = "GET", value = "验证手机号验证码是否成功", notes = "验证手机号验证码是否成功")
	public void tset() {
		orgServiceImpl.getReginParams();
	}

}

