package com.sifang.modules.supply.warehouse.service;

import com.google.common.collect.Maps;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.order.utils.excelExt.ExcelReader;
import com.sifang.modules.sunshine.SystemSetting.utils.Result;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.supply.handler.BarcodeExcelImportHandler;
import com.sifang.modules.supply.warehouse.dao.CrmSupplyBarcodeDao;
import com.sifang.modules.supply.warehouse.entity.CrmSupplyBarcode;
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 com.sifang.modules.sys.util.SqlBuilder;
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.*;

@Service
public class CrmSupplyBarcodeService extends BaseService {

    @Autowired
    private CrmSupplyBarcodeDao crmSupplyBarcodeDao;


    public void barcodeDataList(LayuiPage<Record> page, Map<String, String> map) {
        List<Record> list = crmSupplyBarcodeDao.getList(page, map);
        Long count = crmSupplyBarcodeDao.countList(map);
        page.setData(list);
        page.setCount(count);
    }


    /**
     * 校验导入条码数据
     */
    @SuppressWarnings("unchecked")
    public Map<String, Object> checkImportBarcode(Map<String, String> params, InputStream in) {
        Map<String, Object> resultMap = Maps.newHashMap();
        resultMap.put("operType", "check");
        BarcodeExcelImportHandler handler = new BarcodeExcelImportHandler();
        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 errorMsg = (String) map.get("TemplateError");
            if (!handler.isCheckFlag()) {
                handler.appendErrorDetail("<p>未填充数据</p>");
            }
            List<String> existsCode = findExistsCode("");
            List<CrmSupplyBarcode> retList = handler.getRetList();
            Set<String> existCodeSet = new HashSet<>(existsCode);
            int i = 1;
            for(CrmSupplyBarcode crmSupplyBarcode :retList){
                if(!existCodeSet.add(crmSupplyBarcode.getMaterialBarcode())){
                    handler.appendErrorDetail("第" + (i + 1) + "行物料条码已存在</p>");
                }
                i++;
            }
            String errorDetail = handler.getErrorDetail();
            if (StringUtils.isNotBlank(errorMsg)) {
                resultMap.put("errorDetail", errorMsg);
                resultMap.put("errorMessage", "y");
            } else if (StringUtils.isNotBlank(errorDetail)) {
                resultMap.put("errorDetail", errorDetail);
                resultMap.put("errorMessage", "y");
            } else if ("overLimit".equalsIgnoreCase((String) map.get("overLimit"))) {
                resultMap.put("overLimit", "y");
            } else {
                resultMap.put("pass", "y");
            }
        } catch (Exception e) {
            resultMap.put("errorDetail", "系统出错啦~");
            resultMap.put("errorMessage", "y");
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultMap;
    }

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

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

            retMap.put("pass", "y");
            List<CrmSupplyBarcode> exeSqlParams = handler.getRetList();
            if (exeSqlParams != null && exeSqlParams.size() > 0) {
                importProjectContract(exeSqlParams);
            }
            retMap.put("successCount", exeSqlParams.size());//成功条数
        } catch (Exception e) {
            e.printStackTrace();
            retMap.put("pass", "no");
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return retMap;
    }

    public Result importProjectContract(List<CrmSupplyBarcode> paramList) {
        Date time = new Date();
        User user = UserUtils.getUser();
        for (CrmSupplyBarcode item : paramList) {
            item.setCreateBy(user.getId());
            item.setCreateTime(time);
            item.setStatus("0");
            item.setBarcodeStatus("2");
        }
        crmSupplyBarcodeDao.save(paramList);
        return Result.ok();
    }

    public List<String> findExistsCode(String status) {
        SqlBuilder builder = new SqlBuilder();
        builder.line("SELECT material_barcode")
                .line("from crm_supply_barcode")
                .line("where 1=1");
        return Db.query(builder.build());
    }
    @Transactional(rollbackFor = Exception.class)
    public void deletePlan(String planIds) {
        String[] idStr = planIds.split(",");
        SqlBuilder builder = new SqlBuilder();
        builder.line("insert into crm_supply_barcode_del");
        builder.line("select md5(uuid()),material_id,material_barcode,barcode_status,batch_Code,batch_Code_note,now(), ? ", UserUtils.getUser().getId());
        builder.line("from crm_supply_barcode ");
        if (idStr.length > 1) {
            builder.inst("where id in ", idStr);
        }
        else {
            builder.line("where id = ?", idStr[0]);
        }
        Db.update(builder.build(), builder.params());
        Db.update("delete from crm_supply_barcode where id in (" + StringUtil.joinInSql(idStr)+ ")");
    }
}