package com.huigou.topsun.sap.suppliers.controller;

import com.huigou.cache.DictUtil;
import com.huigou.cache.SystemCache;
import com.huigou.context.Operator;
import com.huigou.topsun.common.CommonUtils;
import com.huigou.topsun.sap.suppliers.application.SuppliersDataApplication;
import com.huigou.topsun.sap.suppliers.domain.SuppliersBank;
import com.huigou.topsun.sap.suppliers.domain.SuppliersBuyer;
import com.huigou.topsun.sap.suppliers.domain.SuppliersInfo;
import com.huigou.topsun.sap.suppliers.domain.SuppliersPay;
import com.huigou.topsun.sap.suppliers.repository.SuppliersBankRepository;
import com.huigou.topsun.sap.suppliers.repository.SuppliersBuyerRepository;
import com.huigou.topsun.sap.suppliers.repository.SuppliersInfoRepository;
import com.huigou.topsun.sap.suppliers.repository.SuppliersPayRepository;
import com.huigou.topsun.util.CommonUtil;
import com.huigou.uasp.bmp.fn.CodeGenerator;
import com.huigou.uasp.bmp.operator.OperatorApplication;
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.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.beans.Transient;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

@Service("impDataFromXLS")
public class ImpDataFromXLS {

    @Autowired
    SuppliersInfoRepository suppliersInfoRepository;
    @Autowired
    SuppliersPayRepository suppliersPayRepository;
    @Autowired
    SuppliersBuyerRepository suppliersBuyerRepository;
    @Autowired
    SuppliersBankRepository suppliersBankRepository;
    @Resource
    private OperatorApplication operatorApplication;
    @Autowired
    private CodeGenerator codeGenerator;

    public static void main(String[] args) {
        ImpDataFromXLS obj=new ImpDataFromXLS();
        obj.readFile();
    }

