package com.sptg.gateway.service.impl;

import com.baomidou.mybatisplus.toolkit.IdWorker;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.sptg.common.core.beans.ResultBean;
import com.sptg.common.core.constant.OperationConstant;
import com.sptg.estate.api.dto.UserDto;
import com.sptg.estate.api.entity.ApplyUser;
import com.sptg.estate.api.entity.Member;
import com.sptg.estate.api.entity.Room;
import com.sptg.estate.api.entity.User;
import com.sptg.estate.api.feigns.ApplyUserFeign;
import com.sptg.estate.api.feigns.MemberFeign;
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.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;

/**
 * @author WFT
 * @date 2020/6/17
 * description:
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AppMemberAuthCsvServiceImpl implements CsvService {
    @Override
    public String getFlag() {
        return "csv_app_member_auth";
    }

    @Override
    public String getTemplateName() {
        return "App会员认证记录导入模板";
    }

    private final ApplyUserFeign applyUserFeign;
    private final UserFeign userFeign;
    private final RoomFeign roomFeign;
    private final MemberFeign memberFeign;

    @Override
    public ResultBean<?> save(Object data) {
        return this.applyUserFeign.addApplyUser((ApplyUser) data);
    }

    private void setAttributeByUserNameAndRoomId(String username,Long roomId,String userId,String mobile,ApplyUser user,String memberId){
        User houseUser = null;
        if (!StringUtils.isEmpty(userId)){
            houseUser = this.userFeign.getByOldId(userId);
        }
        //  根据房间号和住户名称查询
        if (null == houseUser && !StringUtils.isEmpty(username)){
            houseUser = this.userFeign.getByRoomIdAndUserId(roomId, username);
        }
        //  根据房间号和手机号码查询
        if (null == houseUser && !StringUtils.isEmpty(mobile)){
            houseUser = this.userFeign.getByRoomIdAndUserMobile(roomId,mobile);
        }
        //  根据会员Id查询住户
        if (null == houseUser && !StringUtils.isEmpty(memberId)){
            houseUser = this.userFeign.getByOldCustomerId(memberId,roomId);
        }
        if (null != houseUser) {
            user.setUserId(houseUser.getId());
            user.setName(houseUser.getName());
        } else {
            throw new RuntimeException("无法通过住户名称，Id，手机号码查询到住户信息");
        }
    }

    @Override
    public Object arrToObj(String[] array) {
        //  获取房屋信息
        String roomId = array[2];
        Assert.hasText(roomId,"房屋Id不能为空");
        Room room = this.roomFeign.getByOldId(roomId);
        Assert.notNull(room,"房间Id不存在");
        ApplyUser user = new ApplyUser();
        user.setRoomId(room.getId());
        user.setRoomName(room.getName());
        //  审核状态
        String checkStatus = array[3];
        Assert.hasText(checkStatus,"审核状态不能为空");
        //  住户名称
        String userId = array[12];
        String username = array[0];
        //  联系电话
        String mobile = array[11];
        if (StringUtils.hasText(mobile)){
            user.setTel(mobile);
        }
        //  住户类型
        String userType = array[4];
        Assert.hasText(userType,"住户类型不能为空");
        try {
            user.setType(Integer.valueOf(userType));
        }catch (NumberFormatException e){
            throw new RuntimeException("住户类型数据异常");
        }
        //  性别(选填:0:未定义,1:男,2:女)
        String sex = array[6];
        if (StringUtils.hasText(sex)){
            try {
                user.setSex(Integer.valueOf(sex));
            }catch (NumberFormatException e){
                user.setSex(0);
            }
        }
        //  国籍
        String guoJi = array[7];
        if (StringUtils.hasText(sex)){
            try {
                user.setNationality(Integer.valueOf(guoJi));
            }catch (NumberFormatException e){
                throw new RuntimeException("国籍参数异常");
            }
        }
        //  护照Url
        String hz = array[8];
        if (StringUtils.hasText(hz)) {
            try {
                hz = this.downLoad(hz);
                user.setPassportImgUri(hz);
            } catch (IOException e) {
                throw new RuntimeException("护照地址有误");
            }
        }
        //  入境证明
        String rjzm = array[9];
        if (StringUtils.hasText(rjzm)){
            try {
                rjzm = this.downLoad(rjzm);
                user.setEntryImgUri(rjzm);
            } catch (IOException e) {
                throw new RuntimeException("入境证明地址有误");
            }
        }
        //  会员Id
        String memberId = array[1];
        Assert.hasText(memberId,"会员Id不能为空");
        //  审核状态(必填、0:待审核、1:审核通过、2:审核不通过)
        switch (checkStatus){
            case "0":
                user.setCheckState(0);
                try {
                    this.setAttributeByUserNameAndRoomId(username, room.getId(), userId, mobile, user,memberId);
                }catch (Exception e){
                    //  创建新住户
                    UserDto dto = new UserDto();
                    dto.setId(IdWorker.getId());
                    dto.setName(username);
                    dto.setRoomId(room.getId());
                    dto.setRoomName(room.getName());
                    dto.setUnitId(room.getUnitId());
                    dto.setUnitName(room.getUnitName());
                    dto.setResidentialId(room.getResidentialId());
                    dto.setResidentialName(room.getResidentialName());
                    dto.setType(user.getType());
                    dto.setSex(null == user.getSex() ? 0 : user.getSex());
                    dto.setNationality(user.getNationality());
                    //  保存住户
                    this.userFeign.addUser(dto);
                    user.setUserId(dto.getId());
                    user.setName(dto.getName());
                }
                break;
            case "1":
                user.setCheckState(1);
                //  根据住户Id查询
                this.setAttributeByUserNameAndRoomId(username,room.getId(),userId,mobile,user,memberId);
                break;
            case "2":
                user.setCheckState(2);
                //  审核未通过的数据若无法获取到用户信息,则直接跳过
                try {
                    this.setAttributeByUserNameAndRoomId(username, room.getId(), userId,mobile, user,memberId);
                }catch (Exception e){
                    return null;
                }
                break;
            default:
                throw new RuntimeException("审核状态数据异常");
        }
        //  小区
        user.setResidentialId(room.getResidentialId());
        user.setResidentialName(room.getResidentialName());
        //  单元
        user.setUnitId(room.getUnitId());
        user.setUnitName(room.getUnitName());
        user.setOrgPosition(room.getOrgPosition());
        Member member = this.memberFeign.getByOldId(memberId);
        Assert.notNull(member,"会员Id不存在");
        user.setMemberId(member.getId());
        //  审核拒绝原因
        String liYou = array[5];
        if (StringUtils.hasText(liYou)){
            user.setCheckOpinion(liYou);
        }
        //  人脸图片
        String faceImg = array[10];
        if (faceImg.startsWith("\"[\"\"")){
            faceImg = faceImg.substring(4);
        }
        if (faceImg.endsWith("\"\"]\"")){
            faceImg = faceImg.substring(0,faceImg.length() - 4);
        }
        if (StringUtils.hasText(faceImg)){
            try {
                faceImg = this.downLoad(faceImg);
                user.setImageUri(faceImg);
            } catch (IOException e) {
                throw new RuntimeException("人脸图片地址有误");
            }
        }
        user.setRecordType(OperationConstant.ZERO);
        return user;
    }

    private final FastFileStorageClient storageClient;

    private String downLoad(String imageUri) throws IOException{
        //  将图片上传到文件服务器
        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);
        return storePath.getFullPath();
    }


    @Override
    public List<String> getHeaderList() {
        return new ArrayList<>(Arrays.asList(
                "申请人姓名(必填)",                                        //  0
                "会员Id(必填)",                                            //  1
                "房间Id(必填)",                                            //  2
                "审核状态(必填、0:待审核、1:审核通过、2:审核不通过)",      //  3
                "住户类型(必填、0:业主、1:成员、2:租客、)",                //  4
                "审核被拒绝原因(选填)",                                    //  5
                "性别(选填:0:未定义、1:男、2:女)",                         //  6
                "国籍(选填、0:大陆、1:香港澳门、2:台湾、3:海外)",          //  7
                "护照图片地址(选填)",                                      //  8
                "入境证明(选填)",                                          //  9
                "人脸图片(选填)",                                          //  10
                "联系电话(选填)",                                          //  11
                "住户Id"                                                   //  12
        ));
    }

}
