package main

import (
	dalBase "LAPP_ACURA_MOM_BACKEND/dao/base"
	dalJit "LAPP_ACURA_MOM_BACKEND/dao/jit"
	"LAPP_ACURA_MOM_BACKEND/etl_task/model"
	"LAPP_ACURA_MOM_BACKEND/grmi"
	meta "LAPP_ACURA_MOM_BACKEND/meta/base"
	metaJit "LAPP_ACURA_MOM_BACKEND/meta/jit"
	modelJit "LAPP_ACURA_MOM_BACKEND/models/jit"
	"LAPP_ACURA_MOM_BACKEND/utils"
	"fmt"
	_ "github.com/denisenkom/go-mssqldb"
	_ "github.com/go-sql-driver/mysql"
	"github.com/go-xorm/xorm"
	"golang.org/x/text/encoding/simplifiedchinese"
	"golang.org/x/text/transform"
	"io/ioutil"
	"os"
	"path"
	"strconv"
	"strings"
	"time"
)

//BackFlushPackOrder.exe "server=101.201.121.115;database=LAPP_ACURA_MES;user id=sa;password=Leit2020;port=1433;encrypt=disable" "LAPP_ACURA_MES" "server=101.201.121.115;database=LAPP_ETL2;user id=sa;password=Leit2020;port=1433;encrypt=disable" "LAPP_ETL2" "97"


