package com.ruoyi.ibs.grid.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.ibs.customerselect.domain.CustInfoDeleteFromAnchor;
import com.ruoyi.ibs.customerselect.domain.CustInfoUpdateFromAnchor;
import com.ruoyi.ibs.customerselect.service.IMyCustomerService;
import com.ruoyi.ibs.enumertion.CustTypeEnum;
import com.ruoyi.ibs.grid.domain.dto.AnchorRefreshDTO;
import com.ruoyi.ibs.grid.domain.entity.IbsAnchor;
import com.ruoyi.ibs.grid.domain.entity.IbsAnchorAddress;
import com.ruoyi.ibs.grid.domain.excel.NewPersonAnchor;
import com.ruoyi.ibs.grid.domain.excel.NewQyAnchor;
import com.ruoyi.ibs.grid.domain.vo.*;
import com.ruoyi.ibs.grid.mapper.AnchorAddressMapper;
import com.ruoyi.ibs.grid.mapper.AnchorMapper;
import com.ruoyi.ibs.grid.service.AddressAnalyseService;
import com.ruoyi.ibs.grid.service.AnchorService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import static com.ruoyi.common.utils.PageUtils.startPage;


@Service
public class AnchorServiceImpl implements AnchorService {

    @Autowired
    AnchorMapper mapper;

    @Autowired
    AnchorAddressMapper addressMapper;

    @Autowired
    AddressAnalyseService addressAnalyseService;

    @Autowired
    IMyCustomerService iMyCustomerService;

    @Override
    public List<AnchorVo> selectAnchorList(String userid, String custType,String anchorName,String street,String community,String source,String custStatus,String custAddressStatus,String status) {
        userid = SecurityUtils.getUsername();
        HashMap<String, Object> paramMap = new HashMap<>();
//        if (SecurityUtils.userRole().equals("head") || SecurityUtils.userRole().equals("public")||SecurityUtils.userRole().equals("private")||SecurityUtils.userRole().equals("ops")||SecurityUtils.userRole().equals("branch")){
//        if(SecurityUtils.userRole().equals("head") || SecurityUtils.userRole().equals("public")||SecurityUtils.userRole().equals("private")||SecurityUtils.userRole().equals("ops")){
//            userid = userid.substring(0,3);
//        }

        if(SecurityUtils.userRole().equals("branch")){
            paramMap.put("isHead",false);
            paramMap.put("deptId",SecurityUtils.getDeptId());
        }
        paramMap.put("userid",userid);
        paramMap.put("custType",custType);
        paramMap.put("anchorName",anchorName);
        paramMap.put("street",street);
        paramMap.put("community",community);
        paramMap.put("source",source);
        paramMap.put("custStatus",custStatus);
        paramMap.put("status",status);
        paramMap.put("custAddressStatus",custAddressStatus);
        //分页插件，pageNum为当前页码，固定每页展示五条
        List<AnchorVo> list = mapper.selectAnchorList(paramMap);
        return list;
//    }
//        //待补充客户经理查询
//        paramMap.put("userid",userid);
//        paramMap.put("custType",custType);
//        paramMap.put("anchorName",anchorName);
//        paramMap.put("street",street);
//        paramMap.put("community",community);
//        paramMap.put("source",source);
//        paramMap.put("custStatus",custStatus);
//        paramMap.put("custAddressStatus",custAddressStatus);
//        List<AnchorVo> list = mapper.selectAnchorListWithRegion(paramMap);
//        return list;
    }


    @Override
    public List<AuditVo> selectAuditList(String userid, String custType,String custStatus,String custAddressStatus) {
        userid = SecurityUtils.getUsername();
        HashMap<String, Object> paramMap = new HashMap<>();
//            if(SecurityUtils.userRole().equals("head") || SecurityUtils.userRole().equals("public")||SecurityUtils.userRole().equals("private")||SecurityUtils.userRole().equals("ops")){
//                userid = userid.substring(0,3);
//            }
        if(SecurityUtils.userRole().equals("branch")){
            paramMap.put("isHead",false);
            paramMap.put("deptId",SecurityUtils.getDeptId());
        }
        paramMap.put("userid",userid);
        paramMap.put("custType",custType);
        paramMap.put("custStatus",custStatus);
        paramMap.put("custAddressStatus",custAddressStatus);
        //分页插件，pageNum为当前页码，固定每页展示五条
        List<AuditVo> list = mapper.selectAuditList(paramMap);
        return list;
    }

    @Override
    public List<IgnoreVo> selectIgnoreList(String userid, String custType,String custStatus,String custAddressStatus) {
        userid = SecurityUtils.getUsername();
        HashMap<String, Object> paramMap = new HashMap<>();
//        if(SecurityUtils.userRole().equals("head") || SecurityUtils.userRole().equals("public")||SecurityUtils.userRole().equals("private")||SecurityUtils.userRole().equals("ops")){
//            userid = userid.substring(0,3);
//        }
        if(SecurityUtils.userRole().equals("branch")){
            paramMap.put("isHead",false);
            paramMap.put("deptId",SecurityUtils.getDeptId());
        }
        paramMap.put("userid",userid);
        paramMap.put("custType",custType);
        paramMap.put("custStatus",custStatus);
        paramMap.put("custAddressStatus",custAddressStatus);
        //分页插件，pageNum为当前页码，固定每页展示五条
        List<IgnoreVo> list = mapper.selectIgnoreList(paramMap);
        return list;
    }

