package controller

import (
    "bswas/excel"
    "bswas/orm"
    "bswas/utilities"
    "encoding/json"
    "net/http"
    "strconv"
)

func Export(w http.ResponseWriter,req *http.Request)  {
	errorMsg := utilities.NewError()
	decoder := json.NewDecoder(req.Body)
	var params map[string]string
	// 解析参数 存入map
	e := decoder.Decode(&params)
	if e != nil{
		utilities.WriteLog("/api/controller/controller.go:18   参数解析失败!","ERROR")
	}
	file := excel.CreateFile(selectCreateFormat(params))
	if errorMsg.GetMsg() != "" {
		w.Header().Set("Msg",errorMsg.GetMsg())
		w.WriteHeader(500)
		return
	}
	if _, err := file.WriteTo(w); err != nil {
		utilities.WriteLog("/api/controller/controller.go:27   返回二进制流失败!","ERROR")
		return
	}
}
type base struct {
	ROW []interface{} `json:"row"`
	LIST [][]interface{} `json:"list"`
	MERGEROW map[string]string `json:"mergeRow"`
	MERGECOLUMN []string `json:"mergeColumn"`
}

func selectCreateFormat(params map[string]string) (row []interface{}, list [][]interface{}, mergeRow map[string]string, mergeColumn []string){
	switch params["createFormat"] {
	case "merge":
		row, list, mergeRow, mergeColumn = selectModule(params)
    case "warpText":
        row, list, _, mergeColumn = selectModule(params)
	default:
		row, list, _, _ = selectModule(params)
	}
	return
}

func selectModule(params map[string]string) (row []interface{}, list [][]interface{}, mergeRow map[string]string, mergeColumn []string) {
	var data []map[string]string
	switch params["type"] {
	case "base":
		var val base
		err := json.Unmarshal([]byte(params["data"]),&val)
		if err != nil {
			utilities.WriteLog("/api/controller/controller.go:58  JSON解析失败!","ERROR")
			utilities.WriteLog(params["data"],"ERROR")
		}
		row = val.ROW
		list = val.LIST
		mergeRow = val.MERGEROW
		mergeColumn = val.MERGECOLUMN
	case "waybill":
		data = orm.GetMysqlData(params["sql"])
		row, list = WaybillFormat(data)
	case "waybillDelivering":
		data = orm.GetMysqlData(params["sql"])
		row, list = WaybillDeliveringFormat(data)
	case "waybillFinancial":
		data = orm.GetMysqlData(params["sql"])
		row, list = WaybillFinancialFormat(data)
	case "rejected":
		data = orm.GetMysqlData(params["sql"])
		row, list, mergeRow = RejectedFormat(data)
		mergeColumn = []string{
			"A","B","C","D","E","F","G","H","I","J","K","T","U",
		}
	case "rejectedStatistics":
		data = orm.GetMysqlData(params["sql"])
		row, list = RejectedStatisticsFormat(data)
	case "order":
		data = orm.GetOracleData(params["sql"])
		row, list, mergeRow = OrderFormat(data)
		mergeColumn = []string{
			"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P",
			"Q","R","S","Z","AA","AB","AC","AD",
		}
	case "orderWave":
		data = orm.GetOracleData(params["sql"])
		row, list = OrderWaveFormat(data)
	case "packageIssuedException":
		data = orm.GetMysqlData(params["sql"])
		row, list = PackageIssuedExceptionFormat(data)
	case "packageCreateException":
		data = orm.GetMysqlData(params["sql"])
		row, list = PackageCreateExceptionFormat(data)
	case "inventory":
		if params["sql"] != "" {
			data = orm.GetOracleData(params["sql"])
		}else{
			err := json.Unmarshal([]byte(params["data"]), &data)
			if err != nil {
				utilities.WriteLog("/api/controller/controller.go:104   库存数据json解析失败!","ERROR")
			}
		}
		row, list = InventoryFormat(data, true)
	case "allInventory":
		if params["sql"] != "" {
			data = orm.GetOracleData(params["sql"])
		}else{
			err := json.Unmarshal([]byte(params["data"]), &data)
			if err != nil {
				utilities.WriteLog("/api/controller/controller.go:114   全部库存数据json解析失败!","ERROR")
			}
		}
		row, list = InventoryFormat(data, false)
	case "process":
		data = orm.GetMysqlData(params["sql"])
		row, list, mergeRow = ProcessFormat(data)
		mergeColumn = []string{
			"A","B","C","D","E","F","G","H","I",
		}
	case "laborReport":
		err := json.Unmarshal([]byte(params["data"]), &data)
		if err != nil {
			utilities.WriteLog("/api/controller/controller.go:127   临时工报表数据json解析失败!","ERROR")
		}
		row, list = LaborReportFormat(data)
	case "orderIssue":
		sqlList := make(map[string]string)
		err := json.Unmarshal([]byte(params["sqlList"]), &sqlList)
		if err != nil {
			utilities.WriteLog("/api/controller/controller.go:134   订单问题件数据json解析失败!","ERROR")
		}
		if sqlList["orderPackageSql"] == "" || sqlList["secondOrderPackageSql"] == "" || sqlList["orderIssueSql"] == "" || sqlList["rejectedBillItemSql"] == "" || sqlList["logSql"] == ""{
			return
		}
		orderIssues := orm.GetMysqlData(sqlList["orderIssueSql"])
		if len(orderIssues) < 1 {
			break
		}
		modelData, orderPackageConditionValue, secondOrderPackageConditionValue, rejectedBillItemConditionValue, logConditionValue := GetOrderIssuesModel(orderIssues)
		orderPackages := make([]map[string]string,0)
		secondOrderPackages := make([]map[string]string,0)
		rejectedBillItems := make([]map[string]string,0)
		logs := make([]map[string]string,0)
		OP := len(orderPackageConditionValue)
		SOP := len(secondOrderPackageConditionValue)
		RB := len(rejectedBillItemConditionValue)
		L := len(logConditionValue)
		if  orderPackageConditionValue[OP-2:] != "()"{
			if orderPackageConditionValue[OP-2:OP-1] == "," {
				orderPackageConditionValue = orderPackageConditionValue[0:OP-2] + orderPackageConditionValue[OP-1:]
			}
			orderPackages = orm.GetMysqlData(sqlList["orderPackageSql"]+orderPackageConditionValue)
		}
		if  secondOrderPackageConditionValue[len(secondOrderPackageConditionValue)-2:] != "()"{
			if secondOrderPackageConditionValue[SOP-2:SOP-1] == "," {
				secondOrderPackageConditionValue = secondOrderPackageConditionValue[0:SOP-2] + secondOrderPackageConditionValue[SOP-1:]
			}
			secondOrderPackages = orm.GetMysqlData(sqlList["secondOrderPackageSql"]+secondOrderPackageConditionValue)
		}
		if  rejectedBillItemConditionValue[len(rejectedBillItemConditionValue)-2:] != "()"{
			if rejectedBillItemConditionValue[RB-2:RB-1] == "," {
				rejectedBillItemConditionValue = rejectedBillItemConditionValue[0:RB-2] + rejectedBillItemConditionValue[RB-1:]
			}
			rejectedBillItems = orm.GetMysqlData(sqlList["rejectedBillItemSql"]+rejectedBillItemConditionValue)
		}
		if  logConditionValue[len(logConditionValue)-2:] != "()"{
			if logConditionValue[L-2:L-1] == "," {
				logConditionValue = logConditionValue[0:L-2] + logConditionValue[L-1:]
			}
			logs = orm.GetMysqlData(sqlList["logSql"]+logConditionValue)
		}
		result := MergerOrderIssueData(modelData,orderPackages,secondOrderPackages,rejectedBillItems,logs)
		row, list, mergeRow = OrderIssueFormat(result)
		mergeColumn = []string{
			"A","B","C","D","E","F","G","H","I","J","K","L",
			"U","Y","Z","AA","AF","AG","AH","AI","AJ","AK",
		}
	case "inventoryAccountMission":
		err := json.Unmarshal([]byte(params["data"]), &data)
		if err != nil {
			utilities.WriteLog("/api/controller/controller.go:185   库存盘点数据json解析失败!","ERROR")
		}
		row, list = InventoryAccountMissionFormat(data)
	case "inventoryCompare":
		data = orm.GetMysqlData(params["sql"])
		row, list = InventoryCompareFormat(data)
	case "unify":
		var column []string
		var rule map[string]string
		err := json.Unmarshal([]byte(params["row"]), &row)
		if err != nil {
			utilities.WriteLog("/api/controller/controller.go:196   参数传递错误!","ERROR")
		}
		err = json.Unmarshal([]byte(params["column"]), &column)
		if err != nil {
			utilities.WriteLog("/api/controller/controller.go:200   参数传递错误!","ERROR")
		}
		if params["mergeColumn"] != ""{
		    err = json.Unmarshal([]byte(params["mergeColumn"]), &mergeColumn)
            if err != nil {
                utilities.WriteLog("/api/controller/controller.go:205   参数传递错误!","ERROR")
            }
        }
		err = json.Unmarshal([]byte(params["rule"]), &rule)
		if params["connection"] == "oracle" {
			data = orm.GetOracleData(params["sql"])
		}else{
			data = orm.GetMysqlData(params["sql"])
		}
		list, mergeRow = unifyFormat(data, column, rule, params["datum"])
	}
	return row,list,mergeRow,mergeColumn
}

