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

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.boot.module.tzs.api.dto.EquipmentCategoryDto;
import com.yeejoin.amos.boot.module.tzs.api.entity.CategoryOtherInfo;
import com.yeejoin.amos.boot.module.tzs.api.entity.EquipmentCategory;
import com.yeejoin.amos.boot.module.tzs.api.enums.EquipmentCategoryEnum;
import com.yeejoin.amos.boot.module.tzs.api.enums.EquipmentClassifityEnum;
import com.yeejoin.amos.boot.module.tzs.api.mapper.CategoryOtherInfoMapper;
import com.yeejoin.amos.boot.module.tzs.api.mapper.EquipmentCategoryMapper;
import com.yeejoin.amos.boot.module.tzs.api.service.IEquipmentCategoryService;
import com.yeejoin.amos.boot.module.tzs.biz.fegin.PrivilegeFeign;
import com.yeejoin.amos.boot.module.tzs.biz.utils.JsonUtils;
import com.yeejoin.amos.boot.module.tzs.flc.api.feign.IdxFeignService;
import com.yeejoin.amos.boot.module.tzs.flc.api.feign.PrivilegeFeginService;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.model.CompanyModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import java.util.*;

/**
 * 装备分类服务实现类
 *
 * @author system_generator
 * @date 2021-10-20
 */
@Service
public class EquipmentCategoryServiceImpl extends BaseService<EquipmentCategoryDto, EquipmentCategory, EquipmentCategoryMapper> implements IEquipmentCategoryService {

    @Autowired
    EquipmentCategoryMapper equipmentCategoryMapper;

    @Value("classpath:/json/equipCategory.json")
    private Resource equipCategory;

    @Value("classpath:/json/equipStatus.json")
    private Resource equipStatus;

    @Autowired
    PrivilegeFeign privilegeFeign;

    @Autowired
    CategoryOtherInfoMapper categoryOtherInfoMapper;

    @Autowired
    PrivilegeFeginService privilegeFeginService;
    @Autowired
    IdxFeignService idxFeignService;


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

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

    public List<EquipmentCategoryDto> selectClassify() {
        return equipmentCategoryMapper.selectClassify();
    }

    @Override
    public List<Map<String, Object>> equipTree(String type) {
        List<Map<String, Object>> menus = new ArrayList<>();
        Map<String, List<Map<String, Object>>> resourceJson = JsonUtils.getResourceJson(equipCategory);
        List<Map<String, Object>> mapList;
        if (ValidationUtil.isEmpty(type)) {
            mapList = resourceJson.get(EquipmentClassifityEnum.BDLS.getCode());
        } else {
            mapList = resourceJson.get(type);
        }
        for (Map map : mapList) {
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("instanceName", map.get("name"));
            resultMap.put("instanceId", map.get("code"));
            menus.add(resultMap);
        }
        return menus;
    }

    @Override
    public Page equipClaimOverview() {
        Page page = new Page<>();
        Map<String, List<Map<String, Object>>> resourceJson = JsonUtils.getResourceJson(equipCategory);
        List<Map<String, Object>> mapList = resourceJson.get(EquipmentClassifityEnum.BDLS.getCode());
        List<Map<String, Object>> list = new ArrayList<>();
        for (Map map : mapList) {
            Map<String, Object> resultMap = new HashMap<>();
            //todo sql待定，目前为假数据
//            Map<String, Object> map1 = equipmentCategoryMapper.getCategoryCount(map.get("code").toString());
            Map<String, Object> objectMap = new HashMap<>();
            objectMap.put("waitClaim", 985);
            objectMap.put("alreadyClaim", 18985);
            objectMap.put("refuseClaim", 985);
            List<Map<String, Object>> list1 = new ArrayList<>();
            Map<String, List<Map<String, Object>>> jsonMap = JsonUtils.getResourceJson(equipStatus);
            List<Map<String, Object>> equipStatusList = jsonMap.get(EquipmentClassifityEnum.SBRLZT.getCode());
            for (Map equipStatusMap : equipStatusList) {
                Map<String, Object> map1 = new HashMap<>();
                map1.put("name", equipStatusMap.get("value"));
                map1.put("value", objectMap.get(equipStatusMap.get("value")));
                list1.add(map1);
            }
            resultMap.put("name", map.get("name"));
            resultMap.put("image", map.get("image"));
            resultMap.put("waitClaim", 985);
            resultMap.put("alreadyClaim", 18985);
            resultMap.put("refuseClaim", 985);
            resultMap.put("sum", 20955);
            resultMap.put("value", list1);
            list.add(resultMap);
        }
        page.setCurrent(1);
        page.setTotal(list.size());
        page.setRecords(list);
        return page;
    }

