package com.yeejoin.amos.boot.module.hygf.biz.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.hygf.api.dto.*;
import com.yeejoin.amos.boot.module.hygf.api.entity.*;
import com.yeejoin.amos.boot.module.hygf.api.mapper.SurveyInformationMapper;
import com.yeejoin.amos.boot.module.hygf.api.service.ISurveyInformationService;
import com.yeejoin.amos.boot.module.hygf.api.util.BeanDtoUtils;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import com.yeejoin.amos.feign.systemctl.model.RegionModel;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

/**
 * 勘察信息服务实现类
 *
 * @author system_generator
 * @date 2023-07-07
 */
@Service
public class SurveyInformationServiceImpl extends BaseService<SurveyInformationDto,SurveyInformation,SurveyInformationMapper> implements ISurveyInformationService {


    @Autowired
    SurveyDetailsServiceImpl surveyDetailsService;

    @Autowired
    InformationServiceImpl informationService;

    @Autowired
    ExtendedInformationServiceImpl extendedInformationService;

    @Autowired
    CommercialServiceImpl commercialService;

    @Autowired
    PeasantHouseholdServiceImpl peasantHouseholdServiceImpl;

    @Autowired
    RedisUtils redisUtils;

    private static final String regionRedis="app_region_redis";


    /**
     * 分页查询
     */
    public Page<SurveyInformationDto> queryForSurveyInformationPage(Page<SurveyInformationDto> page)   {
        return this.queryForPage(page, null, false);
    }

    /**
     * 列表查询 示例
     */
    public List<SurveyInformationDto> queryForSurveyInformationList()   {
        return this.queryForList("" , false);
    }


