package com.sifang.modules.sunshine.SystemSetting.service;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.order.utils.excelExt.ExcelReader;
import com.sifang.modules.sunshine.SystemSetting.dao.LinkNumberSettingDao;
import com.sifang.modules.sunshine.SystemSetting.entity.CrmLinkNumberSetting;
import com.sifang.modules.sunshine.SystemSetting.handler.ExcelImportBankNumberHandler;
import com.sifang.modules.sunshine.SystemSetting.utils.BankNumberUtils;
import com.sifang.modules.sunshine.SystemSetting.utils.BusinessException;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.entity.User;
import com.sifang.modules.sys.common.service.BaseService;
import com.sifang.modules.sys.util.LayuiPage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class LinkNumberSettingService extends BaseService {

    @Autowired
    private LinkNumberSettingDao dao;

    /**
     * 获取设置列表
     */
    public List<Record> getList(Map<String, String> params, LayuiPage page) {
        List<Record> list = dao.findList(params, page);
        if (page != null) {
            page.setData(list);
            page.setCount(dao.queryCount(params));
        }
        return list;
    }

    /**
     * 根据联行号名称获取列表
     */
    public List<Record> getListByName(String name, String partner) {
        if (StringUtil.isBlank(name) || name.length() < 2) {
            return new ArrayList<>();
        }
        return dao.findBankList(name,partner);
    }

    /**
     * 获取设置列表
     */
    public void getPageList(Map<String, String> params, LayuiPage page) {
        page.setData(dao.findPageList(params, page));
        page.setCount(dao.queryCount(params));
    }

    /**
     * 查询变更类型设置详情
     */
    public Record getOneById(String id) {
        return dao.findOneById(id);
    }

    @Transactional(rollbackFor = Exception.class)
    public Result add(String bankName, String number,  Result result, String capitals) {
        // 校验名称
        long total = dao.queryCountByName(number, null);
        if (total > 0) {
            result.setCode("206");
            result.setMsg("已存在相同联行号，请重新设置");
            return result;
        }
        User user = UserUtils.getUser();
        CrmLinkNumberSetting set = new CrmLinkNumberSetting();
        set.setBankName(bankName);
        set.setNumber(number);
        set.setCapitals(capitals);
        set.setCreateBy(user.getId());
        set.setCreateTime(new Date());
        dao.save(set);
        result.setCode("200");
        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    public Result edit(String id, String bankName, String number, Result result, String capitals) {
        // 校验名称
        long total = dao.queryCountByName(number, id);
        if (total > 0) {
            result.setCode("206");
            result.setMsg("已存在相同联行号，请重新设置");
            return result;
        }
        CrmLinkNumberSetting set = dao.get(Integer.valueOf(id));
        set.setBankName(bankName);
        set.setNumber(number);
        set.setCapitals(capitals);
        set.setUpdateTime(new Date());
        dao.save(set);
        result.setCode("200");
        return result;
    }

    public void deleteById(String id) {
        dao.deleteById(id);
    }

    /**
     * 校验导入物料数据
     */
    @SuppressWarnings("unchecked")
    public Map<String, Object> checkImportBankNumber(Map<String, String> params, InputStream in) {
        Map<String, Object> retMap = Maps.newHashMap();
        retMap.put("operType", "check");
        ExcelImportBankNumberHandler handler=new ExcelImportBankNumberHandler();
        handler.setStartSheet(1);
        handler.setStartRow(1);
        try {
            new ExcelReader().check(in, params.get("extName"), handler);
            Map<String, Object> map = (Map<String, Object>) handler.getHandlerResult();
            String templateError = (String) map.get("TemplateError");
            if(!handler.isCheckFlag()){
                handler.appendErrorDetail("<p>未填充数据</p>");
            }
            List<String> codeslist = BankNumberUtils.findBankNumber();
            List<Map<String, Object>> list =handler.getRetList();
            int i =1;
            for(Map<String, Object> rowData :list){
                if (codeslist.contains(String.valueOf(rowData.get("2")))) {
                    handler.appendErrorDetail("第" + (i + 1) + "行联行号已存在");
                }
                i++;
            }
            String hanl = handler.getErrorDetail();
            if (StrKit.notBlank(templateError)){
                retMap.put("errorDetail", templateError);
                retMap.put("errorMessage", "y");
            }else if (StringUtils.isNotBlank(hanl)) {
                retMap.put("errorDetail", hanl);
                retMap.put("errorMessage", "y");
            } else if ("overLimit".equalsIgnoreCase((String) map.get("overLimit"))) {
                retMap.put("overLimit", "y");
            } else {
                retMap.put("pass", "y");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return retMap;
    }

    /**
     * 导入物料数据
     */
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> importBankNumber(Map<String, String> params, InputStream in) {
        Map<String, Object> retMap = Maps.newHashMap();
        retMap.put("operType", "import");
        ExcelImportBankNumberHandler handler=new ExcelImportBankNumberHandler();
        handler.setStartSheet(1);
        handler.setStartRow(2);
        User user = UserUtils.getUser();

        try {
            new ExcelReader().readExcel(in, params.get("fileName"), handler);

            List<Map<String, Object>> list =handler.getRetList();
            List<CrmLinkNumberSetting> maters = Lists.newArrayList();
            for(Map<String, Object> rowData :list){
                CrmLinkNumberSetting set = new CrmLinkNumberSetting();
                set.setBankName(String.valueOf(rowData.get("1")));
                String value=rowData.get("2").toString();
                value=value.replace(".0","");
                set.setNumber(value);
                String capitals = "";
                String str = rowData.get("3").toString();
                String[] arr = str.split(",");
                for(int i = 0;i<arr.length;i++){
                    if(arr[i].equals("广州越秀融资租赁有限公司")){
                        capitals+="01,";
                    }else if(arr[i].equals("华能")){
                        capitals+="02,";
                    }else if(arr[i].equals("广州发展新能源集团股份有限公司")){
                        capitals+="03,";
                    }else if(arr[i].equals("华融金融租赁股份有限公司")){
                        capitals+="04,";
                    }
                }
                capitals = capitals.substring(0,capitals.length()-1);
                set.setCapitals(capitals);
                set.setCreateBy(user.getId());
                set.setCreateTime(new Date());
                maters.add(set);
            }
            dao.save(maters);

            retMap.put("successCount", maters.size());
            retMap.put("pass", "y");
            retMap.put("materialList", handler.getRetList());
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(" 导入物料异常,e:{}",e);
            throw new BusinessException(e.getMessage());
        } finally {
            if(in != null){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return retMap;
    }

    public String findBankNUmberName(String number){
        return dao.findBankNUmberName(number);
    }
}
