package com.chinaweal.aiccs.aiccs.abnormal.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chinaweal.aiccs.aicbizqy.entity.datamove.EBaseInfo;
import com.chinaweal.aiccs.aicbizqy.mapper.datamove.EBaseInfoDataMoveMapper;
import com.chinaweal.aiccs.aiccs.abnormal.entity.vo.FileUploadRecordVO;
import com.chinaweal.aiccs.aiccs.abnormal.mapper.FileUploadRecordMapper;
import com.chinaweal.aiccs.aiccs.abnormal.service.impl.ManualMoveInService;
import com.chinaweal.aiccs.aiccs.abnormal.service.impl.ManualMoveOutService;
import com.chinaweal.aiccs.crgs.entity.EMoveIn;
import com.chinaweal.aiccs.crgs.entity.EMoveOut;
import com.chinaweal.aiccs.crgs.mapper.EMoveInMapper;
import com.chinaweal.aiccs.crgs.mapper.EMoveOutMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;



/**
 * 手动数据迁出接口Controller
 */
@RestController
@RequestMapping("/manual/move-out")
@Slf4j
@Api(tags = "手动数据迁出接口") // Swagger注解，可选
public class ManualMoveOutController {

    @Autowired
    private ManualMoveOutService manualMoveOutService;

    @Autowired
    private ManualMoveInService manualMoveInService;


    @Autowired
    private FileUploadRecordMapper fileUploadRecordMapper;

    @Autowired
    private EMoveOutMapper eMoveOutMapper;

    @Autowired
    private EMoveInMapper eMoveInMapper;

    @Autowired
    private EBaseInfoDataMoveMapper eBaseInfoMapper;

    @Autowired
    private RestTemplate restTemplate;

    @Value("${forest.variables.fileUpload.appform}")
    private String appform;

    @Value("${forest.variables.fileUpload.testDownloadUrl:}")
    private String testDownloadUrl;

    @Value("${forest.variables.fileUpload.prodDownloadUrl:}")
    private String prodDownloadUrl;

    /**
     * 单个企业手动迁出（按PRIPID）
     */
    @PostMapping("/single")
    @ApiOperation("单个企业手动迁出")
    public ResponseEntity<?> singleMoveOut(
            @ApiParam(value = "企业主体身份代码（PRIPID）", required = true)
            @RequestParam String pripid) {
        try {
            String result = manualMoveOutService.manualMoveOutByPripid(pripid);
            return ResponseEntity.ok(new HashMap<String, Object>() {{
                put("code", 200);
                put("message", result);
            }});
        } catch (Exception e) {
            log.error("单个企业手动迁出失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new HashMap<String, Object>() {{
                        put("code", 500);
                        put("message", "单个企业手动迁出失败：" + e.getMessage());
                    }});
        }
    }

    /**
     * 批量企业手动迁出（按PRIPID列表）
     */
