package com.sptg.gateway.service.impl;

import com.sptg.common.core.beans.ResultBean;
import com.sptg.device.api.dto.DevicePathDto;
import com.sptg.device.api.feigns.DevicePathFeign;
import com.sptg.estate.api.entity.Residential;
import com.sptg.estate.api.feigns.ResidentialFeign;
import com.sptg.gateway.service.CsvService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author WFT
 * @date 2020/6/19
 * description:
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class DevicePathCsvServiceImpl implements CsvService {


    @Override
    public String getFlag() {
        return "csv_device_path";
    }

    @Override
    public String getTemplateName() {
        return "设备位置导入模板";
    }

    @Override
    public ResultBean<?> save(Object data) {
        return this.devicePathFeign.addEntity((DevicePathDto) data);
    }

    private final DevicePathFeign devicePathFeign;
    private final ResidentialFeign xqFeign;

    @Override
    public Object arrToObj(String[] array) {
        DevicePathDto path = new DevicePathDto();
        //  数据Id
        String oldId = array[0];
        Assert.hasText(oldId,"原数据Id不能为空");
        if (null != this.devicePathFeign.getByOldId(oldId)){
            return null;
        }
        path.setOldId(oldId);
        //  位置名称
        String name = array[1];
        Assert.hasText(name,"位置名称不能为空");
        path.setName(name);
        //  小区Id
        String xqId = array[2];
        Assert.notNull(xqId,"小区Id不能为空");
        Residential xq = this.xqFeign.getByOldId(xqId);
        Assert.notNull(xq,"小区Id不存在");
        path.setXqId(xq.getId());
        path.setXqName(xq.getName());
        path.setRootOrgId(xq.getRootOrgId());
        path.setOrgPosition(xq.getOrgPosition());
        //  类型
        String type = array[3];
        Assert.hasText(type,"类型不能为空");
        try{
            path.setType(Integer.valueOf(type));
        } catch (NumberFormatException e){
            throw new RuntimeException("位置类型数据异常");
        }
        //  位置用途
        String yongTu = array[4];
        if (StringUtils.hasText(yongTu)){
            try{
                path.setPathUse(Integer.valueOf(yongTu));
            }catch (NumberFormatException e){
                throw new RuntimeException("位置用途数据异常");
            }
        }else {
            //  默认为一般用途
            path.setPathUse(10);
        }
        return path;
    }

    @Override
    public List<String> getHeaderList() {
        return new ArrayList<>(Arrays.asList(
                "原数据Id(必填)",
                "位置名称(必填)",
                "小区Id(必填)",
                "类型(必填、0:小区、1:单元)",
                "位置用途(选填、10:一般位置、11:特殊位置)"
        ));
    }
}
