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


import com.alibaba.fastjson.JSON;
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.constants.CommonConstant;
import com.yeejoin.amos.boot.biz.common.utils.RedisKey;
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.enums.OrgPersonEnum;
import com.yeejoin.amos.boot.module.common.api.service.IOrgUsrService;
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.Enum.OrgEnum;
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.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.privilege.model.RoleModel;
import com.yeejoin.amos.feign.privilege.util.DesUtil;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import com.yeejoin.amos.feign.systemctl.model.RegionModel;
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.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;

	@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)
	@GetMapping(value = "/page")
	@ApiOperation(httpMethod = "GET",value = "企业信息表分页查询",  notes = "企业信息表分页查询")
	public ResponseModel<Page<CompanyDto>> queryForPage(@RequestParam(value = "current") int current,@RequestParam
                    (value = "size") int size,CompanyDto companyDto) {

		return ResponseHelper.buildResponse(companyServiceImpl.queryCompanyPage(current,size,companyDto));
	}

	/**
	 * 列表全部数据查询
     *
	 * @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));
	}
	/**
	 * 企业注册：获取单位类型
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
	@GetMapping(value = "/getType")
	@ApiOperation(httpMethod = "Get", value = "", notes = "")
	public ResponseModel<List> getType(){
		return ResponseHelper.buildResponse(CompanyTypeEnum.mapList);
	}

//	/**
//	 * 企业注册：3、账号信息提交
//	 */
//	@TycloudOperation(ApiLevel = UserType.AGENCY,needAuth = false)
//	@PostMapping(value = "/saveInfo")
//	@ApiOperation(httpMethod = "POST", value = "", notes = "")
//	public ResponseModel<String> saveInfo(Object object){
//		return ResponseHelper.buildResponse(companyServiceImpl.saveInfo(object));
//	}

	/**
	 * 获取组织机构树
	 *
	 * @return
	 */
	@TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
	@GetMapping(value = "/region/tree")
	@ApiOperation(httpMethod = "GET", value = "获取组织机构树", notes = "获取组织机构树")
	public ResponseModel<Collection<RegionModel>> getRegionTree() {
		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);
	}

	/**
	 * 判断手机号是否已经注册
	 *
	 * @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 = "/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);
	}







}

