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 com.kiisoo.ic.store.entity.PoiStore;
import com.kiisoo.ic.store.mapper.PoiStoreDOMapper;
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 OrganizationInitShop {
    static String shopPath = "D:\\Backup\\桌面\\各种客户端\\bsd\\智慧导购\\组织数据20200422.xlsx";
    static String[] shopColumns= {"上级组织","店铺编码","店铺名称","店铺简称","网点地址","网点经营性质","店铺级别"};

    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 = shopPath;
        //对应文件所取列名
        columns = shopColumns;
        //需要取的行数，若全部则置零
        maxRow = 0;
        dataType = "shop";
        sheetNum = "店铺数据";
        regionLevel = 1;
    }
    @Autowired
    private RetailCompanyMapper retailCompanyMapper;
    @Autowired
    private PoiStoreDOMapper poiStoreDOMapper;
    @Autowired
    private PrivilageDomainDOMapper privilageDomainDOMapper;
    @Autowired
    private PrivilageDomainEntityDOMapper privilageDomainEntityDOMapper;
    /**
     * 入库
     */
    private void inDB() {
        if(dataType.equals("shop")){
//            System.out.println(sellerMap.size());
            inDBRegion();
        }
    }

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

    //区域去重map
    private Map<String, ShopInitDO> shopMap = new HashMap<>();
    //去重去重
    public void duplicateRemovalShop(ShopInitDO u){
        shopMap.put(u.getShopName()+u.getCustomerName(), u);
    }

    //区域入库
    public void inDBRegion(){
        shopMap.forEach((k,v) -> {
            //查看是否有此店铺
            QueryWrapper<PoiStore> qw = new QueryWrapper<>();
            qw.eq("code", v.getShopCode());
            PoiStore poiStore = poiStoreDOMapper.selectOne(qw);
            if(null == poiStore){
                poiStore = new PoiStore();
                poiStore.setType(getType(v.getType()));
                poiStore.setLevel(getLevel(v.getLevel()));
                poiStore.setName(v.getShopName());
                poiStore.setCode(v.getShopCode());
                poiStore.setAddress(v.getAddress());
                poiStore.setStatus(1l);
                poiStore.setCreateTime(new Date());
                poiStore.setUpdateTime(new Date());
                poiStore.setAbbreviation(v.getShopAbbreviation());
                poiStoreDOMapper.insert(poiStore);
            }

            //查看是否有上级区域
            String parentName = v.getCustomerName();
            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();

                //找到区域域
                PrivilageDomainDO domain = privilageDomainDOMapper.selectDomain(parentId, 1,1);
                //对接域店铺关系
                PrivilageDomainEntityDO ent = new PrivilageDomainEntityDO();
                ent.setDomainId(domain.getId());
                ent.setEntityId(poiStore.getId());
                ent.setType(3);
                ent.setCreateTime(new Date());
                ent.setUpdateTime(new Date());
                privilageDomainEntityDOMapper.insert(ent);
            }

        });
    }
    public long getType(String shopType){
    //零售经理, 店长, 信息主管, 零售主管, 店助, 导购, 店员, 已离职, PO
        //1 店长 2 副店长 3 店长助理 4 导购 5零售经理 6信息主管 7店员 8PO 9零售主管 10已离职 11未定义
        long type = 0;
        if(shopType == null){
            type = 3;
        }else if(shopType.equals("直营")) {
            type = 1;
        }else if(shopType.equals("加盟")){
            type = 2;
        }
        return type;
    }
    public String getLevel(String shopLevel){
        //零售经理, 店长, 信息主管, 零售主管, 店助, 导购, 店员, 已离职, PO
        //1 店长 2 副店长 3 店长助理 4 导购 5零售经理 6信息主管 7店员 8PO 9零售主管 10已离职 11未定义
        String level = shopLevel;
        if(shopLevel == null){
            level = "未定义";
        }
        return level;
    }
    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;
    }
}
