package com.chinaweal.aiccs.aiccs.market.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chinaweal.aiccs.aiccs.market.entity.AreaDsm;
import com.chinaweal.aiccs.aiccs.market.entity.AreaSlice;
import com.chinaweal.aiccs.aiccs.market.mapper.AreaDsmMapper;
import com.chinaweal.aiccs.aiccs.market.service.AreaSliceService;
import com.chinaweal.aiccs.aiccs.market.service.IAreaDsmService;
import com.chinaweal.aiccs.aiccs.market.vo.AreaDsmVo;
import com.chinaweal.aiccs.common.base.controller.BaseController;
import com.chinaweal.aiccs.common.constant.Constant;
import com.chinaweal.aiccs.common.enums.SliceTypeEnums;
import com.chinaweal.aiccs.org.entity.OrgUnits;
import com.chinaweal.aiccs.org.service.TUsersService;
import com.chinaweal.aicorg.model.AICUser;
import com.chinaweal.aicorg.services.OrgUM;
import com.chinaweal.youfool.framework.springboot.mybatis.plus.BaseServiceImpl;
import com.chinaweal.youfool.framework.springboot.rest.RestResult;
import com.chinaweal.youfool.framework.springboot.rest.ResultCode;
import com.chinaweal.youfool.framework.sso.util.SSOUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author chinaweal
 * @since 2021-11-26
 */
@Service
public class AreaDsmServiceImpl extends BaseServiceImpl<AreaDsmMapper, AreaDsm> implements IAreaDsmService {

    @Resource
    private AreaSliceService areaSliceService;
    @Resource
    private OrgUM orgUM;
    @Resource
    private TUsersService tUsersService;

    @Override
    public List<AreaDsm> getInfoBySparentCode(String sparentCode, String sareaLevel) {
        OrgUnits orgUnits = tUsersService.byOrgUnitId(sparentCode);
        if (orgUnits.getOrgLevel() == 4 || StringUtils.isNotBlank(sareaLevel) && Integer.parseInt(sareaLevel) == 4) {
            return areaSliceService.lambdaQuery().eq(AreaSlice::getOrgNumber, orgUnits.getOrgNumber()).orderByAsc(AreaSlice::getSliceType).list().stream().map(o -> {
                if (o != null) {
                    return new AreaDsm().setSareaName(o.getSliceName()).setSareaCode(o.getSliceId()).setSareaLevel("5");
                }
                return null;
            }).collect(Collectors.toList());
        } else {
            return orgUM.findOrganizationByParentPK(sparentCode).stream().map(o -> {
                // o.isDelete() true-未删除
                if (o != null && o.isDelete()) {
                    return new AreaDsm().setSareaName(o.getName()).setSareaCode(o.getPrimaryKey()).setSareaLevel(String.valueOf(orgUnits.getOrgLevel() + 1));
                }
                return null;
            }).collect(Collectors.toList());
        }

    }

    @Override
    public AreaDsm getInfoBySliceId(String sliceId) {
        QueryWrapper<AreaDsm> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(AreaDsm::getSliceId, sliceId);
        return getOne(wrapper);
    }

    @Override
    public AreaDsmVo getAllBySareaCode(String sareaCode) {
        AreaDsmVo vo = new AreaDsmVo();
        AreaDsm areaDsm = getById(sareaCode);
        BeanUtils.copyProperties(areaDsm, vo);
        AreaDsm parentDsm = getById(areaDsm.getSparentCode());
        String sliceId = areaDsm.getSliceId();
        if (StringUtils.isNotBlank(sliceId)) {
            AreaSlice areaSlice = areaSliceService.getById(sliceId);
            BeanUtils.copyProperties(areaSlice, vo);
        }
        vo.setSparentCode(parentDsm.getSareaCode());
        vo.setSparentName(parentDsm.getSareaName());
        return vo;
    }

    @Override
    public RestResult deleteAreaDsm(String sareaCode) {
        AreaDsm areaDsm = getById(sareaCode);
        if (areaDsm == null) {
            return RestResult.error(ResultCode.USCID_INVALID,"数据不存在，请刷新后重试");
        }
        areaDsm.setSisDelete("1");
        saveOrUpdate(areaDsm);
        // 删除片区设置
        if (StringUtils.isNotBlank(areaDsm.getSliceId())) {
            AreaSlice areaSlice = areaSliceService.getById(areaDsm.getSliceId());
            if (areaSlice != null) {
                areaSlice.setIsDeleted("1");
                areaSlice.setState("0");
                areaSliceService.saveOrUpdate(areaSlice);
            }
        }
        return RestResult.ok();
    }

