package com.chinaweal.aiccs.aiccs.market.controller;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chinaweal.aiccs.aiccs.abnormal.entity.EBaseinfo;
import com.chinaweal.aiccs.aiccs.abnormal.entity.excel.NoClaimByFileExcel;
import com.chinaweal.aiccs.aiccs.abnormal.service.EBaseinfoService;
import com.chinaweal.aiccs.aiccs.abnormal.service.IGzaiccodeService;
import com.chinaweal.aiccs.aiccs.dict.entity.CascadeTreeNode;
import com.chinaweal.aiccs.aiccs.market.ai.AreaSliceClaimAI;
import com.chinaweal.aiccs.aiccs.market.entity.AreaSlice;
import com.chinaweal.aiccs.aiccs.market.entity.BizOwnerAssign;
import com.chinaweal.aiccs.aiccs.market.entity.DraftRevokeEntity;
import com.chinaweal.aiccs.aiccs.market.entity.dto.*;
import com.chinaweal.aiccs.aiccs.market.service.AreaSliceService;
import com.chinaweal.aiccs.aiccs.market.service.BizOwnerAssignService;
import com.chinaweal.aiccs.aiccs.market.service.IDraftRevokeEntityService;
import com.chinaweal.aiccs.common.base.controller.BaseController;
import com.chinaweal.aiccs.common.enums.SliceTypeEnums;
import com.chinaweal.aiccs.common.util.StringUtils;
import com.chinaweal.aicorg.model.AICUser;
import com.chinaweal.aicorg.services.OrgUMImpl;
import com.chinaweal.youfool.framework.springboot.exception.custom.BusinessException;
import com.chinaweal.youfool.framework.springboot.mybatis.plus.page.PageRequestDto;
import com.chinaweal.youfool.framework.springboot.rest.RestResult;
import com.chinaweal.youfool.framework.springboot.rest.ResultCode;
import com.chinaweal.youfool.framework.springboot.util.AssertUtils;
import com.chinaweal.youfool.framework.sso.util.SSOUtil;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanMap;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 业户管理业务记录表 前端控制器
 * </p>
 *
 * @author <a href="https://blog.lroyia.top">lroyia</a>
 * @since 2021-05-05
 */
@Api(tags = "业户管理相关接口")
@ApiSort(3)
@RestController
@RequestMapping("/bizOwnerAssign")
@Slf4j
public class BizOwnerAssignController extends BaseController {

    @Resource
    private BizOwnerAssignService bizOwnerAssignService;
    @Resource
    private AreaSliceService areaSliceService;
    @Resource
    private EBaseinfoService eBaseinfoService;
    @Resource
    private IDraftRevokeEntityService iDraftRevokeEntityService;
    @Resource
    private IGzaiccodeService iGzaiccodeService;
    @Resource
    private OrgUMImpl orgUM;
    @Autowired
    private AreaSliceClaimAI areaSliceClaimAI;

