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

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.hygf.api.dto.MobileLoginParamDto;
import com.yeejoin.amos.boot.module.hygf.api.dto.PeasantHouseholdDto;
import com.yeejoin.amos.boot.module.hygf.api.dto.PeasantHouseholdPageDto;
import com.yeejoin.amos.boot.module.hygf.api.dto.PeasantHouseholdWxDto;
import com.yeejoin.amos.boot.module.hygf.api.entity.PeasantHousehold;
import com.yeejoin.amos.boot.module.hygf.api.service.IWxService;
import com.yeejoin.amos.boot.module.hygf.api.util.BeanDtoUtils;
import com.yeejoin.amos.boot.module.hygf.biz.service.impl.HouseholdContractServiceImpl;
import com.yeejoin.amos.boot.module.hygf.biz.service.impl.PeasantHouseholdServiceImpl;
import com.yeejoin.amos.boot.module.hygf.biz.service.impl.SurveyInformationServiceImpl;
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.AgencyUserModel;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import com.yeejoin.amos.feign.systemctl.model.RegionModel;
import com.yeejoin.amos.feign.systemctl.model.SmsRecordModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
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.context.RequestContext;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
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.HttpServletResponse;
import java.util.*;

/**
 * 农户信息
 *
 * @author system_generator
 * @date 2023-07-07
 */
@RestController
@Api(tags = "农户信息Api for mobile端")
@RequestMapping(value = "/peasant-household/mobile")
@Slf4j
public class PeasantHouseholdWxController extends BaseController {

    private static final String regionRedis = "app_region_redis";
    @Autowired
    RedisUtils redisUtil;
    @Autowired
    SurveyInformationServiceImpl surveyInformationServiceImpl;
    @Autowired
    PeasantHouseholdServiceImpl peasantHouseholdServiceImpl;
    @Autowired
    HouseholdContractServiceImpl householdContractServiceImpl;
    @Autowired
    private IWxService wxService;
    @Value("${dealer.userId}")
    private String defaultUserId;
    @Value("${hygfProgram.loginPage:view/mine/minepage/LoginPhone}")
    private String miniprogramLoginPage;
    @Autowired
    private AmosRequestContext requestContext;

