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.estate.api.dto.UserDto;
import com.sptg.estate.api.entity.Room;
import com.sptg.estate.api.entity.User;
import com.sptg.estate.api.feigns.RoomFeign;
import com.sptg.estate.api.feigns.UserFeign;
import com.sptg.gateway.service.CsvService;
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.io.BufferedReader;
import java.io.IOException;
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/11
 * description:
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class HouseUserCsvServiceImpl implements CsvService {

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

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

    private final RoomFeign roomFeign;
    private final UserFeign userFeign;
    private final FastFileStorageClient storageClient;

    @Override
    public ResultBean<?> save(Object data) {
        return this.userFeign.addUser((UserDto)data);
    }

    @Override
    public Object arrToObj(String[] array) {
        //  原数据Id(必填)
        String oldId = array[2];
        Assert.hasText(oldId,"原数据Id不能为空");
        User user = this.userFeign.getByOldId(oldId);
        //  会员Id
        String customerId = array[14];
        if (null != user){
            return null;
        }
        UserDto dto = new UserDto();
        dto.setOldId(oldId);
        dto.setOldCustomerId(customerId);
        //  住户姓名(必填)
        dto.setName(array[0]);
        if (StringUtils.isEmpty(dto.getName())){
            dto.setName("匿名住户" + oldId);
        }
        //  房间Id(必填)
        String roomId = array[1];
        Assert.hasText(roomId,"房间Id不能为空");
        Room room = this.roomFeign.getByOldId(roomId);
        Assert.notNull(room,"房间Id不存在");
        dto.setRoomId(room.getId());
        dto.setResidentialId(room.getResidentialId());
        dto.setResidentialName(room.getResidentialName());
        dto.setUnitId(room.getUnitId());
        dto.setUnitName(room.getName());
        //  类型(必填,0:业主,1:成员,2:租户)
        String type = array[3];
        Assert.hasText(type,"住户的类型不能为空");
        dto.setType(Integer.valueOf(type));
        //  性别(必填,0:未知,1:男,2:女)
        String sex = array[4];
        if (StringUtils.isEmpty(sex)){
            dto.setSex(0);
        } else {
            dto.setSex(Integer.valueOf(sex));
        }
        //  国籍(必填,0:大陆,1:香港/澳门,2:台湾,3:海外)
        String nationality = array[5];
        Assert.notNull(nationality,"住户国籍不能为空");
        dto.setNationality(Integer.valueOf(nationality));
        //  证件号码(选填)
        String idCard = array[6];
        dto.setIdCard(idCard);
        //  手机号码(选填)
        String tel = array[7];
        dto.setTel(tel);
        //  籍贯(选填)
        String birthPlace = array[8];
        dto.setBirthPlace(birthPlace);
        //  人脸图片URI(选填)
        String imageUri = array[9];
        if (imageUri.startsWith("[\"")){
            imageUri = imageUri.substring(2);
        }
        if (imageUri.endsWith("\"]")){
            imageUri = imageUri.substring(0,imageUri.length() - 2);
        }
        if (!StringUtils.isEmpty(imageUri)){
            //  获取生效时间
            String beginTime =  array[10];
            Assert.hasText(beginTime,"人脸生效时间不能为空");
            //  获取失效时间
            String endTime = array[11];
            Assert.hasText(endTime,"人脸失效时间不能为空");
            //  人脸码
            String faceCode = array[12];
            //  人脸审核状态
            String checkState = array[13];
            try {
                //  将图片上传到文件服务器
                URL url = new URL(imageUri);
                URLConnection connection = url.openConnection();
                MultipartFile multipartFile = new MockMultipartFile("file", connection.getInputStream());
                StorePath storePath = this.storageClient.uploadFile(multipartFile.getInputStream(), multipartFile.getSize(), "jpg", null);
                //  图片地址
                dto.setImageUri(storePath.getFullPath());
                dto.setCreateFaceImageType(1);
                dto.setFaceCode(faceCode);
                dto.setFaceEnable(1);
                dto.setCreateType(2);
                if (StringUtils.isEmpty(checkState)){
                    dto.setCheckState(0);
                } else {
                    dto.setCheckState(Integer.valueOf(checkState));
                }
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                try {
                    dto.setFaceBeginDate(dateFormat.parse(beginTime));
                } catch (ParseException e){
                    throw new RuntimeException("人脸生效时间有误");
                }
                try {
                    dto.setFaceEndDate(dateFormat.parse(endTime));
                } catch (ParseException e){
                    throw new RuntimeException("人脸失效时间有误");
                }
            } catch (IOException e){
                log.error(e.getMessage());
            }
        }
        return dto;
    }

    private final static List<String> HEADER_LIST = new ArrayList<>(Arrays.asList(
            "住户姓名(必填)",                                     // 0
            "房间Id(必填)",                                       // 1
            "原数据Id(必填)",                                     // 2
            "类型(必填、0:业主、1:成员、2:租户)",                 // 3
            "性别(必填、0:未知、1:男、2:女)",                     // 4
            "国籍(必填、0:大陆、1:香港/澳门、2:台湾、3:海外)",    // 5
            "证件号码(选填)",                                     // 6
            "手机号码(选填)",                                     // 7
            "籍贯(选填)",                                         // 8
            "人脸图片URI(选填)",                                  // 9
            "人脸生效时间(选填)",                                 // 10
            "人脸失效时间(选填)",                                 // 11
            "人脸码(选填)",                                       // 12
            "人脸审核状态(选填、0:待审核、1:通过、2:拒绝)",       // 13
            "会员Id"                                              // 14
    ));

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

}
