package init;

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

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.customer.entity.OpCustomer;
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.store.service.PoiStoreStaffService;
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.PrivilageRoleDOMapper;
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.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
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.stereotype.Service;
import org.springframework.test.context.junit4.SpringRunner;

/**
 *  组织数据初始化
 * Created by hc on 2020/4/21
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = IcApplication.class)
public class OrganizationInit {
    static String sellerPath = "file/store.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 sellerCode = v.getAccount() == null ? v.getPhone() : v.getAccount();
            String phone = v.getPhone() == null ? v.getAccount() : v.getPhone();
            String shopCode = v.getShopCode();
            long shopId = 0;
            if(sellerCode == null || phone == null){
                System.out.println("无法找到唯一标示异常");
            }
            //查看店铺
            if(shopCode != null){
                PoiStore p = new PoiStore();
                p.setCode(shopCode);
                PoiStore shop = poiStoreDOMapper.selectOne(new QueryWrapper<>(p));
                if(null != shop){
                    shopId = shop.getId();
                }
            }

            //查看用户
            PrivilageUserDO userdo = new PrivilageUserDO();
            userdo.setMobil(phone);
            PrivilageUserDO us = privilageUserDOMapper.selectOne(new QueryWrapper<>(userdo));
            if (null == us) {
                //如果没有用户就增加
                us = new PrivilageUserDO();
                us.setName(v.getName());
                us.setMobil(phone);
                us.setEmail(v.getEmail());
                us.setAddress(v.getAdress());
                us.setStatus(1);
                us.setCreateTime(new Date());
                us.setUpdateTime(new Date());
                us.setAbbreviation(v.getAlias());
                try{
                    privilageUserDOMapper.insert(us);
                }catch (Exception e){
                    us.setAbbreviation(null);
                    privilageUserDOMapper.insert(us);
                }
            }

            //增加导购
            long statffType = getStaffType(v);
            if (statffType == 1 || statffType == 4) {
                //店涨，导购需要加staff
                PoiStoreStaff p = new PoiStoreStaff();
                p.setStoreId(shopId);
                p.setUserId(us.getId());
                p.setStoreCode(v.getShopCode());
                p.setStaffCode(sellerCode);
                p.setType(statffType);
                p.setStatus(1L);
                p.setCreateTime(new Date());
                p.setUpdateTime(new Date());
                if(v.getCustomerUserId() != null && !v.getCustomerUserId().equals("mal")){
                    p.setCustomerUserId(Long.parseLong(v.getCustomerUserId()));
                }

                Map<String, Object> staffMap = new HashMap<>();
                staffMap.put("store_id", p.getStoreId());
                staffMap.put("user_id", p.getUserId());
                staffMap.put("store_code", p.getStoreCode());
//                staffMap.put("staff_code", p.getStaffCode());
                staffMap.put("type", p.getType());
                staffMap.put("status", p.getStatus());
                List<PoiStoreStaff> staffList = poiStoreStaffDOMapper.selectByMap(staffMap);
                if(staffList.size() == 0){
                    System.out.println("insert" + p.toString());
                    poiStoreStaffDOMapper.insert(p);
                }else{
                    System.out.println("修改店铺信息" + p.toString());
                    staffList.get(0).setStaffCode(p.getStaffCode());
                    staffList.get(0).setCustomerUserId(p.getCustomerUserId());
                    poiStoreStaffDOMapper.updateById(staffList.get(0));
                }

                //如果是店长，需要绑定店铺cp
                if (statffType == 1) {
                    //排重---根据企业微信账号查询是否存在用户
                    PrivilageCpUserDO privilageCpUserDO = new PrivilageCpUserDO();
                    privilageCpUserDO.setCpUserId(v.getCustomerUserId());
                    privilageCpUserDO.setStatus(1);

                    Map<String,Object> map = new HashMap<>();
                    // 客户ID
                    map.put("cp_user_id", p.getCustomerUserId());
                    map.put("status", privilageCpUserDO.getStatus());
                    List<PrivilageCpUserDO> list = privilageCpUserDOMapper.selectByMap(map);
                    if(list.size() == 0){
                        System.out.println("privilageCpUserDO=" + privilageCpUserDO.toString());
                        privilageCpUserDOMapper.insert(privilageCpUserDO);
                        PrivilageCpUserStoreDO cpUserStore = new PrivilageCpUserStoreDO();
                        cpUserStore.setStoreId(shopId);
                        cpUserStore.setCpUserId(privilageCpUserDO.getId());

                        Map<String, Object> cpUserStoreMap = new HashMap<>();
                        cpUserStoreMap.put("store_id", cpUserStore.getStoreId());
//                        cpUserStoreMap.put("cp_user_id", cpUserStore.getCpUserId());
                        List<PrivilageCpUserStoreDO> cpUserStoreList = privilageCpUserStoreDOMapper.selectByMap(cpUserStoreMap);
                        if(cpUserStoreList.size() == 0){
                            System.out.println("privilageCpUserStoreDOMapper:insert" + cpUserStore.toString());
                            privilageCpUserStoreDOMapper.insert(cpUserStore);
                        }else{
                            System.out.println("PrivilageCpUserStoreDO:修改" + cpUserStore.toString());
                            PrivilageCpUserStoreDO cpuserstore = cpUserStoreList.get(0);
                            cpuserstore.setStoreId(cpUserStore.getStoreId());
                            cpuserstore.setCpUserId(cpUserStore.getCpUserId());
                            privilageCpUserStoreDOMapper.updateById(cpuserstore);
                        }
                    }else{
                        PrivilageCpUserDO cpuserdo = list.get(0);
                        cpuserdo.setCpUserId(privilageCpUserDO.getCpUserId());
                        cpuserdo.setStatus(privilageCpUserDO.getStatus());
                        cpuserdo.setName(v.getName());
                        cpuserdo.setAlias(v.getAlias());
                        privilageCpUserDOMapper.updateById(cpuserdo);

                        PrivilageCpUserStoreDO cpUserStore = new PrivilageCpUserStoreDO();
                        cpUserStore.setStoreId(shopId);
                        cpUserStore.setCpUserId(list.get(0).getId());
                        Map<String, Object> cpUserStoreMap = new HashMap<>();
                        cpUserStoreMap.put("store_id", cpUserStore.getStoreId());
//                        cpUserStoreMap.put("cp_user_id", cpUserStore.getCpUserId());
                        List<PrivilageCpUserStoreDO> cpUserStoreList = privilageCpUserStoreDOMapper.selectByMap(cpUserStoreMap);
                        if(cpUserStoreList.size() == 0){
                            System.out.println("privilageCpUserStoreDOMapper:insert" + cpUserStore.toString());
                            privilageCpUserStoreDOMapper.insert(cpUserStore);
                        }else{
//                            if(cpUserStoreList.size() > 1){
//                                System.out.println("修改" + cpUserStore.toString());
//                                for (int i = 0; i < cpUserStoreList.size(); i++) {
//                                    PrivilageCpUserStoreDO citem = cpUserStoreList.get(i);
//                                    if(!citem.getCpUserId().equals(cpUserStore.getCpUserId())){
//                                        privilageCpUserStoreDOMapper.deleteById(citem.getId());
//                                    }
//                                }
//                            }

//                            System.out.println("修改" + cpUserStore.toString());
                            PrivilageCpUserStoreDO cpuserstore = cpUserStoreList.get(0);
                            cpuserstore.setStoreId(cpUserStore.getStoreId());
                            cpuserstore.setCpUserId(cpUserStore.getCpUserId());
                            privilageCpUserStoreDOMapper.updateById(cpuserstore);
                        }
                    }

                }
            }else if(statffType == 9){
                //零售公司
                //绑定用户和零售公司
                QueryWrapper<PrivilageOrganizational> q = new QueryWrapper<>();
                q.eq("code",v.getCompanyCode().replace(".0",""));
                PrivilageOrganizational comp = retailCompanyMapper.selectOne(q);
                if (comp!=null) {
                    PrivilageOrganizationalMember mem = new PrivilageOrganizationalMember();
                    mem.setOrgId(comp.getId());
                    mem.setUserId(us.getId());
                    mem.setCreateTime(new Date());
                    mem.setUpdateTime(new Date());
                    organizationalMemberMapper.insert(mem);
                }
            }

            //不管什么类型都要绑定角色
            PrivilageUserRoleDO privilageUserRoleDO = new PrivilageUserRoleDO();
            privilageUserRoleDO.setUserId(us.getId());
            privilageUserRoleDO.setRoleId(getRoleType(v));
            privilageUserRoleDO.setCreateTime(new Date());
            privilageUserRoleDO.setUpdateTime(new Date());


            Map<String, Object> map = new HashMap<>();
            map.put("user_id", privilageUserRoleDO.getUserId());
            map.put("role_id", privilageUserRoleDO.getRoleId());
            List<PrivilageUserRoleDO> list = privilageUserRoleDOMapper.selectByMap(map);
            if(list.size() == 0){
                System.out.println("insert" + privilageUserRoleDO.toString());

                privilageUserRoleDOMapper.insert(privilageUserRoleDO);
                //创建账号,密码为账号加123
                PrivilageAccountDO acc = new PrivilageAccountDO();
                acc.setLogin(v.getAccount());
                acc.setPassword(MD5FileUtil.getMD5String(v.getAccount()+"123"));
                acc.setUserId(us.getId());
                acc.setType(1);
                acc.setStatus(1);
                acc.setCreateTime(new Date());
                acc.setUpdateTime(new Date());

                Map<String, Object> accountMap = new HashMap<>();
                accountMap.put("login", acc.getLogin());
                accountMap.put("user_id", acc.getUserId());
                accountMap.put("type", acc.getType());
                List<PrivilageAccountDO> accountList = privilageAccountDOMapper.selectByMap(accountMap);
                if(accountList.size() == 0){
                    System.out.println("insert" + acc.toString());
                    privilageAccountDOMapper.insert(acc);
                }else{
                    System.out.println("修改账号信息" + acc.toString());
                    PrivilageAccountDO account = accountList.get(0);
                    account.setLogin(acc.getLogin());
                    account.setUserId(acc.getUserId());
                    account.setType(acc.getType());
                    privilageAccountDOMapper.updateById(account);
                }

            }else{
                System.out.println("修改角色信息" + privilageUserRoleDO.toString());
                PrivilageUserRoleDO role = list.get(0);
                role.setUserId(privilageUserRoleDO.getUserId());
                role.setRoleId(privilageUserRoleDO.getRoleId());
                privilageUserRoleDOMapper.updateById(role);

                //创建账号,密码为账号加123
                PrivilageAccountDO acc = new PrivilageAccountDO();
                acc.setLogin(v.getAccount());
                acc.setPassword(MD5FileUtil.getMD5String(v.getAccount()+"123"));
                acc.setUserId(us.getId());
                acc.setType(1);
                acc.setStatus(1);
                acc.setCreateTime(new Date());
                acc.setUpdateTime(new Date());

                Map<String, Object> accountMap = new HashMap<>();
                accountMap.put("login", acc.getLogin());
                accountMap.put("user_id", acc.getUserId());
                accountMap.put("type", acc.getType());
                List<PrivilageAccountDO> accountList = privilageAccountDOMapper.selectByMap(accountMap);
                if(accountList.size() == 0){
                    System.out.println("insert" + acc.toString());
                    privilageAccountDOMapper.insert(acc);
                }else{
                    System.out.println("修改账号信息" + acc.toString());
                    PrivilageAccountDO account = accountList.get(0);
                    account.setLogin(acc.getLogin());
                    account.setUserId(acc.getUserId());
                    account.setType(acc.getType());
                    privilageAccountDOMapper.updateById(account);
                }
            }

        });
    }
    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:{
                    BigDecimal bd = new BigDecimal(cell.getNumericCellValue());//要修改的值，需要string类型
                    String phoneNumber=bd.setScale(0,BigDecimal.ROUND_HALF_UP).toPlainString();
                    cellValue = String.valueOf(phoneNumber);
                    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;
    }
}