    /*@TycloudOperation (ApiLevel = UserType.AGENCY, needAuth = false)
    @RequestMapping (value = "/authenticate", method = RequestMethod.POST)
    @ApiOperation (httpMethod = "POST", value = "微信农户认证", notes = "微信农户认证")
    public ResponseModel<Boolean> authenticate(@ApiParam(name = "农户信息id") @RequestParam Long sequenceNbr) {
        return ResponseHelper.buildResponse(peasantHouseholdServiceImpl.doAuthenticate(sequenceNbr));
    }*/

    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @ApiOperation("获取验证码")
    @GetMapping("/getAuthCode")
    public ResponseModel<Boolean> getAuthCode(@RequestParam String phoneNo) {
        HashMap<String, String> sendMap = new HashMap<>();
        sendMap.put("mobile", phoneNo);
        sendMap.put("smsType", "MOBILE_LOGIN");
        FeignClientResult<SmsRecordModel> sendVerifyCodeResult = Systemctl.smsClient.sendVerifyCode(sendMap);
        if (sendVerifyCodeResult.getStatus() != 200) {
            if (log.isErrorEnabled()) {
                log.error("调用平台发送验证码失败:{}", sendVerifyCodeResult.getDevMessage());
            }
            throw new BadRequest(sendVerifyCodeResult.getMessage());
        }
        return ResponseHelper.buildResponse(true);
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ApiOperation(httpMethod = "POST", value = "微信授权登陆", notes = "微信授权登陆")
    public ResponseModel<PeasantHouseholdWxDto> wxUserLogin(@ApiParam @RequestBody MobileLoginParamDto mobileLoginParam) {
        log.info("微信授权登录入参 => {}", mobileLoginParam);
        if (StringUtils.isBlank(mobileLoginParam.getAmosUserId())) {
            // 扫码的userId为空, 则取默认值
            mobileLoginParam.setAmosUserId(defaultUserId);
        }
        return ResponseHelper.buildResponse(peasantHouseholdServiceImpl.wxUserLogin(mobileLoginParam));
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @RequestMapping(value = "/getRegisterPhone", method = RequestMethod.POST)
    @ApiOperation(httpMethod = "POST", value = "获取手机号及回填信息", notes = "获取手机号及回填信息")
    public ResponseModel<Map<String, Object>> getRegisterPhone(@ApiParam @RequestBody MobileLoginParamDto mobileLoginParam) {
        log.info("微信授权注册入参 => {}", mobileLoginParam);
        if (StringUtils.isBlank(mobileLoginParam.getAmosUserId())) {
            // 扫码的userId为空, 则取默认值
            mobileLoginParam.setAmosUserId(defaultUserId);
        }
        return ResponseHelper.buildResponse(peasantHouseholdServiceImpl.getRegisterPhone(mobileLoginParam));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @RequestMapping(value = "/getJxsAndNhData", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET", value = "获取经销商农户信息", notes = "获取经销商农户信息")
    public ResponseModel<Map<String, Object>> getJxsAndNhData(@ApiParam(value = "农户Id") @RequestParam(value = "nhUserId") String nhUserId,
                                                              @ApiParam(value = "经销商Id") @RequestParam(value = "jxsUserId") String jxsUserId,
                                                              @ApiParam(value = "二维码类型") @RequestParam(value = "qrCodeType") String qrCodeType) {
        return ResponseHelper.buildResponse(peasantHouseholdServiceImpl.getJxsAndNhData(nhUserId, jxsUserId, qrCodeType));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @RequestMapping(value = "/getPeasantHouseByUserId", method = RequestMethod.POST)
    @ApiOperation(httpMethod = "POST", value = "分页获取农户", notes = "分页获取农户信息")
    public ResponseModel<IPage<PeasantHousehold>> getPeasantHouseByUserId(@RequestBody PeasantHouseholdPageDto peasantHouseholdPageDto) {
        return ResponseHelper.buildResponse(peasantHouseholdServiceImpl.getPeasantHousePage(peasantHouseholdPageDto));
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @RequestMapping(value = "/getPeasantHouseHistoryPage", method = RequestMethod.POST)
    @ApiOperation(httpMethod = "POST", value = "分页获取农户", notes = "分页获取农户信息")
    public ResponseModel<IPage<PeasantHousehold>> getPeasantHouseHistoryPage(@RequestBody PeasantHouseholdPageDto peasantHouseholdPageDto) {
        return ResponseHelper.buildResponse(peasantHouseholdServiceImpl.getPeasantHouseHistoryPage(peasantHouseholdPageDto));
    }

    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @RequestMapping(value = "/addPeasantHousehold", method = RequestMethod.POST)
    @ApiOperation(httpMethod = "POST", value = "新增农户", notes = "新增农户")
    public ResponseModel<String> addPeasantHousehold(@ApiParam @RequestBody PeasantHouseholdDto peasantHouseholdDto) {
        //此处是新增农户，根据用户id查询必须要有一个农户，否则直接抛错
        List<PeasantHousehold> peasantHouseList = peasantHouseholdServiceImpl.getPeasantHouseByUserId(peasantHouseholdDto.getAmosUserId());
        if (CollectionUtil.isEmpty(peasantHouseList)) {
            throw new BadRequest("没有查询到注册的农户，请注册后在进行新增");
        }
        validatedPeasantHouseholdDto(peasantHouseholdDto);
        PeasantHouseholdDto result = peasantHouseholdServiceImpl.addNewPeasantHousehold(peasantHouseholdDto);
        return ResponseHelper.buildResponse("success");

    }

    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    @ApiOperation(httpMethod = "POST", value = "微信农户注册", notes = "微信农户注册")
    public ResponseModel<PeasantHouseholdWxDto> wxUserRegister(@ApiParam @RequestBody MobileLoginParamDto mobileLoginParam) {
        PeasantHousehold peasantHousehold = new PeasantHousehold();
        try {
            log.info("微信农户注册, 入参 => {}", mobileLoginParam);
            PeasantHouseholdDto model = mobileLoginParam.getPeasantHouseholdDto();
            validatedPeasantHouseholdDto(model);
            PeasantHouseholdWxDto peasantHouseholdWxDto = peasantHouseholdServiceImpl.savePeasantHousehold(model, mobileLoginParam,peasantHousehold);
            peasantHouseholdWxDto.setPeasantHousehold(peasantHousehold);
            return ResponseHelper.buildResponse(peasantHouseholdWxDto);
        } catch (Exception e) {
        	e.printStackTrace();
            log.error(e.getMessage());
            if (null != peasantHousehold) {
                log.error("调用平台接口回滚注册的用户 => {}", e, peasantHousehold.getAmosUserId());
                // 调用平台接口回滚注册的用户
                RequestContext.setAppKey("AMOS_STUDIO");
                RequestContext.setProduct("AMOS_STUDIO_WEB");
                RequestContext.setToken(requestContext.getToken());
                Privilege.agencyUserClient.multDeleteUser(peasantHousehold.getAmosUserId());
            }
            if (e instanceof BadRequest || e.getCause() instanceof BadRequest) {
                throw new BadRequest(e.getMessage());
            }
            throw new BadRequest(e.getMessage());
        }

    }

    public JSONArray getRegionName() {
        JSONArray jsonArray = new JSONArray();
        if (redisUtil.hasKey(regionRedis)) {
            jsonArray = JSONArray.parseArray(redisUtil.get(regionRedis).toString());
        } else {
            Collection<RegionModel> regionChild = new ArrayList<>();
            RegionModel regionModel1 = new RegionModel();
            regionChild.add(regionModel1);
            FeignClientResult<Collection<RegionModel>> collectionFeignClientResult = Systemctl.regionClient.queryForTreeParent(610000L);
            Collection<RegionModel> result = collectionFeignClientResult.getResult();
            for (RegionModel regionModel : result) {
                if (null != regionModel && null != regionModel.getChildren()) {
                    for (RegionModel child : regionModel.getChildren()) {
                        if (null != child && null != child.getChildren()) {
                            for (RegionModel childChild : child.getChildren()) {
                                jsonArray.add(childChild);
                            }
                            child.setChildren(regionChild);
                            jsonArray.add(child);
                        }
                    }
                    regionModel.setChildren(regionChild);
                    jsonArray.add(regionModel);
                }
            }

            redisUtil.set(regionRedis, jsonArray);
        }
        return jsonArray;
    }


    @TycloudOperation(ApiLevel = UserType.AGENCY, needAuth = false)
    @GetMapping("/getRegionQrCode")
    @ApiOperation(httpMethod = "GET", value = " 获取区域经销商二维码", notes = " 获取区域经销商二维码")
    public ResponseModel<Map<String, Object>> getRegionQrCode(
            @RequestParam(value = "fileType", required = false, defaultValue = "png") String fileType,
            @RequestParam(value = "width", required = false, defaultValue = "350") String width,
            HttpServletResponse response) {
        AgencyUserModel userInfo = getUserInfo();
        log.info("获取区域经销商二维码, userId:{}", userInfo.getUserId());
        String accessToken = wxService.getAccessToken();
        // 生成二维码
        String page = miniprogramLoginPage;
        String scene = "amosUserId=" + userInfo.getUserId() + "&qrCodeType=1";
        // 返回当前用户ID
        String picStr = wxService.getSmallProQrCodeResponse(accessToken, scene, page, Long.valueOf(width), null, null, null, response,
                "二维码_" + userInfo.getUserId(), fileType);

        PeasantHouseholdDto peasantHouseholdDto = peasantHouseholdServiceImpl.buildDefaultPeasantHouseholdDto("region", userInfo);

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("qrCodePic", picStr);
        resultMap.put("peasantHousehold", peasantHouseholdDto);

        return ResponseHelper.buildResponse(resultMap);

    }

    private void validatedPeasantHouseholdDto(PeasantHouseholdDto model) {
        if (null == model) {
            throw new BadRequest("农户信息不能为空");
        }
        if (StringUtils.isBlank(model.getOwnersName())) {
            throw new BadRequest("姓名不能为空");
        }
        if (StringUtils.isBlank(model.getDeveloper())) {
            throw new BadRequest("开发人不能为空");
        }
        if (StringUtils.isBlank(model.getDeveloperCode())) {
            throw new BadRequest("开发方code不能为空");
        }
        if (StringUtils.isBlank(model.getDeveloperName())) {
            throw new BadRequest("开发方名称不能为空");
        }
        if (null == model.getDeveloperId()) {
            throw new BadRequest("开发方平台id不能为空");
        }
        if (null == model.getRegionalCompaniesSeq()) {
            throw new BadRequest("区域公司id不能为空");
        }
        if (StringUtils.isBlank(model.getRegionalCompaniesCode())) {
            throw new BadRequest("区域公司code不能为空");
        }
        if (StringUtils.isBlank(model.getRegionalCompaniesName())) {
            throw new BadRequest("区域公司名称不能为空");
        }
    }

}
