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

import com.alibaba.fastjson.JSONArray;
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.PeasantHouseholdWxDto;
import com.yeejoin.amos.boot.module.hygf.api.service.IWxService;
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.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.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 {

    @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;

    private static final String regionRedis = "app_region_redis";

    /*@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 = "/register", method = RequestMethod.POST)
    @ApiOperation (httpMethod = "POST", value = "微信农户注册", notes = "微信农户注册")
    public ResponseModel<PeasantHouseholdDto> wxUserRegister(@ApiParam @RequestBody MobileLoginParamDto mobileLoginParam) {
        log.info("微信农户注册, 入参 => {}", mobileLoginParam);
        PeasantHouseholdDto model = mobileLoginParam.getPeasantHouseholdDto();
        validatedPeasantHouseholdDto(model);
        AgencyUserModel userInfo = getUserInfo();
        model.setAmosUserId(userInfo.getUserId());// 绑定平台userId
        model.setPeasantHouseholdNo(peasantHouseholdServiceImpl.getPeasantHouseholdNo(model.getRegionalCompaniesSeq()));
        model.setIsCertified(1);// 这里就实名认证
        model.setSurveyOrNot(0);
        model.setReview(0);
        JSONArray regionName = getRegionName();
        List<RegionModel> list = JSONArray.parseArray(regionName.toJSONString(), RegionModel.class);
        // 处理项目地址
        String area = "";
        if (model.getProjectAddress() != null && model.getProjectAddress().size() != 0) {
            for (Integer reg : model.getProjectAddress())
                for (RegionModel re : list) {
                    if (re.getRegionCode().equals(Integer.valueOf(reg))) {
                        area = area + re.getRegionName() + "/";
                    }
                }
            model.setProjectAddressName(area.length() > 2 ? area.substring(0, area.length() - 1) : area);
            if ("1".equals(model.getIsPermanent()) || "true".equals(model.getIsPermanent())) {
                model.setPermanentAddress(model.getProjectAddress());
                model.setPermanentAddressDetail(model.getProjectAddressDetail());
                model.setPermanentAddressName(area.length() > 2 ? area.substring(0, area.length() - 1) : area);
            } else {
                // 处理常住地址
                String permanent = "";
                if (model.getPermanentAddress() != null && model.getPermanentAddress().size() != 0) {
                    for (Integer reg : model.getPermanentAddress())
                        for (RegionModel re : list) {
                            if (re.getRegionCode().equals(Integer.valueOf(reg))) {
                                permanent = permanent + re.getRegionName() + "/";
                            }
                        }
                    model.setPermanentAddressName(permanent.length() > 2 ? permanent.substring(0, permanent.length() - 1) : permanent);
                }
            }
        }
        PeasantHouseholdDto result = peasantHouseholdServiceImpl.savePeasantHousehold(model, userInfo);

        return ResponseHelper.buildResponse(result);
    }

    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("区域公司名称不能为空");
        }
    }

}
