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.common.utils.MD5FileUtil;
import com.kiisoo.ic.employee.entity.PrivilageCpUserDO;
import com.kiisoo.ic.employee.mapper.PrivilageCpUserDOMapper;
import com.kiisoo.ic.generalize.entity.PrivilageOrganizational;
import com.kiisoo.ic.generalize.entity.PrivilageOrganizationalMember;
import com.kiisoo.ic.generalize.mapper.OrganizationalMemberMapper;
import com.kiisoo.ic.generalize.mapper.RetailCompanyMapper;
import com.kiisoo.ic.store.entity.PoiStore;
import com.kiisoo.ic.store.entity.PoiStoreStaff;
import com.kiisoo.ic.store.entity.PrivilageCpUserStoreDO;
import com.kiisoo.ic.store.mapper.PoiStoreDOMapper;
import com.kiisoo.ic.store.mapper.PoiStoreStaffDOMapper;
import com.kiisoo.ic.store.mapper.PrivilageCpUserStoreDOMapper;
import com.kiisoo.ic.system.entity.PrivilageAccountDO;
import com.kiisoo.ic.system.entity.PrivilageUserDO;
import com.kiisoo.ic.system.entity.PrivilageUserRoleDO;
import com.kiisoo.ic.system.mapper.PrivilageAccountDOMapper;
import com.kiisoo.ic.system.mapper.PrivilageUserDOMapper;
import com.kiisoo.ic.system.mapper.PrivilageUserRoleDOMapper;
import org.apache.commons.lang3.StringUtils;
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 OrganizationInitPhone {
    static String sellerPath = "D:\\Backup\\桌面\\各种客户端\\bsd\\智慧导购\\初始人员数据20200424(1).xlsx";
    //有组织编码为零售公司，角色为总部运营人员, 有别名店长，其他的为导购,
    static String[] sellerColumns= {"pos店铺编码","组织编码","店铺名","姓名","账号","别名","角色","职务","性别","手机"};

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

    @Autowired
    private PoiStoreStaffDOMapper poiStoreStaffDOMapper;

    @Autowired
    private PoiStoreDOMapper poiStoreDOMapper;

    @Autowired
    private PrivilageUserDOMapper privilageUserDOMapper;

    @Autowired
    private PrivilageCpUserDOMapper privilageCpUserDOMapper;

    @Autowired
    private PrivilageCpUserStoreDOMapper privilageCpUserStoreDOMapper;

    @Autowired
    private OrganizationalMemberMapper organizationalMemberMapper;

    @Autowired
    private RetailCompanyMapper retailCompanyMapper;

    @Autowired
    private PrivilageUserRoleDOMapper privilageUserRoleDOMapper;

    @Autowired
    private PrivilageAccountDOMapper privilageAccountDOMapper;
    /**
     * 入库
     */
    private void inDB() {
        if(dataType.equals("seller")){
//            System.out.println(sellerMap.size());
            inDBSeller();
        }
    }

    //获取字符串转换实体
    public void getEntity(String json){
        //字符串转实体
        UserInitDO u = JSON.parseObject(json, UserInitDO.class);
        duplicateRemovalSeller(u);
    }

    //导购去重map
    private Map<String, UserInitDO> sellerMap = new HashMap<>();
    //去重导购
    public void duplicateRemovalSeller(UserInitDO u){
        sellerMap.put(u.getShopCode()+u.getAccount(), u);
    }

    //导购入库
    public void inDBSeller(){
        sellerMap.forEach((k,v) -> {
            String userI =  v.getAccount();
            String phone = v.getPhone();
            long shopId = 0;
            if(phone == null){
                System.out.println("无法找到唯一标示异常");
            }

            //查看用户
            PrivilageUserDO userdo = new PrivilageUserDO();
            userdo.setMobil(userI);
            if(StringUtils.isNotBlank(userI)){
                try{
                    PrivilageUserDO us = privilageUserDOMapper.selectOne(new QueryWrapper<>(userdo));
                    if (null != us) {
                        us.setMobil(phone);
                        us.setUpdateTime(new Date());
                        privilageUserDOMapper.updateById(us);
                    }
                }catch (Exception e){
                }

            }
        });
    }
    public long getStaffType(UserInitDO u){
    //零售经理, 店长, 信息主管, 零售主管, 店助, 导购, 店员, 已离职, PO
        //1 店长 2 副店长 3 店长助理 4 导购 5零售经理 6信息主管 7店员 8PO 9零售主管 10已离职 11未定义
        long type = 0;
        String al = u.getAlias();
        String role = u.getRole();
        String compnayCode = u.getCompanyCode();
        if(StringUtils.isNotBlank(compnayCode)){
            //零售公司
            type = 9;
        }else if(role.equals("总部运营人员")) {
            //总部运营

        }else if(al != null){
            //店长
            type = 1;
        }else{
            //导购
            type = 4;
        }
        return type;
    }

    public long getRoleType(UserInitDO u){
        //零售经理, 店长, 信息主管, 零售主管, 店助, 导购, 店员, 已离职, PO
        //1 店长 2 副店长 3 店长助理 4 导购 5零售经理 6信息主管 7店员 8PO 9零售主管 10已离职 11未定义
//        1	GLY-ADMIN	系统管理员
//        2	GL-YUNYING	总部运营人员
//        3	DG-YUNYING	运营人员
//        4	DZ-DIANZHANG	店长
//        5	DG-DAOGOU	导购
        long type = 0;
        String al = u.getAlias();
        String role = u.getRole();
        String compnayCode = u.getCompanyCode();
        if(StringUtils.isNotBlank(compnayCode)){
            //零售公司
            type = 3;
        }else if(role.equals("总部运营人员")) {
            //总部运营
            type = 2;
        }else if(al != null){
            //店长
            type = 4;
        }else{
            //导购
            type = 5;
        }
        return type;
    }

    static {
        col = columns.length;
    }

    @Test
    public void initData() {
        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.getSheetAt(0);
            //获取最大行数
            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;
    }
}