    /**
     * 生成监管码和电梯96333识别码
     */
    @Override
    public int createSupervisorCode(Map<String, Object> map) {

        LinkedHashMap value = (LinkedHashMap) map.get("value");
        //获取对应城市、区县值
        LinkedHashMap o = (LinkedHashMap) value.get("1627903393253056514");
        String city = o.get("CITY").toString();
        String county = o.get("COUNTY").toString();
        //获取对应种类、类别值
        LinkedHashMap o1 = (LinkedHashMap) value.get("1630483430028369922");
        String equipCategory = o1.get("EQU_CATEGORY").toString();
        String equipList = o1.get("EQU_LIST").toString();
        //测试数据 暂时保留
//        String city = "610400";
//        String county = "610401";
//        String equipCategory = "3200";
//        String equipList = "3000";
        //生成码
        Map<String, String> codeMap = creatCode(city, county, equipCategory, equipList);
        //查询最后一条数据并进行修改
        CategoryOtherInfo otherInfo = categoryOtherInfoMapper.selectOne(new QueryWrapper<CategoryOtherInfo>().orderByDesc("REC_DATE").last("limit 1"));
        return categoryOtherInfoMapper.updateSupervisorCode(codeMap.get("supervisorCode"), codeMap.get("elevatorCode"), otherInfo.getSequenceNbr());
    }

    @Override
    public List<LinkedHashMap> creatTree() {
        FeignClientResult tree = privilegeFeign.tree();
        List<LinkedHashMap> result = (List<LinkedHashMap>) tree.getResult();
        List<LinkedHashMap> treeData = deleteTreeData(result);
        List<LinkedHashMap> resultTree = new ArrayList<>();
        resultTree.add(treeData.get(5));
        return resultTree;
    }

    private List<LinkedHashMap> deleteTreeData(List<LinkedHashMap> result) {
        Iterator it = result.iterator();
        while (it.hasNext()) {
            LinkedHashMap e = (LinkedHashMap)it.next();
            //删除使用单位
            if ("company".equals(e.get("level"))) {
                it.remove();
            }
            if (!ObjectUtils.isEmpty(e.get("children"))) {
                deleteTreeData((List<LinkedHashMap>) e.get("children"));
            }
        }
        return result;
    }

