package controller

import (
    "bswas/utilities"
    "strconv"
    "strings"
)

func OrderFormat(data []map[string]string) ([]interface{}, [][]interface{}, map[string]string) {
	row := []interface{}{
		"编号","订单状态","备注","接口下发时间","店铺名称","客户","客户订单号","承运人","快递单号","收货人名称","收货人电话",
		"省","市","区","收货人地址","波次编号","仓库","快递获取标记","快递获取时间","产品代码","产品条码","明细状态",
		"产品名称","订单数量","复核时间","接口取消标记","拣货单打印标记","接口回传标记","接口回传异常备注","订单冻结",
	}
	column := map[string]int{
		"ORDERNO" : 0,
		"ORDERCODENAME" : 1,
		"NOTES" : 2,
		"ADDTIME" : 3,
		"ISSUEPARTYNAME" : 4,
		"CUSTOMER_DESCR_C" : 5,
		"SOREFERENCE1" : 6,
		"CARRIERNAME" : 7,
		"SOREFERENCE5" : 8,
		"C_CONTACT" : 9,
		"C_TEL2" : 10,
		"C_PROVINCE" : 11,
		"C_CITY" : 12,
		"C_DISTRICT" : 13,
		"C_ADDRESS1" : 14,
		"WAVENO" : 15,
		"WAREHOUSEID" : 16,
		"EDISENDFLAG2" : 17,
		"EDISENDTIME2" : 18,
		"SKU" : 19,
		"ALTERNATE_SKU1" : 20,
		"ORDERDETAILCODENAME" : 21,
		"DESCR_C" : 22,
		"QTYORDERED" : 23,
		"CHECKTIME" : 24,
		"ERPCANCELFLAG" : 25,
		"PICKING_PRINT_FLAG" : 26,
		"EDISENDFLAG" : 27,
		"EDIREMARKS2" : 28,
		"RELEASESTATUS" : 29,
	}
	list := make([][]interface{},len(data))
	mergeRow := make(map[string]string)
	var columnName string
	var startIndex int
	rowAmount := 0
	for k,v := range data{
		if columnName == v["ORDERNO"] {
			rowAmount++
		}else{
			if rowAmount != 0 {
				mergeRow[strconv.Itoa(startIndex+2)] = strconv.Itoa(startIndex+2+rowAmount)
			}
			columnName = v["ORDERNO"]
			startIndex = k
			rowAmount = 0
		}
		if rowAmount != 0 {
			mergeRow[strconv.Itoa(startIndex+2)] = strconv.Itoa(startIndex+2+rowAmount)
		}
		line := make([]interface{},len(row))
		for key,value := range column {
			if key == "ADDTIME" || key == "EDISENDTIME2" || key == "CHECKTIME"{
				line[value] = utilities.DateFormat(v[key], "2006-01-02T15:04:05+08:00")
				continue
			}
			line[value] = v[key]
		}
		list[k] = line
	}
	return row,list,mergeRow
}