    @Override
    public RestResult saveAreaDsm(HttpServletRequest request, AreaDsmVo areaDsmVo) {
        LocalDateTime now = LocalDateTime.now();
        String type = areaDsmVo.getType();
        String sareaCode = areaDsmVo.getSareaCode();
        String sparentCode = areaDsmVo.getSparentCode();
        if (!StringUtils.equals(type, "add") && StringUtils.isBlank(sareaCode)) {
            return RestResult.error(ResultCode.PARAM_NOT_COMPLETE,"代码不能为空");
        }
        AICUser curUser = BaseController.getLoginUser(request);
        AreaDsm parentDsm;
        // 如果父级没选，即为根片区，则使用当前用户信息去查找
        boolean isSliceRoot = false;
        if (StringUtils.isBlank(sparentCode)) {
            isSliceRoot = true;
            String region = curUser.getRegionID();
            parentDsm = getOne(new LambdaQueryWrapper<AreaDsm>().eq(AreaDsm::getOrgNumber, region)
                    .eq(AreaDsm::getBisUnit, "1"));// 找出父机构
            sparentCode = parentDsm.getSareaCode();
        } else {
            parentDsm = getById(sparentCode);
        }
        if (parentDsm == null) {
            return RestResult.error(ResultCode.PARAM_NOT_COMPLETE,"查询不到上级数据");
        }
        if (StringUtils.isBlank(sareaCode)) {
            QueryWrapper<AreaDsm> wrapper = new QueryWrapper<>();
            wrapper.lambda().likeRight(AreaDsm::getSareaCode, sparentCode)
                    .apply("length(sarea_code) = " + (sparentCode.length() + 3) + " and sarea_code < " + (sparentCode + "900"))
                    .orderByDesc(AreaDsm::getSareaCode);
            List<AreaDsm> areaDsms = list(wrapper);
            if (!areaDsms.isEmpty()) {
                String code = areaDsms.get(0).getSareaCode();
                String lastStr = code.substring(code.length() - 3);
                int parseInt = Integer.parseInt(lastStr) + 1;
                String fill = beforeZeroFill(parseInt, 3);
                sareaCode = sparentCode + fill;
            } else {
                sareaCode = sparentCode + "001";
            }
            areaDsmVo.setSareaCode(sareaCode);
        }
        AreaDsm areaDsm = getById(sareaCode);
        if (StringUtils.equals(type, "add")) {
            if (areaDsm != null) {
                return RestResult.error(ResultCode.PARAM_NOT_COMPLETE,"代码已存在，请使用其它代码");
            }
            areaDsm = new AreaDsm();
        }
        String parentLevel = parentDsm.getSareaLevel();
        int intParentLevel = Integer.parseInt(parentLevel);// 父层级
        int areaLevel = intParentLevel + 1; // 当前层级
        areaDsmVo.setSareaLevel(String.valueOf(areaLevel));
        areaDsmVo.setSisDelete("0");
        BeanUtils.copyProperties(areaDsmVo, areaDsm);
        if (StringUtils.equals(type, "add")) {
            areaDsm.setSparentCode(parentDsm.getSareaCode());
            areaDsm.setBend("2");
            areaDsm.setBisUnit("0");
            areaDsm.setSunitId(StringUtils.equals(parentDsm.getBisUnit(), "1") ? parentDsm.getSareaCode() :
                    parentDsm.getSunitId());
            areaDsm.setSareaType("04");
            areaDsm.setOrgNumber(parentDsm.getOrgNumber());
            areaDsm.setPOrgNumber(parentDsm.getOrgNumber());
        }
        saveOrUpdate(areaDsm);
        if (areaLevel == 4) { // 片区
            String sliceId = areaDsm.getSliceId();
            if (StringUtils.isBlank(sliceId)) {
                sliceId = UUID.randomUUID().toString();
            }
            AreaSlice areaSlice = areaSliceService.getById(sliceId);
            if (areaSlice == null) {
                areaSlice = new AreaSlice();
                areaSlice.setCreateTime(now);
            }
            areaSlice.setSliceId(sliceId);
            areaSlice.setSliceName(areaDsm.getSareaName());
            areaSlice.setSupervisorId(areaDsmVo.getSupervisorId());
            areaSlice.setSupervisorName(areaDsmVo.getSupervisorName());
            areaSlice.setState(areaDsmVo.getState());
            areaSlice.setRemark(areaDsmVo.getSmemo());
            areaSlice.setCreatorId(curUser.getPrimaryKey())
                    .setOrgNumber(curUser.getRegionID());
            // pid
            AreaSlice parentSlice = areaSliceService.getOne(new LambdaQueryWrapper<AreaSlice>()
                    .eq(AreaSlice::getSliceType, SliceTypeEnums.STATION_PUBLIC.getCode())
                    .eq(AreaSlice::getOrgNumber, curUser.getRegionID()));
            if(parentSlice != null){
                areaSlice.setPSliceId(parentSlice.getSliceId());
            }
            areaSliceService.saveOrUpdate(areaSlice);
            // 记得把主键赋值回来
            areaDsm.setSliceId(sliceId);
            saveOrUpdate(areaDsm);
        }
        return RestResult.ok();
    }

