package org.ta.pddserver.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.ta.pddserver.entity.AreaEntity;
import org.ta.pddserver.mapper.AreaMapper;
import org.ta.pddserver.model.api.request.AreaListRequest;
import org.ta.pddserver.model.api.request.LogOrderListRequest;
import org.ta.pddserver.model.api.response.LogOrderListResponse;
import org.ta.pddserver.service.AreaService;
import org.ta.pddserver.utils.JsonResponse;

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

@Service
public class AreaImpl extends ServiceImpl<AreaMapper, AreaEntity> implements AreaService {


    public Map<String, Object> areaList(AreaListRequest param) {

        Integer count = baseMapper.countUsable(param);
        param.checkPage(count,20);
        List<AreaEntity> list = baseMapper.getListByRequest(param);
        Map<String, Object> map = new HashMap<>();
        map.put("total", count);
        map.put("list", list);
        map.put("page", param.getPage());
        return map;
    }

    public JSONObject areaAdd(AreaEntity areaEntity) {
        AreaEntity ae = baseMapper.getInfoByCode(areaEntity.getCode());
        if(ae ==null){
            baseMapper.insert(areaEntity);
            return JsonResponse.generateLocalCommonSuccessResponse(true,"");
        }else {
            return JsonResponse.generateLocalCommonFailedResponse("-1", "区域已存在");
        }
    }

    public JSONObject areaEdit(AreaEntity areaEntity) {
        AreaEntity ae = baseMapper.getInfoByUid(areaEntity.getUid());
        if(ae == null){
            return JsonResponse.generateLocalCommonFailedResponse("-1", "区域信息不存在");
        }else {
            AreaEntity ae2 = baseMapper.getInfoByCode(areaEntity.getCode());
            if(ae2 ==null){
                //名称不重复，可以用
                baseMapper.updateById(areaEntity);
            }else {
                if(areaEntity.getUid().equals(ae2.getUid())){
                    //同一条可以修改
                    baseMapper.updateById(areaEntity);
                }else {
                    //code 重复
                    return JsonResponse.generateLocalCommonFailedResponse("-1", "区域名称已存在");
                }
            }
        }
        return JsonResponse.generateLocalCommonSuccessResponse(true,"");
    }

    public JSONObject areaDele(AreaEntity areaEntity) {
        AreaEntity ae = baseMapper.getInfoByUid(areaEntity.getUid());
        if(ae == null){
            return JsonResponse.generateLocalCommonFailedResponse("-1", "区域信息不存在");
        }else if(ae.getState() < 1){
            return JsonResponse.generateLocalCommonFailedResponse("-1", "区域信息已删除，请勿重复操作");
        }
        ae.setState(-1);
        baseMapper.updateById(ae);

        return JsonResponse.generateLocalCommonSuccessResponse(true,"");
    }

    public List<AreaEntity> getList() {
        return baseMapper.getList();
    }
}