func OrderWaveFormat(data []map[string]string) ([]interface{}, [][]interface{})  {
	row := []interface{}{
		"波次号","波次状态","波次规则","波次描述","承运人","操作员","创建时间","拣货单打印人","拣货单打印时间",
		"快递单号打印人","快递单号打印时间",
	}
	column := map[string]int{
		"WAVENO"  :  0,
		"CODENAME_C"  :  1,
		"WAVERULE"  :  2,
		"DESCR"  :  3,
		"DESCR_C"  :  4,
		"ADDWHO"  :  5,
		"ADDTIME"  :  6,
		"pickerPrint"  :  7,
		"pickerPrintTime"  :  8,
		"expressPrinting"  :  9,
		"expressPrintTime"  :  10,
	}
	list := make([][]interface{},len(data))
	for k,v := range data{
		line := make([]interface{},len(row))
		for key,value := range column {
			val := ""
			if key == "pickerPrint" && v["USERDEFINE1"] != ""{
				index := strings.IndexAny(v["USERDEFINE1"],"-PK")
				if  index != -1{
					val = v["USERDEFINE1"][0:index-1]
				}
			}
			if key == "pickerPrintTime" && v["USERDEFINE1"] != ""{
				index := strings.IndexAny(v["USERDEFINE1"],"-PK")
				if  index != -1{
					val = v["USERDEFINE1"][index+3:len(v["USERDEFINE1"])-1]
				}
			}
			if key == "expressPrinting" && v["USERDEFINE2"] != ""{
				index := strings.IndexAny(v["USERDEFINE2"],"-EX")
				if  index != -1{
					val = v["USERDEFINE2"][0:index-1]
				}else{
					index := strings.IndexAny(v["USERDEFINE2"],"-Auto")
					if  index != -1{
						val = v["USERDEFINE2"][0:index-1]
					}
				}
			}
			if key == "expressPrintTime" && v["USERDEFINE2"] != ""{
				index := strings.IndexAny(v["USERDEFINE2"],"-EX")
				if  index != -1{
					val = v["USERDEFINE2"][index+3:len(v["USERDEFINE2"])-1]
				}else{
					index := strings.IndexAny(v["USERDEFINE2"],"-Auto")
					if  index != -1{
						val = v["USERDEFINE2"][index+5:len(v["USERDEFINE2"])-1]
					}
				}
			}
			if val != ""{
				line[value] = val
			}else{
				line[value] = v[key]
			}
		}
		list[k] = line
	}
	return row, list
}
func MergerOrderIssueData(data map[string]map[string]interface{}, orderPackages []map[string]string,
						secondOrderPackages []map[string]string, rejectedBillItems []map[string]string, logs []map[string]string) map[string]map[string]interface{} {
	if len(orderPackages) > 0{
		data = mergerOrderPackage(data, orderPackages)
	}
	if len(secondOrderPackages) > 0{
		data = mergerSecondOrderPackage(data, secondOrderPackages)
	}
	if len(rejectedBillItems) > 0{
		data = mergerRejectedBillItem(data, rejectedBillItems)
	}
	if len(logs) > 0{
		data = mergerLog(data, logs)
	}
	return data
}