    @Override
    public RestResult saveAreaSlice(HttpServletRequest request, AreaSlice areaSlice) {
        String sliceId = areaSlice.getSliceId();
        String sparentCode = areaSlice.getSparentCode();
        String sliceName = areaSlice.getSliceName();
        String remark = areaSlice.getRemark();
        AICUser loginUser = BaseController.getLoginUser(request);
        AreaDsm areaDsm = getInfoBySliceId(sliceId);
        AreaDsm parent = null;
        if(StringUtils.isBlank(sparentCode)){
            parent = getOne(new LambdaQueryWrapper<AreaDsm>()
                    .eq(AreaDsm::getOrgNumber, areaSlice.getOrgNumber())
                    .eq(AreaDsm::getBisUnit, Constant.TRUE_1_STR));
            if(parent != null){
                sparentCode = parent.getSareaCode();
            }
        }
        if (areaDsm == null) {
            String sareaCode;
            areaDsm = new AreaDsm();
            QueryWrapper<AreaDsm> wrapper = new QueryWrapper<>();
            wrapper.lambda().likeRight(AreaDsm::getSareaCode, sparentCode)
                    .apply("length(sarea_code) = " + (sparentCode.length() + 3) + " and sarea_code < " + (sparentCode + "900"))
                    .orderByDesc(AreaDsm::getSareaCode);
            List<AreaDsm> areaDsms = list(wrapper);
            if (!areaDsms.isEmpty()) {
                String code = areaDsms.get(0).getSareaCode();
                String lastStr = code.substring(code.length() - 3);
                int parseInt = Integer.parseInt(lastStr) + 1;
                String fill = beforeZeroFill(parseInt, 3);
                sareaCode = sparentCode + fill;
            } else {
                sareaCode = sparentCode + "001";
            }
            areaDsm.setSareaCode(sareaCode);
        }
        areaDsm.setSliceId(sliceId);
        areaDsm.setSparentCode(sparentCode);
        areaDsm.setSunitId(sparentCode.length() > 9 ? sparentCode.substring(0, 9) : sparentCode);
        areaDsm.setSareaType("04");
        areaDsm.setBisUnit("0");
        areaDsm.setBend("2");
        areaDsm.setSareaLevel("4");
        areaDsm.setSareaName(sliceName);
        areaDsm.setSmemo(remark);
        areaDsm.setSisDelete("0");
        areaDsm.setOrgNumber(loginUser.getRegionID());
        areaDsm.setPOrgNumber(loginUser.getRegionID());
        saveOrUpdate(areaDsm);
        return RestResult.ok();
    }

    @Override
    public RestResult anyscAreaSlice() {
        LocalDateTime now = LocalDateTime.now();
        QueryWrapper<AreaDsm> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(AreaDsm::getSareaLevel, "4");
        List<AreaDsm> areaDsms = list(wrapper);
        for (AreaDsm dsm : areaDsms) {
            String sliceId = dsm.getSliceId();
            if (StringUtils.isBlank(sliceId)) {
                sliceId = UUID.randomUUID().toString();
            }
            AreaSlice slice = areaSliceService.getById(sliceId);
            if (slice == null) {
                slice = new AreaSlice();
                slice.setCreateTime(now);
                slice.setCreatorId("F722C794-3E3E-427E-B303-3D1A8843F0CB");
                slice.setIsDeleted("0");
                slice.setState("1");
                slice.setSubUse("0");
                slice.setRemark("系统导入");
            }
            slice.setSliceId(sliceId);
            slice.setSliceName(dsm.getSareaName());
            slice.setUpdateTime(now);
            areaSliceService.saveOrUpdate(slice);
        }
        return RestResult.ok();
    }

    @Override
    public List<String> listAllExistsAreaDsmCode() {
        return baseMapper.listAllExistsAreaDsmCode();
    }

    /**
     * @param number 需要填充0的数字
     * @param length 需要多少位
     * @return
     */
    public String beforeZeroFill(int number, int length) {
        return beforeZeroFill(String.valueOf(number), length);
    }

    public String beforeZeroFill(String number, int length) {
        String tmp = number;
        for (int i = 0; i < length - number.length(); i++) {
            tmp = "0" + tmp;
        }
        return tmp;
    }

}
