package com.steerinfo.ems.emsgmpcjh.service.impl;

import com.steerinfo.ems.Utils.DateUtils;
import com.steerinfo.ems.Utils.ExcelToolUtils;
import com.steerinfo.ems.Utils.MarketSlmException;
import com.steerinfo.ems.emsgmpcjh.mapper.EmsGmPcJhMapper;
import com.steerinfo.ems.emsgmpcjh.model.EmsGmPcJh;
import com.steerinfo.ems.emsgmpcjh.service.IEmsGmPcJhService;
import com.steerinfo.ems.emsprodplanweightadjustment.mapper.EmsProdplanWeightAdjustmentMapper;
import com.steerinfo.ems.emsprodplanweightadjustment.model.EmsProdplanWeightAdjustment;
import com.steerinfo.framework.controller.RESTfulResult;
import com.steerinfo.framework.mapper.IBaseMapper;
import com.steerinfo.framework.service.impl.BaseServiceImpl;
import com.steerinfo.framework.service.pagehelper.PageHelper;
import com.steerinfo.framework.service.pagehelper.PageList;
import com.steerinfo.framework.user.UserPayload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;

/**
 * EmsGmPcJh服务实现：
 * @author generator
 * @version 1.0-SNAPSHORT 2021-09-11 03:49
 * 类描述
 * 修订历史：
 * 日期：2021-09-11
 * 作者：generator
 * 参考：
 * 描述：EmsGmPcJh服务实现
 * @see null
 * @Copyright 湖南视拓信息技术股份有限公司. All rights reserved.
 */
@Service(value = "emsGmPcJhService")
public class EmsGmPcJhServiceImpl extends BaseServiceImpl<EmsGmPcJh, String> implements IEmsGmPcJhService {

    @Autowired
    private EmsGmPcJhMapper emsGmPcJhMapper;

    @Autowired
    private EmsProdplanWeightAdjustmentMapper emsProdplanWeightAdjustmentMapper;
    @Override
    protected IBaseMapper<EmsGmPcJh, String> getMapper() {
        return emsGmPcJhMapper;
    }

    @Override
    public String getMaxid(EmsGmPcJh emsGmPcJh) {
        return emsGmPcJhMapper.getMaxid(emsGmPcJh);
    }

    @Override
    public int updateState(EmsGmPcJh emsGmPcJh) {
        return emsGmPcJhMapper.updateState(emsGmPcJh);
    }

    @Override
    public PageList<Map<String, Object>> getGmPcJhDataForPage(HashMap<String, Object> parmas, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Map<String, Object>> gmPcJhData = emsGmPcJhMapper.getGmPcJhData(parmas);
        PageList<Map<String,Object>> plist = new PageList<Map<String,Object>>(gmPcJhData);
        return plist;
    }

    @Override
    public PageList<Map<String, Object>> getXsDdDate(HashMap<String, Object> parmas, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Map<String, Object>> xsDdDate = emsGmPcJhMapper.getXsDdDate(parmas);
        PageList<Map<String,Object>> plist = new PageList<Map<String,Object>>(xsDdDate);
        return plist;
    }
    @Override
    public PageList<Map<String, Object>> getXsShData(HashMap<String, Object> parmas, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Map<String, Object>> shData = emsGmPcJhMapper.getShData(parmas);
        PageList<Map<String,Object>> plist = new PageList<Map<String,Object>>(shData);
        return plist;
    }

    @Override
    public RESTfulResult insertexcel(File file) throws Exception {
        RESTfulResult rs = new RESTfulResult("200", "数据导入成功，不规范数据已自动剔除");
        rs.setCode("200");
        List<EmsGmPcJh> lsp = null;
        try {
            lsp = createCheckCar(file);
            if (lsp.size()>0)
            {
                int spm = emsGmPcJhMapper.batchInsert(lsp);
                if (spm > 0) {
                    rs.setData(spm);
                    EmsProdplanWeightAdjustment emsProdplanWeightAdjustment ;
                    for (EmsGmPcJh emsGmPcJh : lsp) {
                        emsProdplanWeightAdjustment = new EmsProdplanWeightAdjustment();
                        emsProdplanWeightAdjustment.setId(emsGmPcJh.getId());
                        emsProdplanWeightAdjustment.setAuditStatus("0");
                        emsProdplanWeightAdjustment.setPlanWeight(emsGmPcJh.getPlanWeight());
                        emsProdplanWeightAdjustment.setPlanWeightOld(emsGmPcJh.getPlanWeight());
                        emsProdplanWeightAdjustmentMapper.insert(emsProdplanWeightAdjustment);
                    }
                } else {
                    rs.setMessage("导入失败");
                    rs.setCode("500");
                }
            }
            else
            {
                rs.setMessage("导入失败,导入数据已经存在！");
                rs.setCode("500");
            }
        } catch (Exception e) {
            e.printStackTrace();
            rs.setCode("500");
            rs.setMessage(e.getMessage());
        } finally {

        }
        return rs;
    }