func unifyFormat(data []map[string]string, row []string, rule map[string]string, datum string) ([][]interface{}, map[string]string){
	rowLen := len(row)
	column :=  make(map[string]int,rowLen)
	for i,c := range row {
		column[c] = i
	}

	list := make([][]interface{},len(data))
    mergeRow := make(map[string]string)
    var columnName string
    var startIndex int
    rowAmount := 0
	for k,v := range data{
        if datum != "" {
            if columnName == v[datum] {
                rowAmount++
            }else{
                if rowAmount != 0 {
                    mergeRow[strconv.Itoa(startIndex+2)] = strconv.Itoa(startIndex+2+rowAmount)
                }
                columnName = v[datum]
                startIndex = k
                rowAmount = 0
            }
            if rowAmount != 0 {
                mergeRow[strconv.Itoa(startIndex+2)] = strconv.Itoa(startIndex+2+rowAmount)
            }
        }
		line := make([]interface{},rowLen)
		for key,value := range column {
			if rule[key] != ""{
				line[value] = dataFormat(rule[key], v[key])
				continue
			}
			line[value] = v[key]
		}
		list[k] = line
	}
	return list, mergeRow
}

func dataFormat(ruleType string,value string)string{
	switch ruleType {
		case "oracleDate":
			value = utilities.DateFormat(value, "2006-01-02T15:04:05+08:00")
		case "mysqlDate":
			value = utilities.DateFormat(value,"2006-01-02T15:04:05Z")
		case "percent":
			rate,_ := strconv.ParseFloat(value,64)
			if rate != 0 {
				value = strconv.FormatFloat(rate * 100, 'f', 2, 64)+"%"
			}
	}
	return value
}
