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.setPeasantHouseholdNo(peasantHouseholdServiceImpl.getPeasantHouseholdNo(peasantHouseholdDto.getRegionalCompaniesSeq()));
        peasantHouseholdDto.setIsCertified(1);// 这里就实名认证
        peasantHouseholdDto.setSurveyOrNot(0);
        peasantHouseholdDto.setReview(0);
        JSONArray regionName = getRegionName();
        List<RegionModel> list = JSONArray.parseArray(regionName.toJSONString(), RegionModel.class);
        // 处理项目地址
        String area = "";
        if (peasantHouseholdDto.getProjectAddress() != null && peasantHouseholdDto.getProjectAddress().size() != 0) {
            for (Integer reg : peasantHouseholdDto.getProjectAddress())
                for (RegionModel re : list) {
                    if (re.getRegionCode().equals(Integer.valueOf(reg))) {
                        area = area + re.getRegionName() + "/";
                    }
                }
            peasantHouseholdDto.setProjectAddressName(area.length() > 2 ? area.substring(0, area.length() - 1) : area);
            if ("1".equals(peasantHouseholdDto.getIsPermanent()) || "true".equals(peasantHouseholdDto.getIsPermanent())) {
                peasantHouseholdDto.setPermanentAddress(peasantHouseholdDto.getProjectAddress());
                peasantHouseholdDto.setPermanentAddressDetail(peasantHouseholdDto.getProjectAddressDetail());
                peasantHouseholdDto.setPermanentAddressName(area.length() > 2 ? area.substring(0, area.length() - 1) : area);
            } else {
                // 处理常住地址
                String permanent = "";
                if (peasantHouseholdDto.getPermanentAddress() != null && peasantHouseholdDto.getPermanentAddress().size() != 0) {
                    for (Integer reg : peasantHouseholdDto.getPermanentAddress())
                        for (RegionModel re : list) {
                            if (re.getRegionCode().equals(Integer.valueOf(reg))) {
                                permanent = permanent + re.getRegionName() + "/";
                            }
                        }
                    peasantHouseholdDto.setPermanentAddressName(permanent.length() > 2 ? permanent.substring(0, permanent.length() - 1) : permanent);
                }
            }
        }
        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);
            
            log.info("校验通过生成平台账号");
            //注册并登录 生成农户信息表数据
            PeasantHouseholdWxDto peasantHouseholdWxDto = peasantHouseholdServiceImpl.registerAndLogin(mobileLoginParam);
            peasantHousehold = peasantHouseholdWxDto.getPeasantHousehold();
            
            BeanDtoUtils.copyPropertiesAllNonNull(peasantHousehold, model);
            log.info("生成农户属性");
            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);
                    }
                }
            }
            log.info("更新农户信息");
            BeanDtoUtils.copyPropertiesAllNonNull(model, peasantHousehold);
            PeasantHouseholdDto result = peasantHouseholdServiceImpl.savePeasantHousehold(model, null);
            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("区域公司名称不能为空");
        }
    }

}