    /**
     * 具体生成监管码和电梯96333识别码逻辑
     */
    private Map<String, String> creatCode(String city, String county, String equipCategory, String equipList) {
        Map<String, String> resultMap = new HashMap<>();
        //生成监管码前缀
        Map<String, Object> divisionMap = equipmentCategoryMapper.getAdministrativeDivision(EquipmentCategoryEnum.XZQH.getCode(), county);
        String division = ObjectUtils.isEmpty(divisionMap) ? equipmentCategoryMapper.getAdministrativeDivision(EquipmentCategoryEnum.XZQH.getCode(), city).get("code").toString() : divisionMap.get("code").toString();
        StringBuilder supervisorCode = new StringBuilder();
        supervisorCode.append(division).append(equipCategory);
        //获取行政区划区县、市是否存在历史监管码
        CategoryOtherInfo supervisor = categoryOtherInfoMapper.selectSupervisorCode(supervisorCode.toString());
        //生成对应监管码
        if (!ObjectUtils.isEmpty(supervisor)) {
            if (supervisor.getSupervisoryCode() != null) {
                //获取补零位长度
                String supervisoryCode = supervisor.getSupervisoryCode().substring(4);
                long num = Long.valueOf(supervisoryCode) + 1;
                int numLength = String.valueOf(num).length();
                int a = 7 - numLength;
                StringBuilder zero = new StringBuilder();
                for (int i = 0; i < a; i++) {
                    zero.append(EquipmentCategoryEnum.BLW.getCode());
                }
                zero.append(num);
                supervisorCode.append(zero);
            } else {
                supervisorCode.append(EquipmentCategoryEnum.JGM.getCode());
            }
        } else {
            supervisorCode.append(EquipmentCategoryEnum.JGM.getCode());
        }

        StringBuilder elevatorCode = new StringBuilder();
        //判断是否是否需要生成96333电梯码
        if (EquipmentClassifityEnum.DT.getCode().equals(equipList)) {
            //生成生成96333电梯码前缀
            Map<String, Object> elevatorMap = equipmentCategoryMapper.getAdministrativeDivision(EquipmentCategoryEnum.XZQHDT.getCode(), county);
            String elevator = ObjectUtils.isEmpty(elevatorMap) ? equipmentCategoryMapper.getAdministrativeDivision(EquipmentCategoryEnum.XZQHDT.getCode(), city).get("code").toString() : elevatorMap.get("code").toString();
            elevatorCode.append(elevator);
            //获取行政区划区县、市是否存在历史96333电梯码
            CategoryOtherInfo elevatorOtherInfo = categoryOtherInfoMapper.selectElevatorCode(elevatorCode.toString());
            //生成对应96333电梯码
            if (!ObjectUtils.isEmpty(elevatorOtherInfo)) {
                if (elevatorOtherInfo.getCode() != null) {
                    //获取补零位长度
                    String elevatorCode1 = elevatorOtherInfo.getCode().substring(2);
                    long num = Long.valueOf(elevatorCode1) + 1;
                    int numLength = String.valueOf(num).length();
                    int a = 5 - numLength;
                    StringBuilder zero = new StringBuilder();
                    for (int i = 0; i < a; i++) {
                        zero.append(EquipmentCategoryEnum.BLW.getCode());
                    }
                    zero.append(num);
                    elevatorCode.append(zero);
                } else {
                    elevatorCode.append(EquipmentCategoryEnum.CSM.getCode());
                }
            } else {
                elevatorCode.append(EquipmentCategoryEnum.CSM.getCode());
            }
        }
        resultMap.put("supervisorCode", ObjectUtils.isEmpty(supervisorCode.toString()) ? null : supervisorCode.toString());
        resultMap.put("elevatorCode", ObjectUtils.isEmpty(elevatorCode.toString()) ? null : elevatorCode.toString());
        return resultMap;
    }



    /**
     * 获取当前登录人单位类型
     *
     *
     * @return
     */

    public JSONObject getCompanyType() {
        ResponseModel<AgencyUserModel> me = privilegeFeginService.getMe();
        CompanyModel companyModel = (me.getResult().getCompanys()).get(0);
        JSONObject object = new JSONObject();
        object.put("leve", companyModel.getLevel());
        object.put("companyCode", companyModel.getCompanyCode());
        return object;
    }


    /**
     * levlel=company,是企业,如果不是都是监管单位,
     *      * 在接口中查询当前登录人所属单位是监管单位还是企业。
     *      * 如果为监管单位添加监管机构查询参数（ORG_BRANCH_CODE）；
     *      * 如果为企业添加使用单位查询参数(USE_UNIT_CREDIT_CODE)
     */
    private static final String LEVEL = "company";

    public ResponseModel<Page<Map<String,Object>>> getTable(Map<String,Object> map) {
        ResponseModel<Page<Map<String,Object>>> model = new ResponseModel<>();
        JSONObject object = getCompanyType();
        String leve = object.getString("leve");
        String code = object.getString("companyCode");
        if (!ValidationUtil.isEmpty(leve)) {
            if (LEVEL.equals(leve)) {
                //企业
                map.put("USE_UNIT_CREDIT_CODE", code);
                model = idxFeignService.getPage(map);
            } else {
                //监管单位
                map.put("ORG_BRANCH_CODE", code);
                model = idxFeignService.getPage(map);
            }
        }
        return model;
    }

}