//    @PostMapping("/batch")
//    @ApiOperation("批量企业手动迁出")
//    public ResponseEntity<?> batchMoveOut(
//            @ApiParam(value = "企业主体身份代码（PRIPID）列表", required = true)
//            @RequestBody List<String> pripidList) {
//        try {
//            Map<String, Object> result = manualMoveOutService.batchManualMoveOut(pripidList);
//            return ResponseEntity.ok(new HashMap<String, Object>() {{
//                put("code", 200);
//                put("message", result);
//            }});
//        } catch (Exception e) {
//            log.error("批量企业手动迁出失败", e);
//            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
//                    .body(new HashMap<String, Object>() {{
//                        put("code", 500);
//                        put("message", "批量处理失败：" + e.getMessage());
//                    }});
//        }
//    }

    /**
     * 查询文件上传记录列表（带省份信息）
     * 可以根据统一社会信用代码和企业名称进行模糊查询
     */
    @GetMapping("/file-upload-records")
    @ApiOperation("查询文件上传记录列表")
    public ResponseEntity<?> getFileUploadRecords(
            @ApiParam(value = "统一社会信用代码（模糊查询）", required = false)
            @RequestParam(required = false) String uniscid,
            @ApiParam(value = "企业名称（模糊查询）", required = false)
            @RequestParam(required = false) String entname) {
        try {
            List<FileUploadRecordVO> records = fileUploadRecordMapper.selectFileUploadRecordsWithProvince(uniscid, entname);
            for (FileUploadRecordVO record : records) {
                if ("1".equals(record.getMigrationType().toString())){
                    record.setPrOut("内蒙古自治区");
                    String prIn = getProvinceNameByCode(record.getPrIn().substring(0, 2) + "0000");
                    record.setPrIn(prIn);
                }else {
                    record.setPrIn("内蒙古自治区");
                    String prOut = getProvinceNameByCode(record.getPrOut().substring(0, 2) + "0000");
                    record.setPrOut(prOut);

                }
            }
            return ResponseEntity.ok(new HashMap<String, Object>() {{
                put("code", 0);
                put("message", "查询成功");
                put("data", records);
            }});
        } catch (Exception e) {
            log.error("查询文件上传记录失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new HashMap<String, Object>() {{
                        put("code", 500);
                        put("message", "查询失败：" + e.getMessage());
                    }});
        }
    }

    /**
     * 下载迁移数据对账接口
     * @param type 迁出/迁入类型（1=迁出，2=迁入）
     * @param moveid 迁出或迁入记录ID
     * @return 对账数据
     */
    @PostMapping("/download-data-record")
    @ApiOperation("下载迁移数据对账")
    public ResponseEntity<?> downloadDataRecord(
            @ApiParam(value = "迁出/迁入类型（1=迁出，2=迁入）", required = true)
            @RequestParam Integer type,
            @ApiParam(value = "迁出/迁入记录ID", required = true)
            @RequestParam String moveid) {
        try {
            log.info("开始执行下载迁移数据对账接口，type={}, moveid={}", type, moveid);

            // 验证参数
            if (type == null || (type != 1 && type != 2)) {
                return ResponseEntity.badRequest()
                        .body(new HashMap<String, Object>() {{
                            put("code", 400);
                            put("message", "参数错误：type必须为1（迁出）或2（迁入）");
                        }});
            }

            if (StrUtil.isBlank(moveid)) {
                return ResponseEntity.badRequest()
                        .body(new HashMap<String, Object>() {{
                            put("code", 400);
                            put("message", "参数错误：moveid不能为空");
                        }});
            }

            // 查询迁出或迁入记录
            String pripid = null;
            String moveInProvince = null;
            String moveOutProvince = null;

            if (type == 1) {
                // 迁出：查询E_MOVE_OUT表，moveid对应MOUT_ID
                log.info("查询迁出记录，MOUT_ID={}", moveid);
                EMoveOut eMoveOut = eMoveOutMapper.selectById(moveid);
                if (eMoveOut == null) {
                    return ResponseEntity.status(HttpStatus.NOT_FOUND)
                            .body(new HashMap<String, Object>() {{
                                put("code", 404);
                                put("message", "未找到迁出记录，MOUT_ID=" + moveid);
                            }});
                }
                pripid = eMoveOut.getPripid();
                moveOutProvince =eMoveOut.getMinareregorg().substring(0, 2) + "0000";
//                moveInProvince = eMoveOut.getMinareregorg().substring(0, 2) + "0000"; // 迁入地登记机关
                log.info("迁出记录查询成功，PRIPID={}, moveOutProvince={}, moveInProvince={}",
                    pripid, moveOutProvince, moveInProvince);
            } else {
                // 迁入：查询E_MOVE_IN表，moveid对应MIN_ID
                log.info("查询迁入记录，MIN_ID={}", moveid);
                EMoveIn eMoveIn = eMoveInMapper.selectById(moveid);
                if (eMoveIn == null) {
                    return ResponseEntity.status(HttpStatus.NOT_FOUND)
                            .body(new HashMap<String, Object>() {{
                                put("code", 404);
                                put("message", "未找到迁入记录，MIN_ID=" + moveid);
                            }});
                }
                pripid = eMoveIn.getPripid();
//                moveInProvince = "440000";  // 固定值
                moveOutProvince = eMoveIn.getMoutareregorg().substring(0, 2) + "0000";;  // 迁出地登记机关
                log.info("迁入记录查询成功，PRIPID={}, moveInProvince={}, moveOutProvince={}",
                    pripid, moveInProvince, moveOutProvince);
            }

            // 查询企业基本信息
            log.info("查询企业基本信息，PRIPID={}", pripid);
            EBaseInfo eBaseInfo = eBaseInfoMapper.selectById(pripid);
            if (eBaseInfo == null) {
                String errorMsg = "未找到企业基本信息，PRIPID=" + pripid;
                log.error(errorMsg);
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body(new HashMap<String, Object>() {{
                            put("code", 404);
                            put("message", errorMsg);
                        }});
            }
            String uniscid = eBaseInfo.getUniscid();
            String entname = eBaseInfo.getEntname();
            log.info("企业基本信息查询成功，UNISCID={}, ENTNAME={}", uniscid, entname);

            // 构建请求参数
            Map<String, Object> requestParam = new HashMap<>();
            requestParam.put("appform", appform);
            requestParam.put("uniscid", uniscid);
            requestParam.put("moveInProvince", "440000");
            requestParam.put("moveOutProvince", moveOutProvince);
            String pinyin = getPinyin(moveOutProvince);
            requestParam.put("province", pinyin); // 固定值为"shandong"
            requestParam.put("entname", entname);

            log.info("调用第三方对账接口，请求参数：{}", new JSONObject(requestParam).toString());

            // 选择接口地址
            String recordUrl = isProductionEnvironment() ?
                "http://172.28.20.169/prod/moveservice/enterprise/downloadDataRecordInfo" :
                "http://172.28.20.169/test/moveservice/enterprise/downloadDataRecordInfo";
            log.info("使用接口地址：{}", recordUrl);
            log.info("当前环境：{}，是否为生产环境：{}", System.getProperty("spring.profiles.active"), isProductionEnvironment());

            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);

            // 创建HttpEntity
            HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestParam, headers);

            // 调用第三方接口
            String response = restTemplate.postForObject(recordUrl, requestEntity, String.class);
            log.info("第三方接口响应：{}", response);

            // 返回响应
            return ResponseEntity.ok(new HashMap<String, Object>() {{
                put("code", 0);
                put("message", "查询成功");
                put("data", response);
            }});

        } catch (Exception e) {
            log.error("下载迁移数据对账失败，type={}, moveid={}", type, moveid, e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new HashMap<String, Object>() {{
                        put("code", 500);
                        put("message", "下载迁移数据对账失败：" + e.getMessage());
                    }});
        }
    }

    /**
     * 判断当前是否为生产环境
     * @return true=生产环境（171或172），false=测试环境
     */
    private boolean isProductionEnvironment() {
        // 从配置文件或系统属性获取环境标识
        String env = System.getProperty("spring.profiles.active");
        if (env == null) {
            env = "dev";  // 默认为开发环境
        }

        // 只有 prod171 和 prod172 才是生产环境
        return "prod171".equals(env) || "prod172".equals(env);
    }

    /**
     * 单个企业手动迁出（按PRIPID）
     */
    @PostMapping("/singleMoveIn")
    @ApiOperation("单个企业手动迁入")
    public ResponseEntity<?> singleMoveIn(
            @ApiParam(value = "企业主体身份代码（PRIPID）", required = true)
            @RequestParam String pripid) {
        try {
            String result = manualMoveInService.manualMoveOutByPripid(pripid);
            return ResponseEntity.ok(new HashMap<String, Object>() {{
                put("code", 200);
                put("message", result);
            }});
        } catch (Exception e) {
            log.error("单个企业手动迁出失败", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new HashMap<String, Object>() {{
                        put("code", 500);
                        put("message", "单个企业手动迁入失败：" + e.getMessage());
                    }});
        }
    }

    /**
     * 通过行政区划代码获取拼音
     */
    public  String getPinyin(String areaCode) {
        switch(areaCode) {
            case "110000": return "beijing";
            case "120000": return "tianjin";
            case "130000": return "hebei";
            case "140000": return "shanxi";
            case "150000": return "neimenggu";
            case "210000": return "liaoning";
            case "220000": return "jilin";
            case "230000": return "heilongjiang";
            case "310000": return "shanghai";
            case "320000": return "jiangsu";
            case "330000": return "zhejiang";
            case "340000": return "anhui";
            case "350000": return "fujian";
            case "360000": return "jiangxi";
            case "370000": return "shandong";
            case "410000": return "henan";
            case "420000": return "hubei";
            case "430000": return "hunan";
            case "440000": return "guangdong";
            case "450000": return "guangxi";
            case "460000": return "hainan";
            case "500000": return "chongqing";
            case "510000": return "sichuan";
            case "520000": return "guizhou";
            case "530000": return "yunnan";
            case "540000": return "xizang";
            case "610000": return "shaxi";
            case "620000": return "gansu";
            case "630000": return "qinghai";
            case "640000": return "ningxia";
            case "650000": return "xinjiang";
            case "710000": return "taiwan";
            case "810000": return "xianggang";
            case "820000": return "aomen";
            default: return null;
        }
    }

    /**
     * 根据省份编码获取中文名称（简单版，无工具类）
     * @param provinceCode 省份编码（如"440000"）
     * @return 对应中文名称，编码无效/为空返回"未知省份"
     */
    public String getProvinceNameByCode(String provinceCode) {
        // 判空处理
        if (provinceCode == null || provinceCode.trim().isEmpty()) {
            return "未知省份";
        }
        // 去除空格，统一匹配
        String code = provinceCode.trim();

        // 编码-名称映射（switch-case 直接匹配）
        switch (code) {
            case "110000": return "北京市";
            case "120000": return "天津市";
            case "130000": return "河北省";
            case "140000": return "山西省";
            case "150000": return "内蒙古自治区";
            case "210000": return "辽宁省";
            case "220000": return "吉林省";
            case "230000": return "黑龙江省";
            case "310000": return "上海市";
            case "320000": return "江苏省";
            case "330000": return "浙江省";
            case "340000": return "安徽省";
            case "350000": return "福建省";
            case "360000": return "江西省";
            case "370000": return "山东省";
            case "410000": return "河南省";
            case "420000": return "湖北省";
            case "430000": return "湖南省";
            case "440000": return "广东省";
            case "450000": return "广西壮族自治区";
            case "460000": return "海南省";
            case "500000": return "重庆市";
            case "510000": return "四川省";
            case "520000": return "贵州省";
            case "530000": return "云南省";
            case "540000": return "西藏自治区";
            case "610000": return "陕西省";
            case "620000": return "甘肃省";
            case "630000": return "青海省";
            case "640000": return "宁夏回族自治区";
            case "650000": return "新疆维吾尔自治区";
            case "710000": return "台湾省";
            case "810000": return "香港特别行政区";
            case "820000": return "澳门特别行政区";
            default: return "未知省份"; // 编码不存在时的默认值
        }
    }
}
