package init;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kiisoo.ic.app.IcApplication;
import com.kiisoo.ic.domain.entity.PrivilageDomainDO;
import com.kiisoo.ic.domain.entity.PrivilageDomainEntityDO;
import com.kiisoo.ic.domain.mapper.PrivilageDomainDOMapper;
import com.kiisoo.ic.domain.mapper.PrivilageDomainEntityDOMapper;
import com.kiisoo.ic.generalize.entity.PrivilageOrganizational;
import com.kiisoo.ic.generalize.mapper.RetailCompanyMapper;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.Map.Entry;

/**
 *  组织数据初始化
 * Created by hc on 2020/4/21
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = IcApplication.class)
public class OrganizationInitCustomer {
    static String bigRegionPath = "D:\\Backup\\桌面\\各种客户端\\bsd\\智慧导购\\组织数据20200422.xlsx";
    static String[] bigRegionColumns= {"上级组织编码","上级组织","客户"};

    static String filePath = null;
    static String columns[] = null;
    static Integer col = null;
    static Integer maxRow = null;
    static String sheetNum = null;
    //seller
    static String dataType = null;
    static long regionLevel = 0;
    //初始化行列数据
    static {
        //文件路径
        filePath = bigRegionPath;
        //对应文件所取列名
        columns = bigRegionColumns;
        //需要取的行数，若全部则置零
        maxRow = 0;
        dataType = "customer";
        sheetNum = "客户";
        regionLevel = 3;
    }

    @Autowired
    private RetailCompanyMapper retailCompanyMapper;
    @Autowired
    private PrivilageDomainDOMapper privilageDomainDOMapper;
    @Autowired
    private PrivilageDomainEntityDOMapper privilageDomainEntityDOMapper;
    /**
     * 入库
     */
    private void inDB() {
        if(dataType.equals("customer")){
//            System.out.println(sellerMap.size());
            inDBRegion();
        }
    }

    //获取字符串转换实体
    public void getEntity(String json){
        if(dataType.equals("customer")){
            //字符串转实体
            RegionInitDO u = JSON.parseObject(json, RegionInitDO.class);
            duplicateRemovalRegion(u);
        }
    }

    //区域去重map
    private Map<String, RegionInitDO> regionMap = new HashMap<>();
    //去重去重
    public void duplicateRemovalRegion(RegionInitDO u){
        regionMap.put(u.getName(), u);
    }

    //区域入库
    public void inDBRegion(){
        regionMap.forEach((k,v) -> {
            //查看是否有上级区域
            String parentName = v.getParentName();
            long parentId = 0;
            if(parentName != null){
                //查区域
                PrivilageOrganizational p = new PrivilageOrganizational();
                p.setName(parentName);
                PrivilageOrganizational parent = retailCompanyMapper.selectOne(new QueryWrapper<>(p));
                if(null == parent){
                    System.out.println("父区域异常");
                }
                parentId = parent.getId();
            }
            //创建品牌公司
            PrivilageOrganizational param = new PrivilageOrganizational();
            param.setName(v.getName());
            param.setLevel(regionLevel);
            param.setParentId(parentId);
            param.setType(2l);
            param.setStatus(1l);
            param.setCreateTime(new Date());
            param.setUpdateTime(new Date());
            retailCompanyMapper.insert(param);

            //创建域
            PrivilageDomainDO p = new PrivilageDomainDO();
            p.setName(v.getName());
            p.setStatus(1);
            p.setCreateTime(new Date());
            p.setUpdateTime(new Date());
            privilageDomainDOMapper.insert(p);

            //创建区域和域实体关系
            PrivilageDomainEntityDO entityDO = new PrivilageDomainEntityDO();
            entityDO.setDomainId(p.getId());
            entityDO.setEntityId(param.getId());
            entityDO.setType(1);
            entityDO.setCreateTime(new Date());
            entityDO.setUpdateTime(new Date());
            privilageDomainEntityDOMapper.insert(entityDO);

            //创建区域和域关联关系
            retailCompanyMapper.insertDomainOrgRelation(p.getId(), param.getId());
        });
    }
    public long getType(String position){
    //零售经理, 店长, 信息主管, 零售主管, 店助, 导购, 店员, 已离职, PO
        //1 店长 2 副店长 3 店长助理 4 导购 5零售经理 6信息主管 7店员 8PO 9零售主管 10已离职 11未定义
        long type = 0;
        if(position == null){
            type = 11;
        }else if(position.equals("零售经理")) {
            type = 5;
        }else if(position.equals("店长")){
            type = 1;
        }else if(position.equals("信息主管")){
            type = 6;
        }else if(position.equals("零售主管")){
            type = 9;
        }else if(position.equals("店助")){
            type = 3;
        }else if(position.equals("导购")){
            type = 4;
        }else if(position.equals("店员")){
            type = 7;
        }else if(position.equals("已离职")){
            type = 10;
        }else if(position.contains("PO")){
            type = 8;
        }
        return type;
    }

    static {
        col = columns.length;
    }

    @Test
    public void initDatas() {
        Workbook wb =null;
        Sheet sheet = null;
        Row row = null;
        List<Map<String,String>> list = null;
        String cellData = null;

        wb = readExcel(filePath);
        if(wb != null){
            //用来存放表中数据
            list = new ArrayList<Map<String,String>>();
            //获取第一个sheet
            sheet = wb.getSheet(sheetNum);
            //获取最大行数
            int rownum = sheet.getPhysicalNumberOfRows();
            //获取第一行
            row = sheet.getRow(0);
            //获取最大列数
            int colnum = col;
            for (int i = 1; i<rownum; i++) {
                Map<String,String> map = new LinkedHashMap<String,String>();
                row = sheet.getRow(i);
                if(row !=null){
                    for (int j=0;j<colnum;j++){
                        cellData = (String) getCellFormatValue(row.getCell(j));
                        map.put(columns[j], cellData);
                    }
                }else{
                    break;
                }
                list.add(map);
            }
        }
        //遍历解析出来的list
        int i = 0;
        for (Map<String,String> map : list) {
            StringBuffer sb = new StringBuffer();
            sb.append("{");
            for (Entry<String,String> entry : map.entrySet()) {
                sb.append("\"");
                sb.append(entry.getKey());
                sb.append("\":\"");
                sb.append(entry.getValue()+"\",");
            }
            sb.deleteCharAt(sb.length() - 1);
            sb.append("}");

            getEntity(sb.toString());

            i ++;
            if(maxRow == i){
                break;
            }
        }

        inDB();

        System.out.println("OK");
    }

    //读取excel
    public static Workbook readExcel(String filePath){
        Workbook wb = null;
        if(filePath==null){
            return null;
        }
        String extString = filePath.substring(filePath.lastIndexOf("."));
        InputStream is = null;
        try {
            is = new FileInputStream(filePath);
            if(".xls".equals(extString)){
                return wb = new HSSFWorkbook(is);
            }else if(".xlsx".equals(extString)){
                return wb = new XSSFWorkbook(is);
            }else{
                return wb = null;
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return wb;
    }
    public static Object getCellFormatValue(Cell cell){
        Object cellValue = null;
        if(cell!=null){
            //判断cell类型
            switch(cell.getCellType()){
                case Cell.CELL_TYPE_NUMERIC:{
                    cellValue = String.valueOf(cell.getNumericCellValue());
                    break;
                }
                case Cell.CELL_TYPE_FORMULA:{
                    //判断cell是否为日期格式
                    if(DateUtil.isCellDateFormatted(cell)){
                        //转换为日期格式YYYY-mm-dd
                        cellValue = cell.getDateCellValue();
                    }else{
                        //数字
                        cellValue = String.valueOf(cell.getNumericCellValue());
                    }
                    break;
                }
                case Cell.CELL_TYPE_STRING:{
                    cellValue = cell.getRichStringCellValue().getString();
                    break;
                }
                default:
                    cellValue = "";
            }
        }else{
            cellValue = "";
        }
        return cellValue;
    }
}
