package com.sptg.gateway.service.impl;

import com.baomidou.mybatisplus.toolkit.IdWorker;
import com.sptg.common.core.beans.ResultBean;
import com.sptg.common.core.beans.ResultEnum;
import com.sptg.device.api.dto.DeviceDto;
import com.sptg.device.api.dto.FlowCardDto;
import com.sptg.device.api.entity.Device;
import com.sptg.device.api.entity.DevicePath;
import com.sptg.device.api.entity.FlowCard;
import com.sptg.device.api.feigns.DeviceFeign;
import com.sptg.device.api.feigns.DevicePathFeign;
import com.sptg.device.api.feigns.FlowCardFeign;
import com.sptg.estate.api.entity.Residential;
import com.sptg.estate.api.entity.Unit;
import com.sptg.estate.api.feigns.ResidentialFeign;
import com.sptg.estate.api.feigns.UnitFeign;
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/12
 * description:
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class DeviceCsvServiceImpl implements CsvService {

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

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

    private final ResidentialFeign xqFeign;
    private final UnitFeign unitFeign;
    private final DeviceFeign deviceFeign;
    private final DevicePathFeign devicePathFeign;
    private final FlowCardFeign flowCardFeign;

    @Override
    public ResultBean<?> save(Object data) {
        DeviceDto dto = (DeviceDto) data;
        dto.setId(IdWorker.getId());
        ResultBean<Boolean> result = this.deviceFeign.addEntity(dto);
        if (result.getCode().equals(ResultEnum.SUCCESS.getCode())){
            if (null != dto.getFlowCardId()){
                FlowCardDto cardDto = new FlowCardDto();
                cardDto.setDeviceId(dto.getId());
                cardDto.setId(dto.getFlowCardId());
                this.flowCardFeign.updateBind(cardDto);
            }
        }
        return result;
    }

    @Override
    public Object arrToObj(String[] array) {
        DeviceDto dto = new DeviceDto();
        String oldId = array[1];
        Assert.hasText(oldId,"原数据Id不能为空");
        dto.setOldId(oldId);
        //  判断是否已存在
        Device device = this.deviceFeign.getByOldId(oldId);
        if (null != device){
            return null;
        }
        String typeCode = array[14];
        dto.setDeviceModelNumber(typeCode);//设备型号
        //  设备序列号
        String serialNumber = array[0];
        Assert.hasText(serialNumber,"设备序列号不能为空");
        dto.setSerialNumber(serialNumber);
        //  设备位置
        String pathId = array[12];
        Assert.notNull(pathId,"设备位置Id不能为空");
        DevicePath devicePath = this.devicePathFeign.getByOldId(pathId);
        Assert.notNull(devicePath,"设备位置Id不存在");
        dto.setInstallPathId(devicePath.getId());
        dto.setInstallPath(devicePath.getName());
        //  单元Id
        String unitId = array[3];
        if (StringUtils.isEmpty(unitId)){
            //  小区Id
            String xqId = array[2];
            Assert.hasText(xqId,"小区Id不能为空");
            Residential xq = this.xqFeign.getByOldId(xqId);
            Assert.notNull(xq,"小区Id不存在");
            dto.setXqId(xq.getId());
            dto.setXqName(xq.getName());
            dto.setOrgPosition(xq.getOrgPosition());
            dto.setEstatePosition(xq.getEstatePosition());
            //  设备名称 = 小区名称 + 设备位置
            dto.setName(xq.getName() + devicePath.getName());
            //  省市区
            dto.setRegionProvince(xq.getRegionProvince());
            dto.setRegionCity(xq.getRegionCity());
            dto.setRegionArea(xq.getRegionArea());
        } else {
            Unit unit = this.unitFeign.getByOldId(unitId);
            Assert.notNull(unit,"单元Id不存在");
            dto.setXqId(unit.getResidentialId());
            dto.setXqName(unit.getResidentialName());
            dto.setUnitId(unit.getId());
            dto.setOrgPosition(unit.getOrgPosition());
            dto.setEstatePosition(unit.getEstatePosition());
            //  设备名称 = 小区名称 + 单元名称 + 设备位置
            dto.setName(unit.getResidentialName() + unit.getName() + devicePath.getName());
            //  获取小区信息
            Residential xq = this.xqFeign.findResidentialById(unit.getResidentialId());
            dto.setRegionProvince(xq.getRegionProvince());
            dto.setRegionCity(xq.getRegionCity());
            dto.setRegionArea(xq.getRegionArea());
        }
        //  设备厂商(必填,1:巨龙,2:大豪,3:全视通)
        String factoryFlag = array[4];
        Assert.hasText(factoryFlag,"设备厂商不能为空");
        switch (factoryFlag){
            case "1":
                dto.setDeviceFactory("sjs");
                break;
            case "2":
                dto.setDeviceFactory("dh");
                break;
            case "3":
                dto.setDeviceFactory("qst");
                break;
            default:
                throw new RuntimeException("尚不支持此厂商设备");
        }
        //  设备别名
        String alias = array[5];
        dto.setAlias(StringUtils.isEmpty(alias) ? dto.getSerialNumber() : alias);
//        if (StringUtils.isEmpty(alias)){
//            dto.setAlias(dto.getSerialNumber());
//        } else {
//            dto.setAlias(alias);
//        }
        //  设备朝向(选填,1:进,2:出,默认1)
        String isOut = array[6];
        dto.setIsOut(StringUtils.isEmpty(isOut) || "1".equals(isOut) ? 1 : 2);
        //  开门密码(选填,默认000000)
        String openDoorPwd = array[7];
        dto.setOpenDoorPwd(StringUtils.isEmpty(openDoorPwd) ? "000000" : openDoorPwd);
        //  管理密码(选填,默认115200)
        String adminPwd = array[8];
        dto.setAdminPwd(StringUtils.isEmpty(adminPwd) ? "115200" : adminPwd);
        //  支持人脸识别(选填,1:支持,2:不支持,默认1)
        String haveFace = array[9];
        dto.setHaveFace(StringUtils.isEmpty(haveFace) || "1".equals(haveFace) ? 1 : 2);
        //  人脸识别度(选填,1~100之间的数字,默认75)
        String faceResolution = array[10];
        dto.setFaceResolution(StringUtils.isEmpty(faceResolution) ? 75 : Integer.parseInt(faceResolution));
//        try {
//            if (StringUtils.isEmpty(faceResolution)){
//                throw new NumberFormatException("null");
//            }
//            dto.setFaceResolution(Integer.parseInt(faceResolution));
//        } catch (NumberFormatException e){
//            dto.setFaceResolution(75);
//        }
        //  开门时长(选填,默认5秒)
        String delay = array[11];
        dto.setDelay(StringUtils.isEmpty(delay) ? 5 : Integer.parseInt(delay));
//        try {
//            if (StringUtils.isEmpty(delay)){
//                throw new NumberFormatException();
//            }
//            dto.setDelay(Integer.parseInt(delay));
//        } catch (NumberFormatException e){
//            dto.setDelay(5);
//        }
        //  流量卡
        String cardId = array[13];
        if (StringUtils.hasText(cardId)){
            FlowCard card = this.flowCardFeign.getByOldId(cardId);
            Assert.notNull(card,"卡号Id不存在");
            dto.setFlowCardId(card.getId());
        }
        dto.setCreateAccountId(1L);
        dto.setRootOrgId(1L);
        return dto;
    }

    private final static List<String> HEADER_LIST = new ArrayList<>(Arrays.asList(
            "设备序列号(必填)",
            "原数据Id(必填)",
            "小区Id(必填)",
            "单元Id(选填)",
            "设备厂商(必填、1:巨龙、2:大豪、3:全视通)",
            "设备别名(选填)",
            "设备朝向(选填、1:进、2:出、默认1)",
            "开门密码(选填、默认12345678)",
            "管理密码(选填、默认12345678)",
            "支持人脸识别(选填、1:支持、2:不支持、默认1)",
            "人脸识别度(选填、1~100之间的数字、默认75)",
            "开门时长(选填、默认5秒)",
            "设备位置Id（必填）",
            "流量卡Id(选填)",
            "设备型号(必填)"
    ));

    @Override
    public List<String> getHeaderList() {
        return HEADER_LIST;
    }
}