    @Override
    @Transactional
    public AjaxResult delIgnore(int[] ids) {
        for (int id:ids
             ) {
               mapper.delIgnore(id);
        }
        return AjaxResult.success("删除成功");
    }

    @Override
    @Transactional
    public AjaxResult delAnchor(int[] ids) {
        for (int id:ids
        ) {
            String roleName = SecurityUtils.getLoginUser().getUser().getRoleName();
            IbsAnchor ibsAnchor = mapper.selectOne(new LambdaQueryWrapper<IbsAnchor>().eq(IbsAnchor::getId, id));
            if(SecurityUtils.getUsername().equals(ibsAnchor.getUpdateBy())||SecurityUtils.userRole().equals("head") || SecurityUtils.userRole().equals("public")||SecurityUtils.userRole().equals("private")||SecurityUtils.userRole().equals("ops")) {
                //查询到该id下锚点的legalId，删除所有客户经理操作的锚点。以及锚点对应的地址
                String legalId = ibsAnchor.getLegalId();
                CustInfoDeleteFromAnchor delAnchor = new CustInfoDeleteFromAnchor();
                delAnchor.setCustType(ibsAnchor.getCustType());
                delAnchor.setLegalId(ibsAnchor.getLegalId());
                iMyCustomerService.custInfoDelete(delAnchor);
                mapper.delAnchorByLegalId(legalId);
                mapper.delAddressByLegalId(legalId);
            }
        }
        return AjaxResult.success("删除成功");
    }