    @ApiOperation(value = "导出认领失败名单")
    @PostMapping("exportNoClaimExcel")
    public void exportNoClaimExcel(@RequestBody Map<String,Object> noClaimList, HttpServletRequest request, HttpServletResponse response) throws IOException {
        AICUser aicUser = getLoginUser(request);
        if(aicUser==null){
            throw new BusinessException("登录超时，请重新登录");
        }

        //JSONObject jsonObject = JSONObject.parseObject(noClaimList);

        Object list = noClaimList.get("noClaimList");
        List<NoClaimByFileExcel> excelJson = new LinkedList<>();
        NoClaimByFileExcel head = new NoClaimByFileExcel();
        head.setUniscid("统一码");
        head.setRegion("区片区");
        head.setSlice("所片区");
        head.setReason("原因");
        excelJson.add(head);
        if (list instanceof List<?>) {
            List<?> entList = (List<?>) list;
            for (Object o : entList) {
                NoClaimByFileExcel atom = new NoClaimByFileExcel();
                Map<String,String> map = (Map<String, String>) o;
                atom.setUniscid(map.get("uniscid"));
                atom.setRegion(map.get("region"));
                atom.setSlice(map.get("slice"));
                atom.setReason(map.get("reason"));
                excelJson.add(atom);
            }
        }

        ServletOutputStream outputStream=null;
        try {
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + new String("不可认领名单.xlsx".getBytes(), "UTF-8"));
            response.setContentType("application/msexcel;charset=UTF-8");
            outputStream = response.getOutputStream();
            ExcelWriter excelWriter = EasyExcel.write(outputStream).build();
            WriteSheet writeSheet1 = EasyExcel.writerSheet(0, "sheet1").build();

            excelWriter.write(excelJson, writeSheet1);
            excelWriter.finish();

        }catch (Exception e) {
            outputStream.close();
            e.printStackTrace();
        } finally {
            outputStream.close();
        }

    }

    @ApiOperation(value = "通过文件指派企业")
    @PostMapping(value = "/assignByFile")
    public RestResult<?> assignByFile(MultipartFile file, HttpServletRequest request) {
        AICUser aicUser = getLoginUser(request);
        if(aicUser==null){
            throw new BusinessException("登录超时，请重新登录");
        }

        Map<String, Object> resultMap = new HashMap<>();
        List<Map<String,String>> handleList = new ArrayList<>();
        try {
            List<Map<Integer, String>> list = EasyExcel.read(file.getInputStream()).sheet(0).doReadSync();
            for (Map<Integer, String> item : list) {
                String uniScId = StringUtils.trim(item.get(0));
                String region = StringUtils.trim(item.get(1));
                String slice = StringUtils.trim(item.get(2).split("所")[0]);
                if (StringUtils.isNotBlank(uniScId) && StringUtils.isNotBlank(slice) && StringUtils.isNotBlank(region)) {
                    Map<String,String> map = new HashMap<>();
                    map.put("uniscid", uniScId);
                    map.put("region", region);
                    map.put("slice", slice);
                    handleList.add(map);
                }else{
                    resultMap.put("erro","信息不全");
                    return RestResult.ok(resultMap);
                }
            }
            resultMap = areaSliceClaimAI.claimByFile(handleList, aicUser);
        } catch (IOException e) {
            log.error("批量查询有误", e);
            throw new BusinessException("请检查文件格式是否有误");
        }
        return RestResult.ok(resultMap);
    }

    @ApiOperation("导出片区的认领数据")
    @PostMapping("assignExcel")
    public void assignExcel(HttpServletRequest request, HttpServletResponse response,@RequestBody List<Map<String, String>> data) throws IOException{
        AssertUtils.isNotNull(data);
        AICUser aicUser = getLoginUser(request);
        if(aicUser==null){
            throw new BusinessException("登录超时，请重新登录");
        }

        List<AssignExcelDto> excelJson = new LinkedList<AssignExcelDto>();
        for( Map<String, String> atom : data){
            AssignExcelDto assignExcelDto = new AssignExcelDto();
            assignExcelDto.setOrgName(atom.get("orgName"));
            assignExcelDto.setAiClaimNum(atom.get("aiClaimNum"));
            assignExcelDto.setAssignNum(atom.get("assignNum"));
            assignExcelDto.setClaimNum(atom.get("claimNum"));
            assignExcelDto.setRemNum(atom.get("remNum"));
            excelJson.add(assignExcelDto);
        }

        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("认领情况统计", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

        ExcelWriter excelWriter = null;
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
            excelWriter = EasyExcel.write(bos, AssignExcelDto.class).inMemory(true).build();

            excelWriter.write(excelJson, EasyExcel.writerSheet("认领情况统计").registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).build());

            // 结束
            excelWriter.finish();

            response.getOutputStream().write(bos.toByteArray());

        } finally {
            // 结束
            if (excelWriter != null) excelWriter.finish();

        }
    }

    @ApiOperation("统计片区的认领数据")
    @PostMapping("countAssign")
    public RestResult<?> countAssign(HttpServletRequest request, @RequestBody PageRequestDto pageRequestDto){
        AICUser aicUser = getLoginUser(request);
        if(aicUser==null){
            throw new BusinessException("登录超时，请重新登录");
        }

        //获取当前账号的登记机关
        List<CascadeTreeNode> rootOrg = iGzaiccodeService.getNodeByOrg(aicUser.getRegionID());
        if(rootOrg.size() > 1 || rootOrg.size() == 0){
            throw new BusinessException("获取跟片区失败");
        }
        List<CascadeTreeNode> orgList = null;

        //获取当前账号的片区
        AreaSlice slice = null;
        if(!"440101".equals(aicUser.getRegionID())){
            slice = areaSliceService.getOne(new LambdaQueryWrapper<AreaSlice>()
                    .eq(AreaSlice::getOrgNumber, aicUser.getRegionID())
                    .eq(AreaSlice::getIsDeleted, "0")
                    .eq(AreaSlice::getState, "1")
                    .ne(AreaSlice::getSliceType, "2"));
            if(slice == null){
                throw new BusinessException("获取跟片区失败");
            }
        }

        //认领时间
        Map<String, Object> customParamMap = pageRequestDto.getCustomParamMap();
        if (!MapUtils.isEmpty(customParamMap) && StringUtils.isNotBlank(StringUtils.tranObject(customParamMap.get("searchDate")))) {
            Object searchDate = customParamMap.get("searchDate");
            if (searchDate instanceof List) {
                List<String> list = (List<String>) searchDate;
                if(list.size() > 1){
                    customParamMap.put("startDate", list.get(0));
                    customParamMap.put("endDate", list.get(1));
                }
            }
        }

        //获取该账号可以查看的各个片区的统计数据
        List<Map<String, String>> sliceMap = "440101".equals(aicUser.getRegionID()) ? bizOwnerAssignService.countAssign(null, null, customParamMap) :
            bizOwnerAssignService.countAssign(aicUser.getRegionID(), slice.getSliceId(), customParamMap);
        if(CollectionUtils.isNotEmpty(sliceMap)) {
            List<AreaSlice> sliceList = null;
            //区和市账号补充登记机关信息
            if (slice != null || "440101".equals(aicUser.getRegionID())) {
                //机关树
                orgList = iGzaiccodeService.getChildList(rootOrg.get(0).getId());
                orgList.add(rootOrg.get(0));

                //机关树和片区树对比补充信息
                for (CascadeTreeNode atom : orgList) {
                    Boolean flag = false;
                    for (Map<String, String> m : sliceMap) {
                        if (m.get("org_number").equals(atom.getValue())) {
                            m.put("orgName", atom.getLabel());
                            flag = true;
                            break;
                        }
                    }
                    if (!flag) {
                        Map<String, String> m = new HashMap<>();
                        m.put("org_number", atom.getValue());
                        m.put("orgName", atom.getLabel());
                        m.put("aiClaimNum", "0");
                        m.put("assignNum", "0");
                        m.put("claimNum", "0");
                        m.put("remNum", "0");
                        sliceMap.add(m);
                    }
                }
            }
            //所账号补充片区信息
            if (slice != null && "1".equals(slice.getSliceType())) {
                //片区树
                sliceList = areaSliceService.list(new LambdaQueryWrapper<AreaSlice>()
                        .eq(AreaSlice::getOrgNumber, aicUser.getRegionID())
                        .eq(AreaSlice::getIsDeleted, "0")
                        .eq(AreaSlice::getState, "1")
                        .eq(AreaSlice::getPSliceId, slice.getSliceId()));

                //片区树和片区树对比补充信息
                for (AreaSlice atom : sliceList) {
                    Boolean flag = false;
                    for (Map<String, String> m : sliceMap) {
                        if (m.get("slice_name").equals(atom.getSliceName())) {
                            m.put("orgName", atom.getSliceName());
                            flag = true;
                            break;
                        }
                    }
                    if (!flag) {
                        Map<String, String> m = new HashMap<>();
                        m.put("orgName", atom.getSliceName());
                        m.put("slice_name", atom.getSliceName());
                        m.put("aiClaimNum", "0");
                        m.put("assignNum", "0");
                        m.put("claimNum", "0");
                        m.put("remNum", "0");
                        sliceMap.add(m);
                    }
                }
            }
        }


        return RestResult.ok(sliceMap);
    }

    @ApiOperation("清理注册二处认领的数据")
    @PostMapping("clearTwoData")
    public RestResult<?> clearTwoData(){
        //清理注册二处认领的
        List<BizOwnerAssign> bizlist = bizOwnerAssignService.list(new LambdaQueryWrapper<BizOwnerAssign>()
                .eq(BizOwnerAssign::getSliceId,"001029901"));
        for(BizOwnerAssign b : bizlist){
            bizOwnerAssignService.removeById(b.getAssignId());
            eBaseinfoService.clearRegulatory(b.getPripid());
//            eBaseinfoService.updateById(new EBaseinfo()
//                    .setPripid(b.getPripid())
//                    .setAssignId(null)
//                    .setRegulatoryTemp(null)
//                    .setRegulatoryNameTemp(null)
//                    .setSuporg(null)
//                    .setSareacodeTemp(null)
//                    .setSareanameTemp(null));
        }
        return RestResult.ok();
    }

    @ApiOperation("清理个体户的数据")
    @PostMapping("clearIndivData")
    public RestResult<?> clearIndivData(){
        String lastSql = "limit 10000";
        List<EBaseinfo> records = eBaseinfoService.lambdaQuery().isNull(EBaseinfo::getSareacodeTemp).eq(EBaseinfo::getRegstate, "1")
                .orderByAsc(EBaseinfo::getPripid).last(lastSql).list();

        while (CollectionUtils.isNotEmpty(records)) {
            for (EBaseinfo each : records) {
                //查找登记机关非6位的个体户
                if(each.getRegorg().length() > 6 && "9910".equals(each.getEnttype())){
                    //处理没有被退还的业户管理业务记录
                    List<BizOwnerAssign> list = bizOwnerAssignService.list(new LambdaQueryWrapper<BizOwnerAssign>()
                            .eq(BizOwnerAssign::getPripid, each.getPripid())
                            .isNull(BizOwnerAssign::getRemDate));

                    if (CollectionUtils.isNotEmpty(list)) {
                        for (BizOwnerAssign dto : list) {
                            BizOwnerAssign bizOwner = dto;
                            bizOwnerAssignService.updateById(bizOwner.setRemDate(LocalDateTime.now())
                                    .setRemOperator("AreaSliceClaimAI")
                                    .setRemReason("登记机关非6位的个体户根据登记机关认领规则重新认领")
                                    .setRemType("1"));
                        }
                        //清空主体认领相关字段
                        eBaseinfoService.clearRegulatory(each.getPripid());
//                        eBaseinfoService.updateById(new EBaseinfo()
//                                .setPripid(each.getPripid())
//                                .setAssignId(null)
//                                .setRegulatoryTemp(null)
//                                .setRegulatoryNameTemp(null)
//                                .setSuporg(null)
//                                .setSareacodeTemp(null)
//                                .setSareanameTemp(null));
                    }

                }else if(StringUtils.isNotBlank(each.getSareacodeTemp())){//登记机关是其他区的市场主体数据重新认领
                    List<SliceAssignLogDto> list = bizOwnerAssignService.listBySliceInfo(null, each.getPripid());
                    if (CollectionUtils.isNotEmpty(list)) {
                        for (SliceAssignLogDto dto : list) {
                            //查找区片区的认领记录
                            if (dto.getRemDate() == null && SliceTypeEnums.REGION_PUBLIC.equals(dto.getSliceType())) {
                                //登记机关与片区码值不一致需要处理
                                if(!each.getRegorg().substring(0,6).equals(dto.getOrgNumber())){
                                    BizOwnerAssign bizOwner = dto;
                                    bizOwnerAssignService.updateById(bizOwner.setRemDate(LocalDateTime.now())
                                            .setRemOperator("AreaSliceClaimAI")
                                            .setRemReason("登记机关是其他区的市场主体数据重新认领")
                                            .setRemType("1"));
                                    //主体表的认领片区id是区局片区的话也需要处理
                                    if(dto.getSliceId().equals(each.getSareacodeTemp())){
                                        //清空主体认领相关字段
                                        eBaseinfoService.clearRegulatory(each.getPripid());
//                                        eBaseinfoService.updateById(new EBaseinfo()
//                                                .setPripid(each.getPripid())
//                                                .setAssignId(null)
//                                                .setRegulatoryTemp(null)
//                                                .setRegulatoryNameTemp(null)
//                                                .setSuporg(null)
//                                                .setSareacodeTemp(null)
//                                                .setSareanameTemp(null));
                                    }
                                }
                            }
                        }
                    }
                }
            }
            records = eBaseinfoService.lambdaQuery().isNull(EBaseinfo::getSareacodeTemp).eq(EBaseinfo::getRegstate, "1")
                    .gt(EBaseinfo::getPripid, records.get(records.size() - 1).getPripid())
                    .orderByAsc(EBaseinfo::getPripid).last(lastSql).list();
        }
        return RestResult.ok();
    }

    /**
     * 业户主体分页
     *
     * @param pageRequestDto 分页参数
     * @return 分页结果
     * @author lroyia
     * @since 2021年5月6日 00:02:12
     */
    @ApiOperation("业户主体分页")
    @PostMapping("entOwnerPage")
    public RestResult<?> entOwnerPage(@ApiParam("分页参数") @RequestBody PageRequestDto pageRequestDto, HttpServletRequest request) {
        AssertUtils.isNotNull(pageRequestDto);
        pageRequestDto.checkDefault(1, 10, null);
        AICUser loginUser = getLoginUser(request);
        Map<String, Object> paramMap = pageRequestDto.getParamMap();
        String regionID = loginUser.getRegionID();
            if (!regionID.equals("440101")&&regionID.length()==6&&paramMap.get("isAssign").equals(0)) {//区局用户认领市局公共片区的市场主体
                paramMap.put("orgNumber", "440101");
            }
            else if (regionID.length()==8&&paramMap.get("isAssign").equals(0)){//所级用户认领区公共片区市场主体
                paramMap.put("orgNumber", regionID.substring(0,6));
            } else {
                paramMap.put("orgNumber", regionID);
            }
        IPage<EBaseInfoAssignDto> eBaseInfoAssignDtoIPage = bizOwnerAssignService.ownerAssignPage(new Page<>(pageRequestDto.getCurPage(), pageRequestDto.getPageSize()), pageRequestDto.getParamMap());

        eBaseInfoAssignDtoIPage.getRecords().forEach(item -> {
            BizOwnerAssign bizOwnerAssign = bizOwnerAssignService.getLatestAssignLog(item.getPripid());

            if (bizOwnerAssign != null) {
                item.setAssignId(bizOwnerAssign.getAssignId());
                item.setAssignDate(bizOwnerAssign.getAssignDate());
            }

            // 注释虚假地址标记功能 2022-9-14市局郭处提出暂不使用该功能
//            DraftRevokeEntity draftRevokeEntity = iDraftRevokeEntityService.lambdaQuery().eq(DraftRevokeEntity::getPripid, item.getPripid()).eq(DraftRevokeEntity::getStatus, "1").one();
//            if (draftRevokeEntity != null) {
//                item.setIsDraftTab("1");
//            }
        });
        return RestResult.ok(eBaseInfoAssignDtoIPage);
    }

    /**
     * 业户认领操作接口 指派
     *
     * @param sliceId 片区id
     * @param pripid  主体pripid
     * @return 操作结果
     * @author lroyia
     * @since 2021年5月6日 00:11:59
     */
    @ApiOperation("业户认领操作接口")
    @PostMapping("assignOwner")
    public RestResult<?> assignOwner(@ApiParam("分区id") String sliceId, @ApiParam("主体pripid") String pripid) {
        AssertUtils.isNotBlank(sliceId, pripid);

        return bizOwnerAssignService.assignOwner(sliceId, pripid, "1");
    }

    /**
     * 业户认领批量操作接口 指派
     *
     * @param sliceId 片区id
     * @param pripids  主体数组pripids
     * @return 操作结果
     * @author fanshangzhi
     * @since 2022年10月8日
     */
    @ApiOperation("业户认领操作接口")
    @PostMapping("BatchAssignOwner")
    public RestResult<?> BatchAssignOwner(@ApiParam("分区id") String sliceId, @RequestParam List<Object> pripids) {
        AssertUtils.isNotBlank(sliceId);
        bizOwnerAssignService.BatchAssignOwner(sliceId,pripids,"1");
        return RestResult.ok();
    }

    /**
     * 业户认领批量操作接口
     *
     * @param orgCode 所属机关
     * @param pripid  主体pripid
     * @return 操作结果
     * @author fanshangzhi
     * @since 2022年10月12日
     */
    @ApiOperation("业户认领操作接口")
    @PostMapping("assignOwner1")
    public RestResult<?> assignOwner1(@ApiParam("所属机关") String orgCode, @ApiParam("主体pripid") String pripid) {
        AssertUtils.isNotBlank(orgCode, pripid);
        QueryWrapper<AreaSlice> wrapper = new QueryWrapper<>();
        if (orgCode.length()==8){
            wrapper.eq("org_number",orgCode)
                    .eq("slice_type",1);
        } else {
            wrapper.eq("org_number",orgCode)
                    .eq("slice_type",0);
        }
        AreaSlice areaSlice=areaSliceService.getOne(wrapper);
        return bizOwnerAssignService.assignOwner(areaSlice.getSliceId(), pripid, "2");
    }
    /**
     * 业户认领批量操作接口
     *
     * @param orgCode 所属机关
     * @param pripids  主体数组pripids
     * @return 操作结果
     * @author fanshangzhi
     * @since 2022年10月8日
     */
    @ApiOperation("业户认领操作接口")
    @PostMapping("BatchAssignOwner1")
    public RestResult<?> BatchAssignOwner1(@ApiParam("分区id") String orgCode, @RequestParam List<Object> pripids) {
        AssertUtils.isNotBlank(orgCode);
        QueryWrapper<AreaSlice> wrapper = new QueryWrapper<>();
        if (orgCode.length()==8){
            wrapper.eq("org_number",orgCode)
                    .eq("slice_type",1);
        } else {
            wrapper.eq("org_number",orgCode)
                    .eq("slice_type",0);
        }
        AreaSlice areaSlice=areaSliceService.getOne(wrapper);
        bizOwnerAssignService.BatchAssignOwner(areaSlice.getSliceId(), pripids, "2");
        return RestResult.ok();
    }

    /**
     * 业户退还操作接口
     *
     * @return 操作结果
     * @author lroyia
     * @since 2021年5月6日 00:11:59
     */
    @Transactional
    @ApiOperation("业户退还操作接口")
    @PostMapping("removeOwner")
    public RestResult<?> removeOwner(@RequestBody BizOwnerAssign params, HttpServletRequest request) {
        String assignId = params.getAssignId();
        String pripid = params.getPripid();
        String remReason = params.getRemReason();
        String phone = params.getPhone();
        AssertUtils.isNotBlank(assignId, pripid, remReason, phone);

        AreaSlice areaSlice = areaSliceService.getOne(new LambdaQueryWrapper<AreaSlice>().exists(
                String.format("select 1 from biz_owner_assign " +
                        "where biz_owner_assign.slice_id = area_slice.slice_id and assign_id = '%s'", assignId)
        ));

        if (areaSlice == null) {
            log.error("无法找到片区数据, assignId: {}", assignId);
            return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR, "无法找到片区数据");
        }

        LocalDateTime now = LocalDateTime.now();
        AICUser loginUser = getLoginUser(request);

        // 区局退还市局
        if (SliceTypeEnums.REGION_PUBLIC.getCode().equals(areaSlice.getSliceType())) {
            eBaseinfoService.clearRegulatory(pripid);

            bizOwnerAssignService.updateById(new BizOwnerAssign().setRemDate(now)
                    .setRemReason(remReason)
                    .setPhone(phone)
                    .setRemType("0")
                    .setRemOperator(loginUser.getPrimaryKey())
                    .setRemOperatorName(loginUser.getName())
                    .setUpdater(loginUser.getPrimaryKey())
                    .setUpdateTime(now)
                    .setAssignId(assignId));
        } else {

            // 找到上一级,所直接退还区局 2->0, 1->0
//            AreaSlice parentAreaSlice = areaSliceService.getOne(new LambdaQueryWrapper<AreaSlice>().exists(
//                    String.format("select 1 from biz_owner_assign " +
//                            "where biz_owner_assign.slice_id = area_slice.slice_id and rem_date is null and slice_type = '0' and pripid = '%s'", pripid)
//            ));
            List<AreaSlice> parentAreaSlicelist = areaSliceService.list(
                    new LambdaQueryWrapper<AreaSlice>()
                            .inSql(AreaSlice::getSliceId,
                                    String.format(
                                            "SELECT slice_id FROM biz_owner_assign " +
                                                    "WHERE rem_date IS NULL " +
                                                    "  AND slice_type = '0' " +
                                                    "  AND pripid = '%s' " +
                                                    "ORDER BY UPDATE_TIME DESC ",
                                            pripid
                                    )
                            )
            );

            AreaSlice parentAreaSlice = parentAreaSlicelist.get(0);
            if (parentAreaSlice == null) {
                log.error("无法找到父级片区数据, slice_id: {}", areaSlice.getSliceId());
                return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR, "无法找到父级片区数据");
            }

            eBaseinfoService.updateRegulatory(pripid, parentAreaSlice.getOrgNumber(), parentAreaSlice.getSliceId(), parentAreaSlice.getSliceName());

            // 操作认领
            List<BizOwnerAssign> bizOwnerAssignList = bizOwnerAssignService.list(new LambdaQueryWrapper<BizOwnerAssign>().exists(
                    String.format("select 1 from area_slice " +
                            "where biz_owner_assign.slice_id = area_slice.slice_id and slice_type != '0' and rem_date is null and pripid = '%s'", pripid)
            ));

            for (BizOwnerAssign bizOwnerAssign : bizOwnerAssignList) {
                bizOwnerAssignService.updateById(bizOwnerAssign.setRemDate(now)
                        .setRemReason(remReason)
                        .setPhone(phone)
                        .setRemType("0")
                        .setRemOperator(loginUser.getPrimaryKey())
                        .setRemOperatorName(loginUser.getName())
                        .setUpdater(loginUser.getPrimaryKey())
                        .setUpdateTime(now));
            }
        }

        // 主体表更新退认领id
        eBaseinfoService.lambdaUpdate().set(EBaseinfo::getAssignId, assignId).eq(EBaseinfo::getPripid, pripid).update();
        return OK;
    }

    @Transactional
    @ApiOperation("批量业户退还操作接口")
    @PostMapping("BatchRemoveOwner")
    public RestResult<?> BatchRemoveOwner(@RequestBody List<BizOwnerAssign> params, HttpServletRequest request) {

        for (BizOwnerAssign ent : params){
            String assignId = ent.getAssignId();
            String pripid = ent.getPripid();
            String remReason = ent.getRemReason();
            String phone = ent.getPhone();
            AssertUtils.isNotBlank(assignId, pripid, remReason, phone);

            AreaSlice areaSlice = areaSliceService.getOne(new LambdaQueryWrapper<AreaSlice>().exists(
                    String.format("select 1 from biz_owner_assign " +
                            "where biz_owner_assign.slice_id = area_slice.slice_id and assign_id = '%s'", assignId)
            ));

            if (areaSlice == null) {
                log.error("无法找到片区数据, assignId: {}", assignId);
                return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR, "无法找到片区数据");
            }

            LocalDateTime now = LocalDateTime.now();
            AICUser loginUser = getLoginUser(request);

            // 区局退还市局
            if (SliceTypeEnums.REGION_PUBLIC.getCode().equals(areaSlice.getSliceType())) {
                eBaseinfoService.clearRegulatory(pripid);

                bizOwnerAssignService.updateById(new BizOwnerAssign().setRemDate(now)
                        .setRemReason(remReason)
                        .setPhone(phone)
                        .setRemType("0")
                        .setRemOperator(loginUser.getPrimaryKey())
                        .setRemOperatorName(loginUser.getName())
                        .setUpdater(loginUser.getPrimaryKey())
                        .setUpdateTime(now)
                        .setAssignId(assignId));
            } else {

                // 找到上一级,所直接退还区局 2->0, 1->0
                AreaSlice parentAreaSlice = areaSliceService.getOne(new LambdaQueryWrapper<AreaSlice>().exists(
                        String.format("select 1 from biz_owner_assign " +
                                "where biz_owner_assign.slice_id = area_slice.slice_id and slice_type = '0' and rem_type is null and pripid = '%s'", pripid)
                ));

                if (parentAreaSlice == null) {
                    log.error("无法找到父级片区数据, slice_id: {}", areaSlice.getSliceId());
                    return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR, "无法找到父级片区数据");
                }

                eBaseinfoService.updateRegulatory(pripid, parentAreaSlice.getOrgNumber(), parentAreaSlice.getSliceId(), parentAreaSlice.getSliceName());

                // 操作认领
                List<BizOwnerAssign> bizOwnerAssignList = bizOwnerAssignService.list(new LambdaQueryWrapper<BizOwnerAssign>().exists(
                        String.format("select 1 from area_slice " +
                                "where biz_owner_assign.slice_id = area_slice.slice_id and slice_type != '0' and rem_date is null and pripid = '%s'", pripid)
                ));

                for (BizOwnerAssign bizOwnerAssign : bizOwnerAssignList) {
                    bizOwnerAssignService.updateById(bizOwnerAssign.setRemDate(now)
                            .setRemReason(remReason)
                            .setPhone(phone)
                            .setRemType("0")
                            .setRemOperator(loginUser.getPrimaryKey())
                            .setRemOperatorName(loginUser.getName())
                            .setUpdater(loginUser.getPrimaryKey())
                            .setUpdateTime(now));
                }
            }
            // 主体表更新退认领id
            eBaseinfoService.lambdaUpdate().set(EBaseinfo::getAssignId, assignId).eq(EBaseinfo::getPripid, pripid).update();
        }
        return OK;
    }

    /**
     * 调整片区 (监管所使用)
     *
     * @param assignId 主体pripid
     * @param sliceId  片区id
     * @param request  请求信息
     * @return 调整结果
     * @author lroyia
     * @since 2021年5月6日 16:11:08
     */
    @Transactional
    @ApiOperation("调整片区")
    @PostMapping("changeOwner")
    public RestResult<?> changeOwner(@ApiParam("业户认领记录id") String assignId, @ApiParam("片区id") String sliceId, HttpServletRequest request) {
        AssertUtils.isNotBlank(assignId, sliceId);

        // 操作认领
        AICUser loginUser = getLoginUser(request);
        LocalDateTime now = LocalDateTime.now();
        BizOwnerAssign byId = bizOwnerAssignService.getById(assignId);

        AreaSlice currentAreaSlice = areaSliceService.getById(byId.getSliceId());
        if (currentAreaSlice.getSliceId().equals(sliceId)) return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR);

        AreaSlice areaSlice = areaSliceService.getById(sliceId);

        // 类型调整判断
        boolean is2to2 = SliceTypeEnums.SPEC_SLICE.getCode().equals(currentAreaSlice.getSliceType()) && SliceTypeEnums.SPEC_SLICE.getCode().equals(areaSlice.getSliceType());
        boolean is2to1 = SliceTypeEnums.SPEC_SLICE.getCode().equals(currentAreaSlice.getSliceType()) && SliceTypeEnums.STATION_PUBLIC.getCode().equals(areaSlice.getSliceType());
        boolean is1to2 = SliceTypeEnums.STATION_PUBLIC.getCode().equals(currentAreaSlice.getSliceType()) && SliceTypeEnums.SPEC_SLICE.getCode().equals(areaSlice.getSliceType());

        if (is2to2 || is2to1) {
            bizOwnerAssignService.updateById(new BizOwnerAssign()
                    .setRemDate(now)
                    .setRemReason("业户调整")
                    .setRemType("1")
                    .setRemOperator(loginUser.getPrimaryKey())
                    .setRemOperatorName(loginUser.getName())
                    .setAssignId(assignId));
        }

        if (is2to2 || is1to2) {
            bizOwnerAssignService.save(new BizOwnerAssign()
                    .setSliceId(sliceId)
                    .setAssignDate(now)
                    .setAssignOperator(loginUser.getPrimaryKey())
                    .setPripid(byId.getPripid())
                    .setUpdater(loginUser.getPrimaryKey())
                    .setUpdateTime(now));
        }

        eBaseinfoService.updateRegulatory(byId.getPripid(), areaSlice.getOrgNumber(), areaSlice.getSliceId(), areaSlice.getSliceName());

        return OK;
    }

    @Transactional
    @ApiOperation("批量调整片区")
    @PostMapping("changeOwnerBatch")
    public RestResult<?> changeOwnerBatch(@RequestBody Map<String, Object> params, HttpServletRequest request) {
        Object ent = params.get("ent");
        String sliceId = params.get("sliceId").toString();
        List<Map<String,String>> entlist = null;
        if (ent instanceof List) {
            entlist = (List<Map<String,String>>) ent;
        }
        if(entlist.size() > 0) {
            for(Map<String,String> b : entlist) {
                String assignId = b.get("assignId");
                // 操作认领
                AICUser loginUser = getLoginUser(request);
                LocalDateTime now = LocalDateTime.now();
                BizOwnerAssign byId = bizOwnerAssignService.getById(assignId);

                AreaSlice currentAreaSlice = areaSliceService.getById(byId.getSliceId());
                if (currentAreaSlice.getSliceId().equals(sliceId))
                    return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR);

                AreaSlice areaSlice = areaSliceService.getById(sliceId);

                // 类型调整判断
                boolean is2to2 = SliceTypeEnums.SPEC_SLICE.getCode().equals(currentAreaSlice.getSliceType()) && SliceTypeEnums.SPEC_SLICE.getCode().equals(areaSlice.getSliceType());
                boolean is2to1 = SliceTypeEnums.SPEC_SLICE.getCode().equals(currentAreaSlice.getSliceType()) && SliceTypeEnums.STATION_PUBLIC.getCode().equals(areaSlice.getSliceType());
                boolean is1to2 = SliceTypeEnums.STATION_PUBLIC.getCode().equals(currentAreaSlice.getSliceType()) && SliceTypeEnums.SPEC_SLICE.getCode().equals(areaSlice.getSliceType());

                if (is2to2 || is2to1) {
                    bizOwnerAssignService.updateById(new BizOwnerAssign()
                            .setRemDate(now)
                            .setRemReason("业户调整")
                            .setRemType("1")
                            .setRemOperator(loginUser.getPrimaryKey())
                            .setRemOperatorName(loginUser.getName())
                            .setAssignId(assignId));
                }

                if (is2to2 || is1to2) {
                    bizOwnerAssignService.save(new BizOwnerAssign()
                            .setSliceId(sliceId)
                            .setAssignDate(now)
                            .setAssignOperator(loginUser.getPrimaryKey())
                            .setPripid(byId.getPripid())
                            .setUpdater(loginUser.getPrimaryKey())
                            .setUpdateTime(now));
                }

                eBaseinfoService.updateRegulatory(byId.getPripid(), areaSlice.getOrgNumber(), areaSlice.getSliceId(), areaSlice.getSliceName());
            }
        }
        return OK;
    }

    /**
     * 获取可改变的片区
     *
     * @param sliceId  当前片区id
     * @return 查询结果
     * @author lroyia
     * @since 2021年12月14日 15:16:11
     */
    @ApiOperation("获取可改变的片区")
    @GetMapping("getChangeableSlice")
    public RestResult<?> getChangeableSlice(@ApiParam("当前片区id") String sliceId) {
        if (StringUtils.isBlank(sliceId)) {
            return RestResult.error(ResultCode.PARAM_IS_BLANK);
        }

        AICUser aicUser = SSOUtil.getUser();
        AreaSlice byId = areaSliceService.getById(sliceId);

        if (SliceTypeEnums.REGION_PUBLIC.getCode().equals(byId.getSliceType())) {
            return RestResult.error(ResultCode.BUSINESS_LOGIC_ERROR);
        }

        return RestResult.ok(areaSliceService.list(new LambdaQueryWrapper<AreaSlice>()
                .eq(AreaSlice::getOrgNumber, aicUser.getRegionID())
                .eq(AreaSlice::getState, "1")
                .orderByAsc(AreaSlice::getSliceId)));
    }

    /**
     * 获取主体认领记录
     *
     * @param pripid 主体id
     * @return 认领记录
     * @author lroyia
     * @since 2021年12月29日 10:31:45
     */
    @GetMapping("record/{pripid}")
    public RestResult<List<AssignLogDto>> getAssignRecord(@PathVariable String pripid) {
        return RestResult.ok(bizOwnerAssignService.listAssignLog(pripid));
    }


    /**
     * 获取主体认领记录
     *
     * @param assignId 认领id
     * @return 认领记录
     * @author yangmc
     * @since 2022年4月2日 10:18
     */
    @GetMapping("/info")
    public RestResult<RemoveInfoDto> info(@RequestParam String assignId) {
        AssertUtils.isNotBlank(assignId);
        BizOwnerAssign bizOwnerAssign=bizOwnerAssignService.getById(assignId);
        String RemOperator=bizOwnerAssign.getRemOperator();
        AICUser aicUser= orgUM.findUserByPrimaryKey(RemOperator);
        System.out.println("aicuser"+aicUser);
        RemoveInfoDto removeInfoDto = new  RemoveInfoDto();
        removeInfoDto.setBizOwnerAssign(bizOwnerAssign);
        removeInfoDto.setRemoveOrgName(aicUser.getOrgName());
        return RestResult.ok(removeInfoDto);
    }

    /**
     * 导出业户主体数据
     *
     * @param pageRequestDto 请求参数
     * @return excel文件
     * @author ymc
     * @since 2022年5月23日 16:14
     */
    @ApiOperation("导出业户主体数据")
    @PostMapping("exportEntOwner")
    public void exportEntOwner(@ApiParam("请求参数") @RequestBody PageRequestDto pageRequestDto, HttpServletRequest request, HttpServletResponse response) throws IOException {
        AssertUtils.isNotNull(pageRequestDto);
        AICUser loginUser = getLoginUser(request);
        Map<String, Object> paramMap = pageRequestDto.getParamMap();
        String regionID = loginUser.getRegionID();
        paramMap.put("orgNumber", regionID);
        List<EBaseInfoAssignDto> eBaseInfoAssignDtoList = bizOwnerAssignService.ownerAssign(pageRequestDto.getParamMap());

        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("公共库管理主体名单", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

        ExcelWriter excelWriter = null;
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
            excelWriter = EasyExcel.write(bos, EBaseInfoAssignDto.class).inMemory(true).build();

            excelWriter.write(eBaseInfoAssignDtoList, EasyExcel.writerSheet("市场主体信息").registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).build());

            // 结束
            excelWriter.finish();

            response.getOutputStream().write(bos.toByteArray());

        } finally {
            // 结束
            if (excelWriter != null) excelWriter.finish();

        }
    }

    /**
     * 标记虚假地址主体
     *
     * @param pripid 主体id
     * @return
     * @author yangmc
     * @since 2022年5月31日 10:18
     */
    @GetMapping("/inDraftRevoke")
    public RestResult<?> inDraftRevoke(@RequestParam String pripid) {
        AssertUtils.isNotBlank(pripid);

        AICUser user = SSOUtil.getUser();
        EBaseinfo eBaseinfo = eBaseinfoService.getOneByPripid(pripid);
        iDraftRevokeEntityService.save(new DraftRevokeEntity().setPripid(pripid).setUscc(eBaseinfo.getUniscid()).setRegNo(eBaseinfo.getRegno())
                .setTabTime(LocalDateTime.now()).setStatus("1")
                .setIntoOrg(user.getRegionID()));
        return RestResult.ok();
    }

    /**
     * 移出标记虚假地址主体
     *
     * @param pripid 主体id
     * @return
     * @author yangmc
     * @since 2022年5月31日 10:18
     */
    @GetMapping("/removeDraftRevoke")
    public RestResult<?> removeDraftRevoke(@RequestParam String pripid) {
        AssertUtils.isNotBlank(pripid);

        DraftRevokeEntity draftRevokeEntity = iDraftRevokeEntityService.lambdaQuery().eq(DraftRevokeEntity::getPripid, pripid).eq(DraftRevokeEntity::getStatus, "1").one();
        iDraftRevokeEntityService.updateById(draftRevokeEntity.setStatus("0"));
        return RestResult.ok();
    }


}