    public SurveyInfoAllDto saveSurveyInfo(SurveyInfoAllDto surveyInfoAllDto,String operationType)   {
        JSONArray regionName = getRegionName();
        List<RegionModel> list = JSONArray.parseArray(regionName.toJSONString(), RegionModel.class);

        //更新勘察基本信息
        SurveyInformation surveyInformation = BeanDtoUtils.convert(surveyInfoAllDto.getSurveyInformation(), SurveyInformation.class);
        surveyInformation.setReview(0);
        this.saveOrUpdate(surveyInformation);

        //更新扩展信息
        ExtendedInformation extendedInformation = BeanDtoUtils.convert(surveyInfoAllDto.getExtendedInformation(), ExtendedInformation.class);
        extendedInformation.setSurveyInformationId(surveyInformation.getSequenceNbr());
        extendedInformationService.saveOrUpdate(extendedInformation);

        //更新勘察明细信息
        SurveyDetailsDto oldSurveyDetails = surveyInfoAllDto.getSurveyDetails();
        SurveyDetails surveyDetails = BeanDtoUtils.convert(oldSurveyDetails, SurveyDetails.class);
        surveyDetails.setSurveyInformationId(surveyInformation.getSequenceNbr());
        surveyDetailsService.saveOrUpdate(surveyDetails);

        //更新商务信息
        CommercialDto oldCommercial = surveyInfoAllDto.getCommercial();
        Commercial commercial = BeanDtoUtils.convert(oldCommercial, Commercial.class);
        // 处理省市县
        String paddressName = "";
        for (Integer reg : surveyInfoAllDto.getSurveyInformation().getProjectAddress()) {
            for (RegionModel re : list) {
                if (re.getRegionCode().equals(Integer.valueOf(reg))) {
                    paddressName = paddressName + re.getRegionName() + "/";
                }
            }
        }
        commercial.setProjectAddressName(paddressName.substring(0, paddressName.length() - 2));
        commercial.setSurveyInformationId(surveyInformation.getSequenceNbr());
        commercialService.saveOrUpdate(commercial);

        //更新资料归档信息
        Information information = BeanDtoUtils.convert(surveyInfoAllDto.getInformation(), Information.class);
        information.setSurveyInformationId(surveyInformation.getSequenceNbr());
        informationService.saveOrUpdate(information);

        //勘察后，更新状态
        QueryWrapper<PeasantHousehold> peasantHouseholdQueryWrapper = new QueryWrapper<>();
        peasantHouseholdQueryWrapper.eq("survey_information_id", surveyInformation.getSequenceNbr());
        PeasantHousehold peasantHousehold = peasantHouseholdServiceImpl.getBaseMapper().selectOne(peasantHouseholdQueryWrapper);
        if("submit".equals(operationType)){
            peasantHousehold.setSurveyOrNot(1);
        }else if("apply".equals(operationType)){
            peasantHousehold.setSurveyOrNot(2);
            peasantHousehold.setReview(1);
        }
        peasantHousehold.setOwnersName(surveyInfoAllDto.getSurveyInformation().getOwnersName());
        peasantHousehold.setTelephone(surveyInfoAllDto.getSurveyInformation().getTelephone());
        peasantHousehold.setIdCard(surveyInfoAllDto.getSurveyInformation().getIdCard());
        peasantHousehold.setMailbox(surveyInfoAllDto.getSurveyInformation().getMailbox());
        peasantHousehold.setProjectAddress(surveyInfoAllDto.getSurveyInformation().getProjectAddress());
        peasantHousehold.setProjectAddressDetail(surveyInfoAllDto.getSurveyInformation().getProjectAddressDetail());
        peasantHousehold.setPermanentAddress(surveyInfoAllDto.getSurveyInformation().getPermanentAddress());
        peasantHousehold.setPermanentAddressDetail(surveyInfoAllDto.getSurveyInformation().getPermanentAddressDetail());
        peasantHousehold.setPermanentAddressDetail(surveyInfoAllDto.getSurveyInformation().getPermanentAddressDetail());

        // 处理项目地址
        String projectAddressName = "";
        for (Integer reg : surveyInfoAllDto.getSurveyInformation().getProjectAddress()) {
            for (RegionModel re : list) {
                if (re.getRegionCode().equals(Integer.valueOf(reg))) {
                    projectAddressName = projectAddressName + re.getRegionName() + "/";
                }
            }
        }
        peasantHousehold.setProjectAddressName(projectAddressName.substring(0, projectAddressName.length() - 2));
        //常住地址
        String permanentAddressName = "";
        for (Integer reg : surveyInfoAllDto.getSurveyInformation().getPermanentAddress()) {
            for (RegionModel re : list) {
                if (re.getRegionCode().equals(Integer.valueOf(reg))) {
                    permanentAddressName = permanentAddressName + re.getRegionName() + "/";
                }
            }
        }
        peasantHousehold.setPermanentAddressName(permanentAddressName.substring(0, permanentAddressName.length() - 2));
        peasantHouseholdServiceImpl.saveOrUpdate(peasantHousehold);
        return surveyInfoAllDto;
    }

    public SurveyInfoAllDto querySurveyInfo(String surveyInformationId)   {

        SurveyInfoAllDto surveyInfoAllDto = new SurveyInfoAllDto();

        LambdaQueryWrapper<SurveyInformation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SurveyInformation::getSequenceNbr, surveyInformationId);
        SurveyInformation surveyInformation = this.baseMapper.selectOne(queryWrapper);
        surveyInfoAllDto.setSurveyInformation(BeanDtoUtils.convert(surveyInformation, SurveyInformationDto.class));