    public  List<EmsGmPcJh> createCheckCar(File file ) throws Exception, IOException {
        UserPayload payload = UserPayload.getCurrUser();
        FileInputStream is = null;
        String fileName = file.getName();
        // 解决fileName兼容性问题
        int lastindex = fileName.lastIndexOf("\\");
        fileName = fileName.substring(lastindex + 1);
        List<EmsGmPcJh> lists = new ArrayList<>();
        if (fileName != null && fileName.length() > 0) {
            is = new FileInputStream(file);
        }
        List<String[]> list = ExcelToolUtils.parseExcel(is, fileName, 0);

        // SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
        String name = fileName.substring(2, 4);
        for (int i = 1; i < list.size(); i++) {
            String[] arr = list.get(i);
            String[] arr1 = list.get(0);

            //String steel = emsGmPcJhMapper.selectsteelcode(arr[1], arr[0]);
            //
            //String heat = emsGmPcJhMapper.selectheatno(arr[0]);

            EmsGmPcJh spp = new EmsGmPcJh();
            ////查询是已经有数据了，有数据不执行导入功能
            //String v1 = emsGmPcJhMapper.select4(arr[0]);
            //if (Integer.valueOf(v1)>0) {
            //    continue;
            //}
            //AT2005 = "G-G1-";
            //AT2006 = "G-G2-";
            //AT2004 = "G-L1-";
            //AT2007 = "G-X1-";
            //Pattern pattern = Pattern.compile("^-?[0-9]+"); //这个也行
            //Pattern pattern = Pattern.compile("^-?\\d+(\\.\\d+)?$");//这个也行
            //正整数
            Pattern pattern = Pattern.compile("[0-9]*");
            if(arr[0].length()>8 || !pattern.matcher(arr[0]).matches()){
                throw new MarketSlmException(500,"排产日期(编号)有误！");
            }
            StringBuffer s=new StringBuffer(arr[0]).insert(4,"-").insert(7,"-");
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            simpleDateFormat.setLenient(false);
            spp.setJhTime(simpleDateFormat.parse(s.toString()));
            spp.setStartTime(arr[0]);
            switch (name) {
                case "型钢" :
                    if(arr[1].contains("一")){
                        spp.setType("G-X1-");
                        spp.setWorkprocType("AT2007");
                    } else {
                        spp.setType("G-X2-");
                    }
                    break;
                case "钢坯" :
                    spp.setType("G-L1-");
                    spp.setWorkprocType("AT2004");
                break;
                case "高线" :
                    if(arr[1].contains("一")){
                        spp.setType("G-G1-");
                        spp.setWorkprocType("AT2005");
                    } else {
                        spp.setType("G-G2-");
                        spp.setWorkprocType("AT2006");
                    }
                    break;
                default: throw new Exception("请选择模板文件");
            }
            String maxid = emsGmPcJhMapper.getMaxid(spp);
            String strh =maxid.substring(maxid.length() -2,maxid.length());
            Integer seq = Integer.parseInt(strh)+(i-1);
            spp.setId(maxid.replace(strh,seq<10?"0"+seq.toString():seq.toString()));
            spp.setState("0");
            spp.setCreateMan(payload.getUserName());
            spp.setCreateTime(new Date());
            spp.setUnitid("008");
            for(int j =1;j<arr1.length;j++) {
                switch (arr1[j].trim()) {
                    case "规格" :
                            spp.setSpecifications(arr[j]);
                        break;
                    case "钢种" :
                        spp.setGrades(arr[j]);
                        break;
                    case "长度" :
                        spp.setLengths(new BigDecimal(arr[j]));
                        break;
                    case "运输方式" :
                        spp.setTransportType(arr[j]);
                        break;
                    case "用途" :
                        spp.setPurpose(arr[j]);
                        break;
                    case "订单量" :
                        if(!pattern.matcher(arr[j]).matches()){
                            throw new MarketSlmException(500,"订单量有误，请仔细检查");
                        }
                        spp.setKxfWeight(new BigDecimal(arr[j]));
                        spp.setYxfWeight(new BigDecimal("0"));
                        spp.setPlanWeight(new BigDecimal(arr[j]));
                        break;
                    case "交货日期" :
                        spp.setDeliveryDate(simpleDateFormat.parse(arr[j]));
                        break;
                    case "备注" :
                        spp.setMemo(arr[j]);
                        break;
                    case "分厂" : continue;
                    default:
                        throw new MarketSlmException(500,"模板文件存在模板外的列，请仔细检查！！");
                }
            }
            //spp.setSteelCode(steel);
            //spp.setHeatno(heat);
            //for (int j=2;j<10;j++)
            //{
            //    if (arr1[j].equals("屈服强度ReH"))
            //    {
            //        spp.setQltyVal1(arr[j]);
            //        spp.setQltyCfnm("屈服强度R(eH)");
            //        spp.setQltyCd("qy0001");
            //        List<Map<String,Object>> rows = qcmQltyJudgeMapper.selectstd(spp.getSteelCode(), spp.getQltyCd());
            //        if(rows.size()>0)
            //        {
            //            if(rows.get(0).get("QLTY_MIN")!=null)
            //            {
            //                spp.setQltyMin(rows.get(0).get("QLTY_MIN").toString());
            //            }
            //            if(rows.get(0).get("QLTY_MAX")!=null)
            //            {
            //                spp.setQltyMax(rows.get(0).get("QLTY_MAX").toString());
            //            }
            //        }
            //        EmsGmPcJh spp1 = new EmsGmPcJh();
            //        BeanUtils.copyProperties(spp,spp1);
            //        lists.add(spp1);
            //    }
            //    if (arr1[j].equals("屈服强度ReL"))
            //    {
            //        spp.setQltyVal1(arr[j]);
            //        spp.setQltyCfnm("屈服强度R(eL)");
            //        spp.setQltyCd("qy0002");
            //        List<Map<String,Object>> rows = qcmQltyJudgeMapper.selectstd(spp.getSteelCode(), spp.getQltyCd());
            //        if(rows!=null&&!"".equals(rows.toString()))
            //        {
            //            if(rows.get(0).get("QLTY_MIN")!=null)
            //            {
            //                spp.setQltyMin(rows.get(0).get("QLTY_MIN").toString());
            //            }
            //            if(rows.get(0).get("QLTY_MIN")!=null)
            //            {
            //                spp.setQltyMax(rows.get(0).get("QLTY_MAX").toString());
            //            }
            //        }
            //        EmsGmPcJh spp1 = new EmsGmPcJh();
            //        BeanUtils.copyProperties(spp,spp1);
            //        lists.add(spp1);
            //    }
            //    if (arr1[j].equals("抗拉强度Rm"))
            //    {
            //        spp.setQltyVal1(arr[j]);
            //        spp.setQltyCfnm("抗拉强度Rm");
            //        spp.setQltyCd("qy0003");
            //        List<Map<String,Object>> rows = qcmQltyJudgeMapper.selectstd(spp.getSteelCode(), spp.getQltyCd());
            //        if(rows.get(0).get("QLTY_MIN")!=null)
            //        {
            //            spp.setQltyMin(rows.get(0).get("QLTY_MIN").toString());
            //        }
            //        if(rows.get(0).get("QLTY_MAX")!=null)
            //        {
            //            spp.setQltyMax(rows.get(0).get("QLTY_MAX").toString());
            //        }
            //        EmsGmPcJh spp1 = new EmsGmPcJh();
            //        BeanUtils.copyProperties(spp,spp1);
            //        lists.add(spp1);
            //    }
            //
            //    if (arr1[j].equals("断后伸长率%"))
            //    {
            //        spp.setQltyVal1(arr[j]);
            //        spp.setQltyCfnm("断后伸长率%");
            //        spp.setQltyCd("qy0004");
            //        List<Map<String,Object>> rows = qcmQltyJudgeMapper.selectstd(spp.getSteelCode(), spp.getQltyCd());
            //        if(rows.get(0).get("QLTY_MIN")!=null)
            //        {
            //            spp.setQltyMin(rows.get(0).get("QLTY_MIN").toString());
            //        }
            //        if(rows.get(0).get("QLTY_MAX")!=null)
            //        {
            //            spp.setQltyMax(rows.get(0).get("QLTY_MAX").toString());
            //        }
            //        EmsGmPcJh spp1 = new EmsGmPcJh();
            //        BeanUtils.copyProperties(spp,spp1);
            //        lists.add(spp1);
            //    }
            //
            //    if (arr1[j].equals("冲击试验温度"))
            //    {
            //        spp.setQltyVal1(arr[j]);
            //        spp.setQltyCfnm("冲击试验温度");
            //        spp.setQltyCd("qy0005");
            //        List<Map<String,Object>> rows = qcmQltyJudgeMapper.selectstd(spp.getSteelCode(), spp.getQltyCd());
            //        if(rows.get(0).get("QLTY_MIN")!=null)
            //        {
            //            spp.setQltyMin(rows.get(0).get("QLTY_MIN").toString());
            //        }
            //        if(rows.get(0).get("QLTY_MAX")!=null)
            //        {
            //            spp.setQltyMax(rows.get(0).get("QLTY_MAX").toString());
            //        }
            //        EmsGmPcJh spp1 = new EmsGmPcJh();
            //        BeanUtils.copyProperties(spp,spp1);
            //        lists.add(spp1);
            //    }
            //    if (arr1[j].equals("冷弯"))
            //    {
            //        spp.setQltyVal1(arr[j]);
            //        spp.setQltyCfnm("冷弯");
            //        spp.setQltyCd("qy0009");
            //        List<Map<String,Object>> rows = qcmQltyJudgeMapper.selectstd(spp.getSteelCode(), spp.getQltyCd());
            //        if(rows.get(0).get("QLTY_MIN")!=null)
            //        {
            //            spp.setQltyMin(rows.get(0).get("QLTY_MIN").toString());
            //        }
            //        if(rows.get(0).get("QLTY_MAX")!=null)
            //        {
            //            spp.setQltyMax(rows.get(0).get("QLTY_MAX").toString());
            //        }
            //        EmsGmPcJh spp1 = new EmsGmPcJh();
            //        BeanUtils.copyProperties(spp,spp1);
            //        lists.add(spp1);
            //    }
            //    if (arr1[j].equals("冲击吸收功J1"))
            //    {
            //        spp.setQltyVal1(arr[j]);
            //        spp.setQltyVal2(arr[j+1]);
            //        spp.setQltyVal3(arr[j+2]);
            //        spp.setQltyCfnm("冲击");
            //        spp.setQltyCd("qy0006");
            //        List<Map<String,Object>> rows = qcmQltyJudgeMapper.selectstd(spp.getSteelCode(), spp.getQltyCd());
            //        if(rows.get(0).get("QLTY_MIN")!=null)
            //        {
            //            spp.setQltyMin(rows.get(0).get("QLTY_MIN").toString());
            //        }
            //        if(rows.get(0).get("QLTY_MAX")!=null)
            //        {
            //            spp.setQltyMax(rows.get(0).get("QLTY_MAX").toString());
            //        }
            //        EmsGmPcJh spp1 = new EmsGmPcJh();
            //        BeanUtils.copyProperties(spp,spp1);
            //        lists.add(spp1);
            //    }

            //}
            lists.add(spp);
        }
        } catch (Exception e){
            throw new MarketSlmException (500,"导入失败，请检查文档中是否有错误数据。");
        }
        return lists;
    }
    //每个月自动生成内部计划
    public void addNbjh(){
        EmsGmPcJh emsGmPcJh = new EmsGmPcJh();
        ArrayList<String> ls =  new ArrayList<>();
        ls.add("N-G1-");
        ls.add("N-G2-");
        ls.add("N-X1-");
        ls.add("N-L1-");
        String s = DateUtils.dateStr(new Date(), "yyyy-MM-dd");
        DateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
        try {
            for (String l : ls) {
                l+= DateUtils.dateStr(new Date(),"yyyyMM")+"00-00";
                emsGmPcJh.setPlanWeight(new BigDecimal("99999"));
                emsGmPcJh.setKxfWeight(new BigDecimal("99999"));
                emsGmPcJh.setYxfWeight(new BigDecimal("0"));
                emsGmPcJh.setWorkprocType(this.setWorkprocType(l));
                emsGmPcJh.setJhTime(dateFormat1.parse(s));
                emsGmPcJh.setId(l);
                emsGmPcJh.setState("2");
                emsGmPcJhMapper.insert(emsGmPcJh);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String setWorkprocType(String str){
        if (str.contains("N-G1-")){
            return "AT2005";
        }
        if (str.contains("N-G2-")){
            return "AT2006";
        }
        if (str.contains("N-X1-")) {
            return "AT2007";
        }
        if (str.contains("N-L1-")) {
            return "AT2004";
        }
        return null;
    }

    public static void main(String[] args) throws ParseException {
//
//        System.out.println(myDate1);
        DateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
        Date myDate1 = dateFormat1.parse("2009-06-01");
        System.out.println(myDate1);
    }
}
