package com.sptg.gateway.service.impl;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.sptg.common.core.beans.ResultBean;
import com.sptg.device.api.entity.Device;
import com.sptg.device.api.feigns.DeviceFeign;
import com.sptg.estate.api.entity.AccessRecords;
import com.sptg.estate.api.entity.User;
import com.sptg.estate.api.feigns.AccessRecordsFeign;
import com.sptg.estate.api.feigns.UserFeign;
import com.sptg.gateway.service.CsvService;
import com.sptg.permissions.api.entity.Account;
import com.sptg.permissions.api.feigns.AccountFeign;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.net.URL;
import java.net.URLConnection;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

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

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

    @Override
    public String getTemplateName() {
        return "出入记录导入模板";
    }

    @Override
    public ResultBean<?> save(Object data) {
        return this.accessRecordsFeign.addRecords((AccessRecords)data);
    }

    private final AccessRecordsFeign accessRecordsFeign;
    private final DeviceFeign deviceFeign;
    private final FastFileStorageClient storageClient;

    @Override
    public Object arrToObj(String[] array) {
        //  出入时间
        String time = array[8];
        Assert.hasText(time,"出入时间不能为空");
        AccessRecords records = new AccessRecords();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try{
            records.setAccessDate(dateFormat.parse(time));
        }catch (ParseException e){
            throw new RuntimeException("出入时间有误");
        }
        //  获取设备信息
        String serialNumber = array[0];
        log.warn("serialNumber  " + serialNumber);
        Device device = this.deviceFeign.getEntityBySerialNumber(serialNumber);
        Assert.notNull(device,"设备序列号不存在");
        records.setDeviceId(device.getId());
        records.setOrgPosition(device.getOrgPosition());
        records.setEstatePosition(device.getEstatePosition());
        records.setRootOrgId(device.getRootOrgId());
        records.setResidentialId(device.getXqId());
        records.setResidentialName(device.getXqName());
        records.setIsOut(device.getIsOut());
        records.setInstallPath(device.getInstallPath());
        records.setSerialNumber(device.getSerialNumber());
        records.setDeviceName(device.getName());
        records.setDeviceId(device.getId());
        //  必填,0:人脸开门,1:密码开门,2:刷卡开门,3:远程开门
        String openType = array[1];
        Assert.hasText(openType,"开门方式不能为空");
        switch (openType){
            case "0": records.setOpenDoorType(0); break;
            case "1": records.setOpenDoorType(1); break;
            case "2": records.setOpenDoorType(2); break;
            case "3": records.setOpenDoorType(3); break;
            default: throw new RuntimeException("开门方式参数异常");
        }
        //  设置用户信息
        this.setUserInfo(array,records);
        //  密码或卡号
        records.setAccessCardNo(array[6]);
        //  抓拍人脸地址
        String snapshoUri = array[7];
        if (StringUtils.hasText(snapshoUri)){
            if (snapshoUri.startsWith("[")){
                snapshoUri = snapshoUri.substring(2);
            }
            if (snapshoUri.endsWith("]")){
                snapshoUri = snapshoUri.substring(0,snapshoUri.length() - 2);
            }
            try{
                //  将图片上传到文件服务器
                String[] split = snapshoUri.split(",");
                URL url = new URL(split[0].substring(0, split[0].length() - 1));
                URLConnection connection = url.openConnection();
                MultipartFile multipartFile = new MockMultipartFile("file", connection.getInputStream());
                StorePath storePath = this.storageClient.uploadFile(multipartFile.getInputStream(), multipartFile.getSize(), "jpg", null);
                records.setSnapshoUri(storePath.getFullPath());
            }catch (Exception e){
                log.error(e.getMessage());
            }
        }
        return records;
    }

    private final AccountFeign accountFeign;
    private final UserFeign userFeign;

    private void setUserInfo(String[] array, AccessRecords records){
        //  开门用户类型(必填,0:后台管理员,2:住户,3:访客)
        String userType = array[2];
        //  默认就当是访客的开门记录
        int isAdmin = 3;
        int type = 3;
        //  用户Id
        String userId = array[4];
        if (StringUtils.hasText(userType) && StringUtils.hasText(userId)){
            switch (userType){
                case "0":
                    isAdmin = 0;
                    Account account = this.accountFeign.getByOldId(userId);
                    Assert.notNull(account,"后台管理员Id不存在");
                    records.setOpenUserId(account.getId());
                    records.setOpenUserName(account.getUserName());
                    records.setOpenUserTel(account.getUserMobile());
                    break;
                case "2":
                    isAdmin = 2;
                    User user = this.userFeign.getByOldId(userId);
                    records.setOpenUserId(user.getId());
                    records.setOpenUserName(user.getName());
                    records.setOpenUserTel(user.getTel());
                    type = user.getType();
                    break;
                case "3":
                    isAdmin = 3;
                    String visitorType = array[3];
                    if (StringUtils.hasText(visitorType)){
                        try {
                            type = Integer.valueOf(visitorType);
                        }catch (Exception e){
                            log.error(e.getMessage());
                        }
                    }
                    records.setOpenUserName(array[5]);
                    break;
            }

        }
        records.setIsAdmin(isAdmin);
        records.setAccessUserType(type);
    }

    @Override
    public List<String> getHeaderList() {
        return new ArrayList<>(Arrays.asList(
                "设备序列号(必填)",
                "开门方式(必填、0:人脸开门、1:密码开门、2:刷卡开门、3:远程开门)",
                "开门用户类型(必填、0:后台管理员、2:住户、3:访客)",
                "访客类型(选填、0:朋友、2:外卖、3:快递、4:其他)",
                "开门用户Id(选填)",
                "开门用户名称(选填)",
                "开门密码或卡号(选填)",
                "抓拍人脸地址(选填)",
                "出入时间(必填、yyyy-MM-dd HH:mm:ss)"
        ));
    }

}