func main() {
	var err error
	baseDir, err := utils.GetCurrentPath(".")
	if err != nil {
		fmt.Printf("获取当前文件路径失败, error:" + err.Error())
		return
	}
	var plantNr = 100
	var userId = "backFlush"
	now := time.Now()
	year, month, day := now.Date()
	hour := now.Hour()
	minute := now.Minute()
	second := now.Second()
	// init global location time zone
	utils.TimezoneLocation, err = time.LoadLocation("Asia/Shanghai")
	if err != nil {
		fmt.Println("初始化时区错误:" + err.Error())
		return
	}
	if len(os.Args) < 5 {
		fmt.Println("参数长度错误!")
		return
	}
	var acuraDsn = os.Args[1]
	var etlDsn = os.Args[3]
	taskId, err := strconv.Atoi(os.Args[5])
	if err != nil {
		fmt.Println("接收到的taskId错误, taskId:" + os.Args[5])
		return
	}
	// 初始化数据库连接
	etlDB, err := xorm.NewEngine("mssql", etlDsn)
	if err != nil {
		fmt.Println("初始化etl数据库引擎错误:" + err.Error())
		return
	}
	err = etlDB.Ping()
	if err != nil {
		fmt.Println("连接ETL数据库失败, error:" + err.Error())
		return
	}
	acraDB, err := xorm.NewEngine("mssql", acuraDsn)
	if err != nil {
		fmt.Println("初始化讴歌数据库引擎错误:" + err.Error())
		return
	}
	err = acraDB.Ping()
	if err != nil {
		fmt.Println("连接讴歌数据库失败, error:" + err.Error())
		return
	}
	//acraDB.ShowSQL(true)
	// 从etl数据库中获取参数
	var index4, index5, index6, index7, index8 string

	var dir string
	etlSession := etlDB.NewSession()
	shellParamLi := make([]model.ShellParam, 0)
	err = etlSession.Table("ShellParam").Where("TaskId = ?", taskId).Find(&shellParamLi)
	if err != nil {
		fmt.Println("查询任务需要参数失败, error:" + err.Error())
		return
	}
	for _, param := range shellParamLi {
		switch param.ParamName {
		case "index4":
			index4 = param.ParamValue
		case "index5":
			index5 = param.ParamValue
		case "index6":
			index6 = param.ParamValue
		case "index7":
			index7 = param.ParamValue
		case "index8":
			index8 = param.ParamValue
		case "path":
			dir = param.ParamValue
		}
	}
	// index4编码转换
	tempReader := transform.NewReader(strings.NewReader(index4), simplifiedchinese.GBK.NewEncoder())
	tempBytes, err := ioutil.ReadAll(tempReader)
	if err != nil {
		fmt.Println("转码失败, 错误:" + err.Error())
		return
	}
	index4 = string(tempBytes)
	// index5编码转换
	tempReader = transform.NewReader(strings.NewReader(index5), simplifiedchinese.GBK.NewEncoder())
	tempBytes, err = ioutil.ReadAll(tempReader)
	if err != nil {
		fmt.Println("转码失败, 错误:" + err.Error())
		return
	}
	index5 = string(tempBytes)
	// index6 编码转换
	tempReader = transform.NewReader(strings.NewReader(index6), simplifiedchinese.GBK.NewEncoder())
	tempBytes, err = ioutil.ReadAll(tempReader)
	if err != nil {
		fmt.Println("转码失败, 错误:" + err.Error())
		return
	}
	index6 = string(tempBytes)
	// index7 编码转换
	tempReader = transform.NewReader(strings.NewReader(index7), simplifiedchinese.GBK.NewEncoder())
	tempBytes, err = ioutil.ReadAll(tempReader)
	if err != nil {
		fmt.Println("转码失败, 错误:" + err.Error())
		return
	}
	index7 = string(tempBytes)
	// index8 编码转换
	tempReader = transform.NewReader(strings.NewReader(index8), simplifiedchinese.GBK.NewEncoder())
	tempBytes, err = ioutil.ReadAll(tempReader)
	if err != nil {
		fmt.Println("转码失败, 错误:" + err.Error())
		return
	}
	index8 = string(tempBytes)
	dir = path.Join(baseDir, dir)
	filename := "lctr" + fmt.Sprintf("%d%02d%02d%d", year, int(month), day, 3600*hour+60*minute+second) + "ACURA.dat"
	filepath := path.Join(dir, filename)
	acuraSession := acraDB.NewSession()
	daoShipOrderStatus := dalJit.NewShipOrderStatusDAO(acuraSession, plantNr, userId)
	daoShipOrderDataItem := dalJit.NewShipOrderDataLstDAO(acuraSession, plantNr, userId)
	daoPackOrderItem := dalJit.NewPackOrderItemLstDAO(acuraSession, plantNr, userId)
	daoArticle := dalBase.NewArticleDAO(acuraSession, plantNr, userId)
	// 查询正式发运单 关单 且 未回冲的所有发运单数据
	shipOrderDataLi, err := daoShipOrderStatus.SelectUnBackFlushedShipOrder()
	if err != nil {
		fmt.Println("查询未回冲的发运单失败, error:" + err.Error())
		return
	}
	// 如果没有数据 则完成本次任务
	if len(shipOrderDataLi) == 0 {
		fmt.Println("OK")
		return
	}

	shipOrderIdLi := make([]interface{}, len(shipOrderDataLi))
	waitWriteLi := make([]string, 0)
	for _, shipOrderData := range shipOrderDataLi {

		artQtyMap := make(map[string]int)
		artErpQtyMap := make(map[string]int, len(artQtyMap))
		// 查询发运单下的发运数据项 获取到包装单id
		shipOrderId := shipOrderData.ShipOrder.ShipOrderId
		shipOrderIdLi = append(shipOrderIdLi, shipOrderId)
		packOrderDataLi, err := daoShipOrderDataItem.SelectCols([]grmi.Predicate{metaJit.ShipOrderDataLst_ShipOrderId.NewPredicate(grmi.Equal, shipOrderId)}, nil, []string{metaJit.ShipOrderDataLst_PackOrderId.Name})
		if err != nil {
			fmt.Println("查询发运单数据项失败, error:" + err.Error())
			return
		}
		packOrderIdLi := make([]interface{}, 0, len(packOrderDataLi))
		for _, packOrderData := range packOrderDataLi {
			packOrderId, exist := packOrderData[metaJit.ShipOrderDataLst_PackOrderId.Name]
			if exist {
				packOrderIdLi = append(packOrderIdLi, packOrderId)
			} else {
				fmt.Println("查询发运单子项未查询到包装单ID字段")
				return
			}
		}
		packOrderItemLi, err := daoPackOrderItem.Select([]grmi.Predicate{metaJit.PackOrderItemLst_PackOrderId.NewPredicate(grmi.Include, packOrderIdLi...)}, nil)
		if err != nil {
			fmt.Println("查询包装单子项失败, error:" + err.Error())
			return
		}
		for _, packOrderItem := range packOrderItemLi {
			_, exist := artQtyMap[packOrderItem.PartId]
			if !exist {
				artQtyMap[packOrderItem.PartId] = 1
			} else {
				artQtyMap[packOrderItem.PartId] += 1
			}
		}
		for artId, qty := range artQtyMap {
			//article, err := daoArticle.SelectOne(artId)
			articleLi, err := daoArticle.Select([]grmi.Predicate{meta.Article_ArtId.NewPredicate(grmi.Equal, artId)}, nil)
			if err != nil {
				fmt.Println("查询物料数据失败, error:" + err.Error())
				return
			}
			if len(articleLi) == 0 {
				_ = acuraSession.Rollback()
				fmt.Println("物料不存在, 物料ID:" + artId)
				return
			}
			article := articleLi[0]
			if article.ArtSpec3 == "" {
				fmt.Println("物料的ERP零件号为空, 物料ID:" + artId)
				return
			}
			artErpQtyMap[artId] = qty
		}
		var pos = 1
		for artId, qty := range artErpQtyMap {
			index1 := artId
			index2 := strconv.Itoa(qty)
			index3 := now.Format("01/02/06")
			str := fmt.Sprintf(`"%s",%s,%s,"%s","%s","%s","%s","%s","%s",%s,`,
				index1,
				index2,
				index3,
				index4,
				index5,
				index6,
				index7,
				index8,
				shipOrderId,
				strconv.Itoa(pos),
				)
			//str := []string{index1, index2, index3, index4, index5, index6, index7, index8, shipOrderId, strconv.Itoa(pos), "\n"} //需要写入csv的数据，切片类型
			pos++
			waitWriteLi = append(waitWriteLi, str)
		}
	}

	if err = acuraSession.Begin(); err != nil {
		fmt.Println("开启事务失败, error:" + err.Error())
		return
	}
	updateData := modelJit.ShipOrderStatus{BackFlushedToggle: true}
	err = daoShipOrderStatus.UpdateWhere([]grmi.Predicate{metaJit.ShipOrderStatus_ShipOrderId.NewPredicate(grmi.Include, shipOrderIdLi...)}, &updateData, metaJit.ShipOrderStatus_BackFlushedToggle.Name)
	if err != nil {
		_ = acuraSession.Rollback()
		fmt.Println("更新发运单回冲状态失败, error:" + err.Error())
		return
	}
	//OpenFile读取文件，不存在时则创建，使用追加模式
	File, err := os.OpenFile(filepath, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0777)
	if err != nil {
		fmt.Println("创建csv文件失败, error:" + err.Error())
		return
	}
	//WriterCsv := csv.NewWriter(File)
	//for _, writeItem := range waitWriteLi {
	//	//写入一条数据，传入数据为切片(追加模式)
	//	err = WriterCsv.Write(writeItem)
	//	if err != nil {
	//		fmt.Println("写入csv文件失败, error:" + err.Error())
	//		return
	//	}
	//}
	//WriterCsv.Flush() //刷新，不刷新是无法写入的
	_, err = File.WriteString("\xEF\xBB\xBF") // 写入UTF-8 BOM
	if err != nil {
		_ = acuraSession.Rollback()
		fmt.Println("写入csv文件失败, error:" + err.Error())
		return
	}
	for _, item := range waitWriteLi {
		_, err = File.WriteString(item)
		if err != nil {
			_ = acuraSession.Rollback()
			fmt.Println("写入csv文件失败, error:" + err.Error())
			return
		}
		_, err = File.Write([]byte{'\r', '\n'})
		if err != nil {
			_ = acuraSession.Rollback()
			fmt.Println("写入csv文件失败, error:" + err.Error())
			return
		}
	}
	File.Close()
	err = acuraSession.Commit()
	if err != nil {
		fmt.Println("事务提交失败, error:" + err.Error())
		return
	}
	fmt.Println("OK")
	return

}
