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.entity.Residential;
import com.sptg.estate.api.feigns.ResidentialFeign;
import com.sptg.gateway.service.CsvService;
import com.sptg.permissions.api.dto.AccountDto;
import com.sptg.permissions.api.entity.Account;
import com.sptg.permissions.api.entity.Organization;
import com.sptg.permissions.api.feigns.AccountFeign;
import com.sptg.permissions.api.feigns.OrgFeign;
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.util.ArrayList;
import java.util.Arrays;
import java.util.List;

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

    private final AccountFeign accountFeign;
    private final OrgFeign orgFeign;
    private final FastFileStorageClient storageClient;

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

    @Override
    public String getTemplateName() {
        return "后台账号导入模板";
    }

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

    private final static Account ON_LINE_USER = new Account();

    static {
        ON_LINE_USER.setId(1L);
    }

    private final ResidentialFeign xqFeign;

    @Override
    public Object arrToObj(String[] array) {
        String oldId = array[4];
        Assert.hasText(oldId,"原数据Id不能为空");
        //  判断数据是否已存在
        if (null != this.accountFeign.getByOldId(oldId)){
            return null;
        }
        AccountDto dto = new AccountDto();
        dto.setOldId(oldId);
        //  登录名
        dto.setLoginName(array[0]);
        Assert.hasText(dto.getLoginName(),"登录名不能为空");
        String type = array[1];
        Assert.hasText(type,"账号归属类型不能为空");
        //  获取机构Id
        String orgId = array[2];
        if (!StringUtils.isEmpty(orgId)){

            //  判断是否为小区账号
            if ("3".equals(type)){
                //小区账号
                //  获取小区
                Residential xq = this.xqFeign.getByOldId(orgId);
                Assert.notNull(xq,"小区Id不存在");
                dto.setOrgId(xq.getOrgPid());
                dto.setOrgPosition(xq.getOrgPosition());
                dto.setEstatePosition(xq.getEstatePosition());
                dto.setXqId(xq.getId());
                dto.setXqName(xq.getName());
            } else if ("2".equals(type)) {
                //物业账号
                //  获取机构
                Organization org = this.orgFeign.getByOldIdAndType(orgId, "0");
                Assert.notNull(org,"机构Id不存在");
                dto.setOrgId(1L);
                dto.setOrgPosition("0/1/");//集团
                dto.setEstatePosition(org.getPosition());
            } else {
                //机构（代理商）、或者广告商账号
                //  获取机构
                Organization org = this.orgFeign.getByOldIdAndType(orgId, "0");
                Assert.notNull(org,"机构Id不存在");
                dto.setOrgId(org.getId());
                dto.setOrgPosition(org.getPosition());
            }
        } else {
            dto.setOrgId(1L);
            dto.setOrgPosition("0/1/");
        }
        //  密码
        dto.setLoginPwd(array[3]);
        Assert.hasText(dto.getLoginPwd(),"登录密码不能为空");
        //  不需要再次加密
        dto.setIsNotEncryption(1);
        //  姓名,联系方式
        dto.setUserName(array[5]);
        dto.setUserMobile(array[6]);
        //  用户头像
        String userPortrait = array[7];
        if (StringUtils.hasText(userPortrait)){
            try{
                //  将图片上传到文件服务器
                URL url = new URL(userPortrait);
                URLConnection connection = url.openConnection();
                MultipartFile multipartFile = new MockMultipartFile("file", connection.getInputStream());
                StorePath storePath = this.storageClient.uploadFile(multipartFile.getInputStream(), multipartFile.getSize(), "jpg", null);
                dto.setUserPortraitUri(storePath.getFullPath());
            }catch (Exception e){
                log.error(e.getMessage());
            }
        }
        dto.setOnLineUser(ON_LINE_USER);
        dto.setCreateIp("127.0.0.1");
        dto.setRoleIds(type);
        return dto;
    }

    /*
        0   yang,
        1   0,
        2   ,
        3   ef797c8118f02dfb649607dd5d3f8c7623048c9c063d532cc95c5ed7a898a64f,
        4   3,
        5   杨波,
        6   ,

        0   3000101928,
        1   3,
        2   744,
        3   8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92,
        4   375,
        5   演示小区,
        6   ,

        0   00075201,
        1   1,
        2   ,
        3   d73975e725d7e9f2922919c48904415410bc7e7ca5a599bafe1e3d8a8cc0fbb3,
        4   626,
        5   常运智慧,
        6   ,

     */

    @Override
    public List<String> getHeaderList() {
        return new ArrayList<>(Arrays.asList(
                "登录名(必填)",                                              //  0
                "账号归属类型(必填、1:代理商、2:物业、3:小区、4:广告商)",    //  1
                "账号归属机构Id",                                            //  2
                "密码(必填、必须明文)",                                      //  3
                "原数据Id(必填)",                                            //  4
                "姓名(选填)",                                                //  5
                "联系方式(选填)",                                            //  6
                "头像(选填)"                                                 //  7
        ));
    }
}