    @Override
    public AjaxResult anchorDetai(String anchorid) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("anchorid",anchorid);
        AnchorDetail ad = mapper.selectAnchorDetail(paramMap);
        List<AddressDetail> addressDetails = mapper.selectAnchorAddressList(paramMap);
        if(addressDetails.isEmpty()){
            ad.setAddressList(null);
        }else{
            ad.setAddressList(addressDetails);
        }
        return AjaxResult.success(ad);
    }

    @Override
    public AnchorDetail anchorDetai1(String anchorid) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("anchorid",anchorid);
        AnchorDetail ad = mapper.selectAnchorDetail(paramMap);
        ad.setAddressList(mapper.selectAnchorAddressList(paramMap));
        return ad;
    }

    @Override
    @Transactional
    public AjaxResult reAudit(int[] ids) {
        for (int id:ids
        ) {
            mapper.reAudit(id);
        }
        return AjaxResult.success("已上架重新审核");
    }

    @Override
    @Transactional
    public AjaxResult setIgnore(int[] ids) {
        for (int id:ids
        ) {
            mapper.setIgnore(id);
        }
        return AjaxResult.success("地址已忽略");
    }

    @Override
    @Transactional
    public AjaxResult updateAnchor(AnchorDetail anchorDetail, String userid) {
        userid = SecurityUtils.getUsername();
        HashMap<String, Object> anchorParamMap = new HashMap<>();
        anchorParamMap.put("legalId",anchorDetail.getLegalId());
        anchorParamMap.put("anchorName",anchorDetail.getAnchorName());
        anchorParamMap.put("anchorRemark",anchorDetail.getAnchorRemark());
        anchorParamMap.put("belongBusiness",anchorDetail.getBelongBusiness());
        anchorParamMap.put("custType",anchorDetail.getCustType());
        int num  = mapper.updateAnchor(anchorParamMap);
        //补充客户表更新
        CustInfoUpdateFromAnchor ciufa = new CustInfoUpdateFromAnchor();
        ciufa.setAnchorName(anchorDetail.getAnchorName());
        ciufa.setBelongBusiness(anchorDetail.getBelongBusiness());
        ciufa.setLegalId(anchorDetail.getLegalId());
        ciufa.setCustType(anchorDetail.getCustType());
        iMyCustomerService.custInfoUpdate(ciufa);
        if (num <= 0 ){
            return AjaxResult.error("更新失败");
        }
        for (AddressDetail ad:anchorDetail.getAddressList()
             ) {
            //只处理手动导入地址数据
            if (!ad.getSource().equals("手工导入")){
                continue;
            }
            //处理更新地址
            AddressDetail detail = mapper.selectAddressDetailById(ad.getId());
            if (!ad.equals(detail)){
                IbsAnchorAddress iaaBefore = addressMapper.selectById(ad.getId());
                IbsAnchorAddress iaa = new IbsAnchorAddress();
                BeanUtils.copyProperties(iaaBefore,iaa);
                //处理变更的地址信息
                iaa.setAddressName(ad.getAddressName());
                iaa.setId(0L);
                iaa.setAddressNow(ad.getAddress());
                //补充解析地址分级
                AddressResultVO addressResultVO = addressAnalyseService.addressStandardize(ad.getAddress());
                iaa.setStreetNow(addressResultVO.getTown());
                iaa.setCommunityNow(addressResultVO.getVillage());
                iaa.setRegionCode(addressResultVO.getCode());
                //待补充经纬度解析
                iaa.setAnchorId(anchorDetail.getLegalId());
                iaa.setType("地址变化");
                iaa.setSource("手工导入");
                iaa.setAddressStatus(0);
                iaa.setDeleteStatus(0);
                iaa.setUpdateStatus(0);
                iaa.setUpdateBy(userid);
                iaa.setUpdateTime(new Date());
                iaa.setUpdateOrg(SecurityUtils.getDeptId()+"");
                addressMapper.insert(iaa);
            }
        }
        return AjaxResult.success("修改成功");
    }

    @Override
    public AjaxResult insertNewAnchor(List<NewAnchor> list) {
        String userid = SecurityUtils.getUsername();
        String roleName = SecurityUtils.getLoginUser().getUser().getRoleName();
        List<NewAnchor> listFail= new ArrayList<>();
        for (int i = 0; i <list.size(); i++) {
            NewAnchor nanchor = list.get(i);
            String legalId = nanchor.getLegalId();
            List<IbsAnchor> anchorList = mapper.selectList(new LambdaQueryWrapper<IbsAnchor>().eq(IbsAnchor::getLegalId,legalId).eq(IbsAnchor::getDeleteStatus,0).eq(IbsAnchor::getCustType,nanchor.getCustType()));
            //2.0.0版本，不做限制，均可新增
//            IbsAnchor userAnchor= mapper.selectOne(new LambdaQueryWrapper<IbsAnchor>().eq(IbsAnchor::getLegalId,legalId).eq(IbsAnchor::getUpdateBy,userid).eq(IbsAnchor::getDeleteStatus,0).eq(IbsAnchor::getCustType,nanchor.getCustType()));
//            if(SecurityUtils.userRole().equals("branch")){
//            //判断新增的锚点是否是别人新增的,只在支行层级判断
//            if (userAnchor==null&!anchorList.isEmpty()){
//                listFail.add(nanchor);
//                continue;
//            }}
            if(anchorList.isEmpty()){
//                nanchor.setCustType(CustTypeEnum.getByName(nanchor.getCustType()).getCode());
                //若该锚点不存在则新增锚点
                IbsAnchor ibsAnchor = new IbsAnchor();
                ibsAnchor.setId(0L);
                ibsAnchor.setLegalId(nanchor.getLegalId());
                ibsAnchor.setSource("手工导入");
                ibsAnchor.setAnchorName(nanchor.getAnchorName());
                ibsAnchor.setCustIdType(nanchor.getCustIdType());
                ibsAnchor.setAnchorRemark(nanchor.getAnchorRemark());
                ibsAnchor.setBelongBusiness(nanchor.getBelongBusiness());
                ibsAnchor.setUpdateOrg(SecurityUtils.getDeptId()+"");
                ibsAnchor.setCustType(nanchor.getCustType());
                if(nanchor.getCustType().equals("0")){
                    ibsAnchor.setCustId("101"+nanchor.getLegalId());
                }else{
                    ibsAnchor.setCustId("202"+nanchor.getLegalId());
                }
                ibsAnchor.setStatus("未上图");
                ibsAnchor.setUpdateBy(userid);
                ibsAnchor.setDeleteStatus(0);
                mapper.insert(ibsAnchor);

                CustInfoUpdateFromAnchor ciufa = new CustInfoUpdateFromAnchor();
                ciufa.setCustType(ibsAnchor.getCustType());
                ciufa.setLegalId(ibsAnchor.getLegalId());
                ciufa.setCustId(ibsAnchor.getCustId());
                ciufa.setBelongBusiness(ibsAnchor.getBelongBusiness());
                ciufa.setAnchorName(ibsAnchor.getAnchorName());
                ciufa.setCustIdType(ibsAnchor.getCustIdType());
                ciufa.setCustIsn(ibsAnchor.getCustIsn());
                ciufa.setUpdateBy(ibsAnchor.getUpdateBy());
                ciufa.setUpdateOrg(ibsAnchor.getUpdateOrg());
                //补充客户表新增
                iMyCustomerService.custInfoUpdate(ciufa);
            }
            //查地址是否存在
            IbsAnchorAddress ibsAnchorAddress1 = addressMapper.selectOne(new LambdaQueryWrapper<IbsAnchorAddress>()
                    .eq(IbsAnchorAddress::getAnchorId, nanchor.getLegalId())
                    .eq(IbsAnchorAddress::getAddressName, nanchor.getAddressName())
                    .eq(IbsAnchorAddress::getSource,"手工导入")
                    .eq(IbsAnchorAddress::getDeleteStatus, 0)
                    .eq(IbsAnchorAddress::getAddressStatus, 1));
            IbsAnchorAddress iaa = new IbsAnchorAddress();
            iaa.setAddress("");
            iaa.setType("新成立");
            iaa.setSource("手工导入");
            if (ibsAnchorAddress1!=null){
                //存在则将原信息添加进去作为原地址
                BeanUtils.copyProperties(ibsAnchorAddress1,iaa);
                iaa.setType("地址变化");
            }
            //无论是否存在也将数据添加进去作为现地址
            iaa.setAddressName(nanchor.getAddressName());
            iaa.setId(0L);
            iaa.setAddressNow(nanchor.getAddress());
            //地址解析功能
            AddressResultVO addressResultVO = addressAnalyseService.addressStandardize(nanchor.getAddress());
            if(addressResultVO.getStatus()==0)
            {
            iaa.setProvinceNow(addressResultVO.getProvince());
            iaa.setCityNow(addressResultVO.getCity());
            iaa.setCountyNow(addressResultVO.getCounty());
            iaa.setStreetNow(addressResultVO.getTown());
            iaa.setCommunityNow(addressResultVO.getVillage());
            iaa.setRegionCode(addressResultVO.getCode());
            }
            //待补充经纬度解析。经纬度解析在审核通过时补充
            //iaa.setLatitude(addressResultVO.getLat()+"");
            //iaa.setLongitude(addressResultVO.getLng()+"");
            iaa.setAnchorId(nanchor.getLegalId());
            iaa.setAddressStatus(0);
            iaa.setDeleteStatus(0);
            iaa.setUpdateStatus(0);
            iaa.setUpdateBy(userid);
            iaa.setUpdateOrg(SecurityUtils.getDeptId()+"");
            addressMapper.insert(iaa);
        }
        if (listFail.isEmpty()){
            return AjaxResult.success("导入成功");
        }
        if (listFail.size()==list.size())
        {
            return AjaxResult.success("全部失败");
        }
        return AjaxResult.success("部分成功",listFail);
    }

    @Override
    @Transactional
    public AjaxResult passAudit2(List<AuditVo> list1) {
        for (AuditVo iaa:list1
        ) {
            //先更新客户经理调整的地址分级
            IbsAnchorAddress ibaa = addressMapper.selectById(iaa.getId());
            ibaa.setCityNow(iaa.getCityNow());
            ibaa.setCountyNow(iaa.getCountyNow());
            ibaa.setProvince(ibaa.getProvinceNow());
            ibaa.setCommunityNow(iaa.getCommunityNow());
            ibaa.setStreet(iaa.getStreetNow());
            ibaa.setAddressDetailNow(iaa.getAddressDetailNow());
            //更新前端传过来的行政区划编码
            ibaa.setRegionCode(iaa.getRegionCode());
            addressMapper.update(ibaa,new LambdaQueryWrapper<IbsAnchorAddress>().eq(IbsAnchorAddress::getId,iaa.getId()));
            IbsAnchorAddress ibsAnchorAddress = addressMapper.selectById(iaa.getId());
            //先更新掉锚点对应的所有该种审核通过的地址状态为删除状态
            String anchorid = ibsAnchorAddress.getAnchorId();
            String addressName = ibsAnchorAddress.getAddressName();
            IbsAnchorAddress ibsAnchorAddress1 = addressMapper.selectOne(new LambdaQueryWrapper<IbsAnchorAddress>()
                    .eq(IbsAnchorAddress::getAnchorId, anchorid)
                    .eq(IbsAnchorAddress::getAddressName, addressName)
                    .eq(IbsAnchorAddress::getSource,"手工导入")
                    .eq(IbsAnchorAddress::getDeleteStatus, 0)
                    .eq(IbsAnchorAddress::getAddressStatus, 1));
            if (ibsAnchorAddress1!=null) {
                ibsAnchorAddress1.setDeleteStatus(1);
                addressMapper.updateById(ibsAnchorAddress1);
            }
            ibsAnchorAddress.setProvince(ibsAnchorAddress.getProvinceNow());
            ibsAnchorAddress.setCity(ibsAnchorAddress.getCityNow());
            ibsAnchorAddress.setCounty(ibsAnchorAddress.getCountyNow());
            ibsAnchorAddress.setAddress(ibsAnchorAddress.getAddressNow());
            ibsAnchorAddress.setStreet(ibsAnchorAddress.getStreetNow());
            ibsAnchorAddress.setCommunity(ibsAnchorAddress.getCommunityNow());
            ibsAnchorAddress.setAddressDetail(ibsAnchorAddress.getAddressDetailNow());
            //更新经纬度
            AddressResultVO addressResultVO = addressAnalyseService.addressStandardize(ibsAnchorAddress.getAddressNow());
            if(addressResultVO.getStatus()==0)
            {
                ibsAnchorAddress.setLongitude(addressResultVO.getLng() + "");
                ibsAnchorAddress.setLatitude(addressResultVO.getLat() + "");
                if (iaa.getRegionCode().equals("")||iaa.getRegionCode()==null){
                    ibsAnchorAddress.setRegionCode(addressResultVO.getCode()+"");
                }
//                ibsAnchorAddress.setRegionCode(addressResultVO.getCode()+"");
                //regionCode改为前端传值
            }
            //将新地址设置为审核通过状态
            ibsAnchorAddress.setAddressStatus(1);
            addressMapper.updateById(ibsAnchorAddress);
            //查询锚点使用地址是否与该地址一致，不一致则直接通过就好，一致则需要修改锚点对应使用地址。
            List<IbsAnchor> list = mapper.selectList(new LambdaQueryWrapper<IbsAnchor>().eq(IbsAnchor::getLegalId, anchorid).eq(IbsAnchor::getDeleteStatus,0));
            IbsAnchorAddress oldAddress = addressMapper.selectById(list.get(0).getAddressId());
            CustInfoUpdateFromAnchor ciufa = new CustInfoUpdateFromAnchor();
            ciufa.setAddressName(iaa.getAddressName());
            ciufa.setLegalId(anchorid);
            ciufa.setCustType(list.get(0).getCustType());
            ciufa.setAddress(ibsAnchorAddress.getAddress());
            ciufa.setAddressDetail(ibsAnchorAddress.getAddressDetail());
            ciufa.setRegionCode(null);
            if (!list.isEmpty()&&ibsAnchorAddress1!=null&&list.get(0).getAddressId().equals(ibsAnchorAddress1.getId())){
                HashMap<String, Object> anchorParamMap = new HashMap<>();
                anchorParamMap.put("addressid",iaa.getId());
                anchorParamMap.put("legalId",anchorid);
                mapper.updateAnchor2(anchorParamMap);
                ciufa.setRegionCode(ibsAnchorAddress.getRegionCode());
            }
            if (oldAddress==null||(!(iaa.getAddressName().equals(oldAddress.getAddressName())&&!iaa.getSource().equals(oldAddress.getSource())))) {
                iMyCustomerService.custInfoUpdate(ciufa);
            }
        }
        return AjaxResult.success("已使用新地址");
    }
    @Override
    public AjaxResult insertNewQyAnchor(List<NewQyAnchor> list, String userid) {
        userid = SecurityUtils.getUsername();
        String roleName = SecurityUtils.getLoginUser().getUser().getRoleName();
        List<NewQyAnchor> listFail= new ArrayList<>();
        for (NewQyAnchor qyAnchor:list
             ) {
            qyAnchor.setCustType(CustTypeEnum.getByName(qyAnchor.getCustType()).getCode());
            //查锚点是否存在
            List<IbsAnchor> anchorList = mapper.selectList(new LambdaQueryWrapper<IbsAnchor>().eq(IbsAnchor::getLegalId,qyAnchor.getLegalId()).eq(IbsAnchor::getDeleteStatus,0));
            //校验必填项是否填写
            if (qyAnchor.getCustType()==null||qyAnchor.getCustType().equals("")||qyAnchor.getAnchorName()==null||qyAnchor.getAnchorName().equals("")||qyAnchor.getCustIdType()==null||qyAnchor.getCustIdType().equals("")||qyAnchor.getLegalId()==null||qyAnchor.getLegalId().equals("")){
                listFail.add(qyAnchor);
                continue;
            }
            //校验地址是否至少必填一项
            if (qyAnchor.getAddressZc()==null||qyAnchor.getAddressZc().equals("")){
                    if (qyAnchor.getAddressJy()==null||qyAnchor.getAddressJy().equals("")){
                        listFail.add(qyAnchor);
                        continue;
                    }
            }
            if(anchorList.isEmpty()){
                //若该锚点不存在则新增锚点
                IbsAnchor ibsAnchor = new IbsAnchor();
                ibsAnchor.setId(0L);
                ibsAnchor.setCustId(qyAnchor.getCustId());
                ibsAnchor.setCustIsn(qyAnchor.getCustIsn());
                ibsAnchor.setLegalId(qyAnchor.getLegalId());
                ibsAnchor.setBelongBusiness(qyAnchor.getBelongBusiness());
                ibsAnchor.setSource("手工导入");
                ibsAnchor.setAnchorName(qyAnchor.getAnchorName());
                ibsAnchor.setCustIdType(qyAnchor.getCustIdType());
                ibsAnchor.setUpdateOrg(SecurityUtils.getDeptId()+"");
                if(qyAnchor.getCustType().equals("0")){
                    ibsAnchor.setCustId("101"+qyAnchor.getLegalId());
                }else{
                    ibsAnchor.setCustId("202"+qyAnchor.getLegalId());
                }
                ibsAnchor.setAnchorRemark(qyAnchor.getAnchorRemark());
                ibsAnchor.setCustType(qyAnchor.getCustType());
                ibsAnchor.setStatus("未上图");
                ibsAnchor.setUpdateBy(userid);
                ibsAnchor.setUpdateOrg(SecurityUtils.getDeptId()+"");
                ibsAnchor.setDeleteStatus(0);
                mapper.insert(ibsAnchor);
                //新增客户表内容
                CustInfoUpdateFromAnchor ciufa = new CustInfoUpdateFromAnchor();
                ciufa.setCustType(ibsAnchor.getCustType());
                ciufa.setLegalId(ibsAnchor.getLegalId());
                ciufa.setCustId(ibsAnchor.getCustId());
                ciufa.setBelongBusiness(ibsAnchor.getBelongBusiness());
                ciufa.setAnchorName(ibsAnchor.getAnchorName());
                ciufa.setCustIdType(ibsAnchor.getCustIdType());
                ciufa.setCustIsn(ibsAnchor.getCustIsn());
                ciufa.setUpdateBy(ibsAnchor.getUpdateBy());
                ciufa.setUpdateOrg(ibsAnchor.getUpdateOrg());
                //补充客户表新增
                 iMyCustomerService.custInfoUpdate(ciufa);
            }
            //处理地址
                if ((!qyAnchor.getAddressJy().equals(""))&&qyAnchor.getAddressJy()!=null){
                    insertAddress(qyAnchor.getLegalId(),"经营地址",qyAnchor.getAddressJy());
                    //处理经营地址
                    //查地址是否存在
                }
                if ((!qyAnchor.getAddressZc().equals(""))&&qyAnchor.getAddressZc()!=null){
                    insertAddress(qyAnchor.getLegalId(),"注册地址",qyAnchor.getAddressZc());
                    //处理注册地址
                    //查地址是否存在
            }
        }
        if (listFail.isEmpty()){
            return AjaxResult.success("导入成功");
        }
        if (listFail.size()==list.size())
        {
            return AjaxResult.success("全部失败");
        }
        return AjaxResult.success("部分成功",listFail);
    }

    @Override
    public AjaxResult insertNewGrAnchor(List<NewPersonAnchor> list) {
        String userid = SecurityUtils.getUsername();
        String roleName = SecurityUtils.getLoginUser().getUser().getRoleName();
        List<NewPersonAnchor> listFail= new ArrayList<>();
        for (NewPersonAnchor grAnchor:list
        ) {
            grAnchor.setCustType(CustTypeEnum.getByName(grAnchor.getCustType()).getCode());
            //查锚点是否存在
            List<IbsAnchor> anchorList = mapper.selectList(new LambdaQueryWrapper<IbsAnchor>().eq(IbsAnchor::getLegalId,grAnchor.getLegalId()).eq(IbsAnchor::getDeleteStatus,0));
            //校验必填项是否填写
            if (grAnchor.getAnchorName()==null||grAnchor.getAnchorName().equals("")||grAnchor.getCustIdType()==null||grAnchor.getCustIdType().equals("")||grAnchor.getLegalId()==null||grAnchor.getLegalId().equals("")){
                listFail.add(grAnchor);
                continue;
            }
            //校验地址是否至少必填一项
            if (grAnchor.getAddressJt()==null||grAnchor.getAddressJt().equals("")){
                if (grAnchor.getAddressHj()==null||grAnchor.getAddressJt().equals("")){
                    if (grAnchor.getAddressGz()==null||grAnchor.getAddressGz().equals("")){
                        listFail.add(grAnchor);
                        continue;
                    }
                }
            }
            if(anchorList.isEmpty()){
                //若该锚点不存在则新增锚点
                IbsAnchor ibsAnchor = new IbsAnchor();
                ibsAnchor.setId(0L);
                ibsAnchor.setCustId(grAnchor.getCustId());
                ibsAnchor.setCustIsn(grAnchor.getCustIsn());
                ibsAnchor.setLegalId(grAnchor.getLegalId());
                ibsAnchor.setSource("手工导入");
                ibsAnchor.setAnchorName(grAnchor.getAnchorName());
                ibsAnchor.setCustIdType(grAnchor.getCustIdType());
                ibsAnchor.setUpdateOrg(SecurityUtils.getDeptId()+"");
                if(grAnchor.getCustType().equals("0")){
                    ibsAnchor.setCustId("101"+grAnchor.getLegalId());
                }else{
                    ibsAnchor.setCustId("202"+grAnchor.getLegalId());
                }
                ibsAnchor.setAnchorRemark(grAnchor.getAnchorRemark());
                ibsAnchor.setCustType(grAnchor.getCustType());
                ibsAnchor.setStatus("未上图");
                ibsAnchor.setUpdateBy(userid);
                ibsAnchor.setBelongBusiness(grAnchor.getBelongBusiness());
                ibsAnchor.setDeleteStatus(0);
                mapper.insert(ibsAnchor);

                CustInfoUpdateFromAnchor ciufa = new CustInfoUpdateFromAnchor();
                ciufa.setCustType(ibsAnchor.getCustType());
                ciufa.setLegalId(ibsAnchor.getLegalId());
                ciufa.setCustId(ibsAnchor.getCustId());
                ciufa.setBelongBusiness(ibsAnchor.getBelongBusiness());
                ciufa.setAnchorName(ibsAnchor.getAnchorName());
                ciufa.setCustIdType(ibsAnchor.getCustIdType());
                ciufa.setCustIsn(ibsAnchor.getCustIsn());
                ciufa.setUpdateBy(ibsAnchor.getUpdateBy());
                ciufa.setUpdateOrg(ibsAnchor.getUpdateOrg());
                //补充客户表新增
                iMyCustomerService.custInfoUpdate(ciufa);
            }
            //处理地址
            if ((!grAnchor.getAddressGz().equals(""))&&grAnchor.getAddressGz()!=null){
                insertAddress(grAnchor.getLegalId(),"工作地址",grAnchor.getAddressGz());
                //处理工作地址
                //查地址是否存在
            }
            if ((!grAnchor.getAddressJt().equals(""))&&grAnchor.getAddressJt()!=null){
                insertAddress(grAnchor.getLegalId(),"家庭地址",grAnchor.getAddressJt());
                //处理家庭地址
                //查地址是否存在
            }
            if ((!grAnchor.getAddressHj().equals(""))&&grAnchor.getAddressHj()!=null){
                insertAddress(grAnchor.getLegalId(),"户籍地址",grAnchor.getAddressHj());
                //处理户籍地址
                //查地址是否存在
            }
            if ((!grAnchor.getAddressCz().equals(""))&&grAnchor.getAddressCz()!=null){
                insertAddress(grAnchor.getLegalId(),"常住地址",grAnchor.getAddressCz());
                //处理常住地址
                //查地址是否存在
            }
            if ((!grAnchor.getAddressSfz().equals(""))&&grAnchor.getAddressSfz()!=null){
                insertAddress(grAnchor.getLegalId(),"身份证地址",grAnchor.getAddressSfz());
                //处理身份证地址
                //查地址是否存在
            }
            if ((!grAnchor.getAddressLx().equals(""))&&grAnchor.getAddressLx()!=null){
                insertAddress(grAnchor.getLegalId(),"联系地址",grAnchor.getAddressLx());
                //处理联系地址
                //查地址是否存在
            }
        }
        if (listFail.isEmpty()){
            return AjaxResult.success("导入成功");
        }
        if (listFail.size()==list.size())
        {
            return AjaxResult.success("全部失败");
        }
        return AjaxResult.success("部分成功",listFail);
    }

    @Override
    public AjaxResult setIgnoreUp(List<AuditVo> list) {
        for (AuditVo audit:list
             ) {
            IbsAnchorAddress ibsAnchorAddress = addressMapper.selectById(audit.getId());
            ibsAnchorAddress.setAddressRemark(audit.getAddressRemark());
            ibsAnchorAddress.setAddressStatus(2);
            ibsAnchorAddress.setUpdateTime(new Date());
            addressMapper.updateById(ibsAnchorAddress);
        }
        return AjaxResult.success("所选地址已忽略");
    }

    public AjaxResult refresh(String userid,String custType){
        userid = SecurityUtils.getUsername();
        HashMap<String, Object> paramMap = new HashMap<>();
        AnchorRefreshDTO ard = new AnchorRefreshDTO();
        Long newCust = 0L;
        Long changeAdd = 0L;
        paramMap.put("userid",userid);
        paramMap.put("custType",custType);
        //新增企业addressid为0
        if(SecurityUtils.userRole().equals("branch")){
            paramMap.put("isHead",false);
            newCust= mapper.selectCountCust(paramMap);
            changeAdd= mapper.selectCountCustAddress(paramMap);
        }else{
            paramMap.put("isHead",true);
            newCust= mapper.selectCountCust(paramMap);
            changeAdd= mapper.selectCountCustAddress(paramMap);
        }
        //查询地址有变动的锚点
        List<String> anchorList = mapper.selectChangeAnchor(paramMap);
        ard.setNewAnchorNum(newCust.toString());
        ard.setChangeAnchorNum(changeAdd.toString());
        ard.setAuditAnchorNum(anchorList.size()+"");
        return AjaxResult.success(ard);
    }

    public AjaxResult selectAddress(long id){
        List<IbsAnchorAddress> ibsAnchorAddresses = addressMapper.selectList(new LambdaQueryWrapper<IbsAnchorAddress>().gt(IbsAnchorAddress::getId,id));
        System.out.println(ibsAnchorAddresses.size());
        for (IbsAnchorAddress iaa:ibsAnchorAddresses
             ) {
            try {
                AddressResultVO addressResultVO = addressAnalyseService.addressStandardize(iaa.getAddress());
                iaa.setAddressNow(iaa.getAddress());
                System.out.println(addressResultVO);
                if (addressResultVO.getStatus() == 0) {
                    iaa.setProvinceNow(addressResultVO.getProvince());
                    iaa.setCityNow(addressResultVO.getCity());
                    iaa.setCountyNow(addressResultVO.getCounty());
                    iaa.setStreetNow(addressResultVO.getTown());
                    iaa.setCommunityNow(addressResultVO.getVillage());
                    iaa.setProvince(addressResultVO.getProvince());
                    iaa.setCity(addressResultVO.getCity());
                    iaa.setCounty(addressResultVO.getCounty());
                    iaa.setStreet(addressResultVO.getTown());
                    iaa.setCommunity(addressResultVO.getVillage());
                    iaa.setLongitude(addressResultVO.getLng() + "");
                    iaa.setLatitude(addressResultVO.getLat() + "");
                    iaa.setRegionCode(addressResultVO.getCode() + "");
                }
                //将新地址设置为审核通过状态
                iaa.setAddressStatus(1);
                addressMapper.updateById(iaa);
            }catch (Exception e){
                continue;
            }
        }
        return AjaxResult.success();
    }

    @Override
    public String getCust(long id) {
        IbsAnchor ia = mapper.selectById(id);
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("legal_id",ia.getLegalId());
        switch (ia.getCustType()) {
            case "2":
                return mapper.selectBusinessCust(paramMap);
            case "1":
                return mapper.selectMerchantCust(paramMap);
            case "0":
                return mapper.selectRetailCust(paramMap);
        }
        return null;
        }

    public int insertAddress(String legalId,String addressName,String address){
        IbsAnchorAddress ibsAnchorAddress1 = addressMapper.selectOne(new LambdaQueryWrapper<IbsAnchorAddress>()
                .eq(IbsAnchorAddress::getAnchorId, legalId)
                .eq(IbsAnchorAddress::getAddressName, addressName)
                .eq(IbsAnchorAddress::getSource,"手工导入")
                .eq(IbsAnchorAddress::getDeleteStatus, 0)
                .eq(IbsAnchorAddress::getAddressStatus, 1)
                .eq(IbsAnchorAddress::getUpdateStatus,1));
        IbsAnchorAddress iaa = new IbsAnchorAddress();
        iaa.setAddress("");
        iaa.setType("新成立");
        if (ibsAnchorAddress1!=null){
            //存在则将原信息添加进去作为原地址
            BeanUtils.copyProperties(ibsAnchorAddress1,iaa);
            iaa.setType("地址变化");
        }
        //无论是否存在也将数据添加进去作为现地址
        iaa.setAddressName(addressName);
        iaa.setId(0L);
        iaa.setAddressNow(address);
        //解析地址分级
        AddressResultVO addressResultVO = addressAnalyseService.addressStandardize(address);
        if(addressResultVO.getStatus()==0)
        {
            iaa.setProvinceNow(addressResultVO.getProvince());
            iaa.setCityNow(addressResultVO.getCity());
            iaa.setCountyNow(addressResultVO.getCounty());
            iaa.setStreetNow(addressResultVO.getTown());
            iaa.setCommunityNow(addressResultVO.getVillage());
            iaa.setRegionCode(addressResultVO.getCode()+"");
        }
        //待补充经纬度解析。经纬度解析在审核通过时补充
        //iaa.setLatitude(addressResultVO.getLat()+"");
        //iaa.setLongitude(addressResultVO.getLng()+"");
        iaa.setAnchorId(legalId);
        iaa.setAddressStatus(0);
        iaa.setDeleteStatus(0);
        iaa.setUpdateStatus(0);
        iaa.setUpdateBy(SecurityUtils.getUsername());
        iaa.setUpdateOrg(SecurityUtils.getDeptId()+"");
        return addressMapper.insert(iaa);
    }

    public int insert (NewAnchor nanchor){
        if(mapper.selectList(new LambdaQueryWrapper<IbsAnchor>().eq(IbsAnchor::getLegalId,nanchor.getLegalId())).size()>0){
            return 0;
        }
        IbsAnchor ibsAnchor = new IbsAnchor();
        ibsAnchor.setId(0L);
        ibsAnchor.setLegalId(nanchor.getLegalId());
        ibsAnchor.setSource("手工导入");
        ibsAnchor.setAnchorName(nanchor.getAnchorName());
        ibsAnchor.setAnchorRemark(nanchor.getAnchorRemark());
        ibsAnchor.setBelongBusiness(nanchor.getBelongBusiness());
        ibsAnchor.setUpdateOrg(SecurityUtils.getDeptId()+"");
        ibsAnchor.setCustType(nanchor.getCustType());
        if(nanchor.getCustType().equals("0")){
            ibsAnchor.setCustId("101"+nanchor.getLegalId());
            ibsAnchor.setCustIdType("二代身份证");
        }else{
            ibsAnchor.setCustId("202"+nanchor.getLegalId());
            ibsAnchor.setCustIdType("营业执照");
        }
        ibsAnchor.setStatus("未上图");
        ibsAnchor.setUpdateBy(SecurityUtils.getUsername());
        ibsAnchor.setDeleteStatus(0);
        return mapper.insert(ibsAnchor);
    }

    public int update(AnchorDetail anchorDetail){
        HashMap<String, Object> anchorParamMap = new HashMap<>();
        anchorParamMap.put("legalId",anchorDetail.getLegalId());
        anchorParamMap.put("anchorName",anchorDetail.getAnchorName());
        anchorParamMap.put("belongBusiness",anchorDetail.getBelongBusiness());
        return mapper.updateAnchorByCust(anchorParamMap);
    }

}