        QueryWrapper<PeasantHousehold> peasantHouseholdQueryWrapper = new QueryWrapper<>();
        peasantHouseholdQueryWrapper.eq("survey_information_id", surveyInformationId);
        PeasantHousehold peasantHousehold = peasantHouseholdServiceImpl.getBaseMapper().selectOne(peasantHouseholdQueryWrapper);
        BeanUtils.copyProperties(peasantHousehold, surveyInfoAllDto.getSurveyInformation());
        if (!StringUtils.isEmpty(peasantHousehold.getProjectAddressName())) {
            surveyInfoAllDto.getSurveyInformation().setProjectAddressText(Arrays.asList(peasantHousehold.getProjectAddressName().split("/")));
        }
        if(!StringUtils.isEmpty(peasantHousehold.getPermanentAddressName())){
            surveyInfoAllDto.getSurveyInformation().setPermanentAddressText(Arrays.asList(peasantHousehold.getPermanentAddressName().split("/")));
        }

        if(peasantHousehold.getPermanentAddress() ==null){
            surveyInfoAllDto.getSurveyInformation().setPermanentAddress(peasantHousehold.getProjectAddress());
            surveyInfoAllDto.getSurveyInformation().setIsPermanent("1");
        }
        surveyInfoAllDto.getSurveyInformation().setSequenceNbr(surveyInformation.getSequenceNbr());

        QueryWrapper<SurveyDetails> surveyDetailsQueryWrapper = new QueryWrapper<>();
        surveyDetailsQueryWrapper.eq("survey_information_id", surveyInformationId);
        SurveyDetails surveyDetails = surveyDetailsService.getBaseMapper().selectOne(surveyDetailsQueryWrapper);

        if(surveyDetails == null){
            surveyInfoAllDto.setSurveyDetails(new SurveyDetailsDto());
        }else {
            surveyInfoAllDto.setSurveyDetails(BeanDtoUtils.convert(surveyDetails, SurveyDetailsDto.class));
        }

        QueryWrapper<Information> informationQueryWrapper = new QueryWrapper<>();
        informationQueryWrapper.eq("survey_information_id", surveyInformationId);
        Information information = informationService.getBaseMapper().selectOne(informationQueryWrapper);

        if(information == null){
            surveyInfoAllDto.setInformation(new InformationDto());
        }else {
            surveyInfoAllDto.setInformation(BeanDtoUtils.convert(information, InformationDto.class));
        }
        QueryWrapper<Commercial> commercialQueryWrapper = new QueryWrapper<>();
        commercialQueryWrapper.eq("survey_information_id", surveyInformationId);
        Commercial commercial = commercialService.getBaseMapper().selectOne(commercialQueryWrapper);
        if(information == null){
            surveyInfoAllDto.setCommercial(new CommercialDto());
        }else {
            surveyInfoAllDto.setCommercial(BeanDtoUtils.convert(commercial, CommercialDto.class));
            if(commercial !=null && !StringUtils.isEmpty(commercial.getProjectAddressName())){
                surveyInfoAllDto.getCommercial().setProjectAddressText(Arrays.asList(commercial.getProjectAddressName().split("/")));
            }
        }

        QueryWrapper<ExtendedInformation> extendedInformationQueryWrapper = new QueryWrapper<>();
        extendedInformationQueryWrapper.eq("survey_information_id", surveyInformationId);
        ExtendedInformation extendedInformation = extendedInformationService.getBaseMapper().selectOne(extendedInformationQueryWrapper);
        if(information == null){
            surveyInfoAllDto.setExtendedInformation(new ExtendedInformationDto());
        }else {
            surveyInfoAllDto.setExtendedInformation(BeanDtoUtils.convert(extendedInformation, ExtendedInformationDto.class));
        }
        return surveyInfoAllDto;
    }


    public JSONArray getRegionName(){
        JSONArray jsonArray = new JSONArray();
        if (redisUtils.hasKey(regionRedis)) {
            jsonArray= JSONArray.parseArray(redisUtils.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) {
                for (RegionModel child : regionModel.getChildren()) {
                    for (RegionModel childChild : child.getChildren()) {
                        jsonArray.add(childChild);
                    }
                    child.setChildren(regionChild);
                    jsonArray.add(child);
                }
                regionModel.setChildren(regionChild);
                jsonArray.add(regionModel);
            }

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