func mergerOrderPackage(data map[string]map[string]interface{}, orderPackages []map[string]string) map[string]map[string]interface{} {
    for _,orderPackage := range orderPackages {
        if data[orderPackage["order_issue_id"]] == nil {
            items := []map[string]string{
                orderPackage,
            }
            se := map[string]interface{}{
                "orderPackages" : items,
            }
            data[orderPackage["order_issue_id"]] = se
            continue
        }
        if data[orderPackage["order_issue_id"]]["orderPackages"] == nil {
            items := []map[string]string{
                orderPackage,
            }
            data[orderPackage["order_issue_id"]]["orderPackages"] = items
            continue
        }
        data[orderPackage["order_issue_id"]]["orderPackages"] = append(data[orderPackage["order_issue_id"]]["orderPackages"].([]map[string]string),orderPackage)
    }
    return data
}
func mergerSecondOrderPackage(data map[string]map[string]interface{}, secondOrderPackages []map[string]string) map[string]map[string]interface{} {
	for _,secondOrderPackage := range secondOrderPackages {
        if data[secondOrderPackage["order_issue_id"]] == nil {
            items := []map[string]string{
                secondOrderPackage,
            }
            se := map[string]interface{}{
                "secondOrderPackages" : items,
            }
            data[secondOrderPackage["order_issue_id"]] = se
            continue
        }
        if data[secondOrderPackage["order_issue_id"]]["secondOrderPackages"] == nil {
            items := []map[string]string{
                secondOrderPackage,
            }
            data[secondOrderPackage["order_issue_id"]]["secondOrderPackages"] = items
            continue
        }
        data[secondOrderPackage["order_issue_id"]]["secondOrderPackages"] = append(data[secondOrderPackage["order_issue_id"]]["secondOrderPackages"].([]map[string]string),secondOrderPackage)
	}
	return data
}
func mergerRejectedBillItem(data map[string]map[string]interface{}, rejectedBillItems []map[string]string) map[string]map[string]interface{} {
    for _,rejectedBillItem := range rejectedBillItems {
        if data[rejectedBillItem["order_issue_id"]] == nil {
            items := []map[string]string{
                rejectedBillItem,
            }
            se := map[string]interface{}{
                "rejectedBillItems" : items,
            }
            data[rejectedBillItem["order_issue_id"]] = se
            continue
        }
        if data[rejectedBillItem["order_issue_id"]]["rejectedBillItems"] == nil {
            items := []map[string]string{
                rejectedBillItem,
            }
            data[rejectedBillItem["order_issue_id"]]["rejectedBillItems"] = items
            continue
        }
        data[rejectedBillItem["order_issue_id"]]["rejectedBillItems"] = append(data[rejectedBillItem["order_issue_id"]]["rejectedBillItems"].([]map[string]string),rejectedBillItem)
    }
    return data
}
func mergerLog(data map[string]map[string]interface{}, logs []map[string]string) map[string]map[string]interface{} {
    for _,log := range logs {
        if data[log["order_issue_id"]] == nil {
            items := []map[string]string{
                log,
            }
            se := map[string]interface{}{
                "logs" : items,
            }
            data[log["order_issue_id"]] = se
            continue
        }
        if data[log["order_issue_id"]]["logs"] == nil {
            items := []map[string]string{
                log,
            }
            data[log["order_issue_id"]]["logs"] = items
            continue
        }
        data[log["order_issue_id"]]["logs"] = append(data[log["order_issue_id"]]["logs"].([]map[string]string),log)
    }
    return data
}
func OrderIssueFormat(dataMap map[string]map[string]interface{}) ([]interface{}, [][]interface{}, map[string]string)  {
	row := []interface{}{
		"登记日期","创建日期","客户","店铺","客户订单号","原始承运商","收货人",
		"收货电话","省","市","区","收货人地址","原始运单号","原始商品条码","原始商品名称","原始商品数量",
		"退单备注","退单商品名","退单商品条码","退单商品数量","退单状态",
		"操作类型","说明","操作者","情况说明","问题类别","二次订单号","二次承运商","二次运单号",
		"二次商品条码","二次商品名","二次商品数量","最终状态",
		"承运商赔偿金额","承运商快递减免",
		"宝时赔偿金额","宝时快递减免","事故责任方",
	}
	column := map[string]int{
		"order_issues_created_at"  :  0,
		"order_created_at"  :  1,
		"owner_name"  :  2,
		"shop_name"  :  3,
		"client_code"  :  4,
		"logistic_name"  :  5,
		"consignee_name"  :  6,
		"consignee_phone"  :  7,
		"province"  :  8,
		"city"  :  9,
		"district"  :  10,
		"address"  :  11,
		"order_package_logistic_number"  :  12,
		"commodity_sku"  :  13,
		"commodity_name"  :  14,
		"commodity_amount" : 15,
		"remark" : 16,
		"name_goods"  :  17,
		"barcode_goods"  :  18,
		"rejected_bill_amount"  :  19,
		"rejecting_status"  :  20,
		"log_type"  :  21,
		"log_content"  :  22,
		"user_name"  :  23,
		"result_explain"  :  24,
		"order_issue_type_name"  :  25,
		"s_o_client_code"  :  26,
		"s_logistics_name"  :  27,
		"logistic_number"  :  28,
		"s_c_sku"  :  29,
		"s_c_name"  :  30,
		"s_o_p_c_amount"  :  31,
		"final_status"  :  32,
		"logistic_indemnity_money"  :  33,
		"logistic_express_remission"  :  34,
		"baoshi_indemnity_money"  :  35,
		"baoshi_express_remission"  :  36,
		"user_workgroup_name"  :  37,
	}
	data := make([]map[string]interface{},len(dataMap))
	for _,value := range dataMap {
		data[value["index"].(int)] = value
	}
	var list [][]interface{}
	mergeRow := make(map[string]string)
	rownum := 0
	for _,v := range data{
		var orderPackages []map[string]string
		var secondOrderPackages []map[string]string
		var rejectedBillItems []map[string]string
		var logs []map[string]string
		if v["orderPackages"] != nil {
			orderPackages = v["orderPackages"].([]map[string]string)
		}
		orderPackagesLength := len(orderPackages)

		if v["secondOrderPackages"] != nil {
			secondOrderPackages = v["secondOrderPackages"].([]map[string]string)
		}
		secondOrderPackagesLength := len(secondOrderPackages)

		if v["rejectedBillItems"] != nil {
			rejectedBillItems = v["rejectedBillItems"].([]map[string]string)
		}
		rejectedBillItemsLength := len(rejectedBillItems)

		if v["logs"] != nil {
			logs = v["logs"].([]map[string]string)
		}
		logsLength := len(logs)

		count := 1
		if  orderPackagesLength> count {
			count = orderPackagesLength
		}
		if secondOrderPackagesLength > count {
			count = secondOrderPackagesLength
		}
		if rejectedBillItemsLength > count {
			count = rejectedBillItemsLength
		}
		if logsLength > count {
			count = logsLength
		}
		if count > 1{
			mergeRow[strconv.Itoa(rownum+2)] = strconv.Itoa(rownum+1+count)
		}
		for i := 0; i<count; i++ {
			line := make([]interface{},len(row))
			for key,value := range column {
				if key == "order_created_at" || key == "order_issues_created_at" {
					line[value] = utilities.DateFormat(v[key].(string),"2006-01-02T15:04:05Z")
					continue
				}
				if key == "order_package_logistic_number" || key == "commodity_sku" || key == "commodity_name" || key == "commodity_amount"{
					if i < orderPackagesLength && orderPackages != nil{
						line[value] = orderPackages[i][key]
					}else{
						line[value] = ""
					}
					continue
				}
				if key == "logistic_number" || key == "s_c_sku" || key == "s_c_name" || key == "s_o_p_c_amount"{
					if i < secondOrderPackagesLength && secondOrderPackages != nil{
						line[value] = secondOrderPackages[i][key]
					}else{
						line[value] = ""
					}
					continue
				}
				if key == "rejected_bill_amount" || key == "name_goods" || key == "barcode_goods" || key == "remark"{
					if i < rejectedBillItemsLength && rejectedBillItems != nil{
						line[value] = rejectedBillItems[i][key]
					}else{
						line[value] = ""
					}
					continue
				}
				if key == "log_type" || key == "log_content" || key == "user_name"{
					if i < logsLength && logs != nil{
						line[value] = logs[i][key]
					}else{
						line[value] = ""
					}
					continue
				}
				line[value] = v[key]
			}
			list = append(list,line)
			rownum++
		}
	}
	return row, list, mergeRow
}