  public void readFile() {

      String filePath = "E:\\供应商主数据模板0328-2.xlsx";
      InputStream fis = null;
      try {
          System.out.println("开始读取文件......" + new Date());
          fis = new FileInputStream(filePath);
          Workbook workbook = null;
          if (filePath.endsWith(".xlsx")) {
              workbook = new XSSFWorkbook(fis);
          } else if (filePath.endsWith(".xls") || filePath.endsWith(".et")) {
              workbook = new HSSFWorkbook(fis);
          }
          fis.close();
          // System.out.println("读取文件结束......"+new Date());
          /* 读EXCEL文字内容 */
          // 获取第一个sheet表，也可使用sheet表名获取
          Sheet sheet = workbook.getSheetAt(0);
          // 获取行
          Iterator<Row> rows = sheet.rowIterator();
          Row row;
          Cell cell;

          while (rows.hasNext()) {
              row = rows.next();
              System.out.println("行号:=" + row.getRowNum());
              // 获取单元格
              if (row.getRowNum() ==6) {
                  //
                  SuppliersInfo suppliersInfo = new SuppliersInfo();
                  suppliersInfo.setRltgr("Z00001X");
                  suppliersInfo.setApplyType("0");
                  suppliersInfo.setStatusId(3);
                 // suppliersInfo.setBillCode();
                  String createdById = SystemCache.getParameter("adminPersonId", String.class);
                  Operator operator = operatorApplication.createOperatorByPersonMemberId(createdById);
                  suppliersInfo.setFullId(operator.getFullId());
                  suppliersInfo.setPersonMemberId(createdById);
                  suppliersInfo.setPersonMemberName(operator.getPersonMemberName());
                  suppliersInfo.setFillinDate(new Date());
                  String nextCode = codeGenerator.getNextCode("sapSuppliersInfo");
                  suppliersInfo.setBillCode(nextCode);
                  suppliersInfo.setOrganId(operator.getOrgId());
                  suppliersInfo.setOrganName(operator.getOrgName());
                  suppliersInfo.setDeptName(operator.getDeptName());

                  SuppliersBank  bank=new SuppliersBank();
                  SuppliersBuyer buyer=new SuppliersBuyer();
                  SuppliersPay pay=new SuppliersPay();
                  Iterator<Cell> cells = row.cellIterator();
                  while (cells.hasNext()) {
                      cell = cells.next();
                      String cellValue = CommonUtils.getExcelCellValue(cell);
                      String num=transferNum(cell.getColumnIndex());
                      assembleData(suppliersInfo,bank,buyer,pay,num,cellValue);
                      System.out.print(num+ "=" + cellValue + " ");
                  }
                  saveData(suppliersInfo,bank,buyer,pay);
                  System.out.println();
              }
          }
      } catch (FileNotFoundException e) {
          e.printStackTrace();
      } catch (IOException e) {
          e.printStackTrace();
      } finally {
          if (null != fis) {
              try {
                  fis.close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
  }

  public void  assembleData(SuppliersInfo suppliersInfo,SuppliersBank bank,SuppliersBuyer buyer,SuppliersPay pay,String num,String value){
      switch (num) {
          case "A":
              suppliersInfo.setBuGroup(value);
              break;
           case "B":
              suppliersInfo.setPartner(value);
               break;
          case "C":
              suppliersInfo.setNameOrg1(value);
              break;
          case "D":
              suppliersInfo.setNameOrg2(value);
              break;
          case "E":
              suppliersInfo.setNameOrg3(value);
          case "F":
              suppliersInfo.setNameOrg4(value);
              break;
          case "G":
              suppliersInfo.setBuSort1(value);
              break;
          case "H":
              suppliersInfo.setBuSort2(value);
              break;
          case "I":
              suppliersInfo.setStreet(value);
              break;
          case "J":
              suppliersInfo.setStrSuppl1(value);
              break;
          case "K":
              suppliersInfo.setStrSuppl2(value);
              break;
          case "L":
              suppliersInfo.setStrSuppl3(value);
              break;
          case "M":
              break;
          case "N":
              suppliersInfo.setPostCode1(value);
              break;
          case "O":
              suppliersInfo.setCity1Name(value);  //城市名称
              break;
          case "P":
              suppliersInfo.setLand1Name(value);  //国家缺少编码   来自EasySearch
              String land=DictUtil.getDictionaryDetailValue("country",value);
              if (StringUtils.isBlank(land)){
                //  throw new RuntimeException("没有找到字典中的country的值"+value);
              }
              suppliersInfo.setLand1(land);
              break;
          case "Q":
              suppliersInfo.setRegionName(value); //地区缺少编码   来自 Sap 接口 EasySearch
            //  suppliersInfo.setRegion("");
              break;
          case "R":
              suppliersInfo.setLangu(value);
              break;
          case "S":
              suppliersInfo.setTelNumber(value);
              break;
          case "T":
              suppliersInfo.setMobNumber(value);
              break;
          case "U":
              suppliersInfo.setFaxNumber(value);
              break;
          case "V":
              suppliersInfo.setSmtpAddr(value);
              break;
          case "W":
              suppliersInfo.setStenr(value);
              break;
          case "X":
              bank.setBanks(value);  //银行所属国家/地区代码
              break;
          case "Y":
              bank.setBanka(value);  //银行名称
              break;
          case "Z":
              bank.setBankl(value);  //银行代码
              break;
          case "AA":
              bank.setBankn(value);  //银行账号
              break;
          case "AB":
              bank.setBkref(value);  //银行细目的参考明细
              break;
          case "AC":
              buyer.setEkorg(value); //采购组织需要提供编码
              String orgbm=DictUtil.getDictionaryDetailValue("ekorg",value);
              buyer.setEkorg(orgbm);
              break;
          case "AD":
              buyer.setWaers(value);
              break;
          case "AE":
              buyer.setPayCondition(value);  //采购付款条件 提供编码
              String ztermbm=DictUtil.getDictionaryDetailValue("zterm",value);
              buyer.setPayCondition(ztermbm);
              break;
          case "AF":
              buyer.setVerkf(value);
              break;
          case "AG":
              buyer.setLebre(value);    //基于收货发票校验
              break;
          case "AH":    //采购组 ？？
              break;
          case "AI":   //定价方案组  ？？
              break;
          case "AJ":
              pay.setBukrs(value); //公司代码
              break;
          case "AK":
              pay.setAkont(value);  //统驭科目
              break;
          case "AL":
              pay.setZuawa(value);
              break;
          case "AM":
              pay.setZterm(value);  //财务结算付款条件
              String ztmbm=DictUtil.getDictionaryDetailValue("zterm",value);
              pay.setZterm(ztmbm);
              break;
          case "AN":    //支付容差组  ？
              break;
          case "AO":    //检查双重发票
              pay.setReprf(value);
              break;
          case "AP":
              pay.setZwels(value);     //支付方式
              String bzwels=DictUtil.getDictionaryDetailValue("zwels",value);
              pay.setZwels(bzwels);
              break;
          case "AQ":    //发票校验容差组  ？
              break;
          default:
              break;
      }


  }
    @Transactional
  public void saveData(SuppliersInfo suppliersInfo,SuppliersBank bank,SuppliersBuyer buyer,SuppliersPay pay){
      try {
          List<SuppliersInfo> list=suppliersInfoRepository.findByPartner(suppliersInfo.getPartner());
          if (list.size()>0){
              suppliersInfo=list.get(0);
          } else {
              suppliersInfo = suppliersInfoRepository.save(suppliersInfo);
          }
          if (StringUtils.isNotBlank(bank.getBankn())){ //银行代码存在
              if (suppliersBankRepository.findByBankn(bank.getBankn()).size()<1) {
                  bank.setSId(suppliersInfo.getId());
                  suppliersBankRepository.save(bank);
              }
          }
          if (StringUtils.isNotBlank(buyer.getEkorg())) { //采购组织存在
              buyer.setSId(suppliersInfo.getId());
              suppliersBuyerRepository.save(buyer);
          }
          if (StringUtils.isNotBlank(pay.getBukrs())) { //公司代码
              pay.setSId(suppliersInfo.getId());
              suppliersPayRepository.save(pay);
          }

      } catch (Exception ex) {
          ex.printStackTrace();
      }
  }
  public String transferNum(int cellIndex ){
      cellIndex+=65;
      char c=(char)cellIndex;
      String num=String.valueOf(c);
      if (cellIndex>=91){
          char c2=(char)(cellIndex-26);
          num="A"+String.valueOf(c2);
      }
      if (cellIndex>=117){
          char c3=(char)(cellIndex-52);
          num="B"+String.valueOf(c3);
      }
      if (cellIndex>=143){
          char c4=(char)(cellIndex-78);
          num="C"+String.valueOf(c4);
      }
      if (cellIndex>=169){
          char c5=(char)(cellIndex-104);
          num="D"+String.valueOf(c5);
      }
     // System.out.println("num===="+num);
      return num;
  }

}