func GetOrderIssuesModel(orderIssues []map[string]string)(modelData map[string]map[string]interface{}, orderPackageConditionValue string,
	secondOrderPackageConditionValue string, rejectedBillItemConditionValue string, logConditionValue string){
	modelData = make(map[string]map[string]interface{})
	orderPackageConditionValue = " WHERE order_packages.order_id IN ("
	secondOrderPackageConditionValue = " WHERE o_d.client_code IN ("
	rejectedBillItemConditionValue = " WHERE rejected_bills.logistic_number_return IN ("
	logConditionValue = " WHERE order_issue_process_logs.order_issue_id IN ("
	for index,value := range orderIssues{
		orderIssue := map[string]interface{}{
			"index": 					  index,
			"id":                         value["id"],
			"district":                   value["district"],
			"address":                    value["address"],
			"city":                       value["city"],
			"province":                   value["province"],
			"consignee_name":             value["consignee_name"],
			"consignee_phone":            value["consignee_phone"],
			"client_code":                value["client_code"],
			"order_created_at":           value["order_created_at"],
			"logistic_name":              value["logistic_name"],
			"owner_name":                 value["owner_name"],
			"s_o_client_code":            value["s_o_client_code"],
			"logistic_number":            value["logistic_number"],
			"order_issues_created_at":    value["order_issues_created_at"],
			"shop_name":                  value["shop_name"],
			"rejecting_status":           value["rejecting_status"],
			"result_explain":             value["result_explain"],
			"order_issue_type_name":      value["order_issue_type_name"],
			"final_status":               value["final_status"],
			"logistic_indemnity_money":   value["logistic_indemnity_money"],
			"logistic_express_remission": value["logistic_express_remission"],
			"baoshi_indemnity_money":     value["baoshi_indemnity_money"],
			"baoshi_express_remission":   value["baoshi_express_remission"],
			"user_workgroup_name":        value["user_workgroup_name"],
		}
		modelData[value["id"]] = orderIssue
		if index < len(orderIssues)-1{
			if value["order_id"] != "" {
				orderPackageConditionValue += value["order_id"]+","
			}
			if value["s_o_client_code"] != "" {
				secondOrderPackageConditionValue += "'"+value["s_o_client_code"]+"',"
			}
			if value["logistic_number_return"] != "" {
				rejectedBillItemConditionValue += "'"+value["logistic_number_return"]+"',"
			}
			if value["id"] != "" {
				logConditionValue += value["id"]+","
			}
		}else{
			if value["order_id"] != "" {
				orderPackageConditionValue += value["order_id"]
			}
			if value["s_o_client_code"] != "" {
				secondOrderPackageConditionValue += "'"+value["s_o_client_code"]+"'"
			}
			if value["logistic_number_return"] != "" {
				rejectedBillItemConditionValue += "'"+value["logistic_number_return"]+"'"
			}
			if value["id"] != "" {
				logConditionValue += value["id"]
			}
		}
	}
	orderPackageConditionValue += ")"
	secondOrderPackageConditionValue += ")"
	rejectedBillItemConditionValue += ")"
	logConditionValue += ")"
	return
}
