order_info_controlller.go 42.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320
package controllers

import (
	"crypto/md5"
	"encoding/hex"
	"errors"
	"fmt"
	"github.com/beego/beego/v2/client/httplib"
	"os"
	"path"
	"regexp"
	"strconv"
	"strings"
	"time"
	"unicode/utf8"

	"github.com/360EntSecGroup-Skylar/excelize/v2"
	"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/constant"

	"github.com/astaxie/beego/logs"
	orderCmd "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/orderinfo/command"
	orderQuery "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/orderinfo/query"
	orderService "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/orderinfo/service"
	"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/domain"
	"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/infrastructure/utils"
	"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/lib"
	"gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/lib/exceltool"
)

type OrderInfoController struct {
	BaseController
}

////Prepare 重写 BaseController 的Prepare方法
func (c *OrderInfoController) Prepare() {
	c.BaseController.Prepare()
	if ok := c.ValidJWTToken(); !ok {
		return
	}
	if ok := c.ValidAdminPermission(domain.PERMISSION_ORDER); !ok {
		return
	}
}

//postPurposeOrderDetail 请求添加/更新的订单数据
type postPurposeOrderDetail struct {
	Id int64 `json:"id"`
	//订单编号
	OrderId string `json:"orderId"`
	//买家姓名
	BuyerName string `json:"buyer"`
	//对应合伙人 id
	PartnerId int64 `json:"partnerID"`
	//业务员抽成比例
	CommissionProportion float64 `json:"commissionProportion"`
	//订单区域
	OrderDist string `json:"orderDist"`
	//商品
	Product []postOrderGood `json:"product"`
}

func (postData *postPurposeOrderDetail) Valid() error {
	postData.OrderId = strings.TrimSpace(postData.OrderId)
	postData.BuyerName = strings.TrimSpace(postData.BuyerName)
	postData.OrderDist = strings.TrimSpace(postData.OrderDist)
	if len(postData.OrderId) == 0 {
		return lib.ThrowError(lib.ARG_ERROR, "订单编号必填")
	}
	if len(postData.BuyerName) == 0 {
		return lib.ThrowError(lib.ARG_ERROR, "买家信息必填")
	}
	if postData.PartnerId == 0 {
		return lib.ThrowError(lib.ARG_ERROR, "合伙人信息必填")

	}
	if len(postData.OrderDist) == 0 {
		return lib.ThrowError(lib.ARG_ERROR, "订单区域必填")
	}
	if len(postData.Product) == 0 {
		return lib.ThrowError(lib.ARG_ERROR, "货品列表必填")
	}
	if len(postData.Product) > 50 {
		return lib.ThrowError(lib.ARG_ERROR, "货品列表最多50项")
	}
	for i := range postData.Product {
		if err := postData.Product[i].Valid(); err != nil {
			return err
		}
	}
	return nil
}

//PostPurposeOrderGood 请求添加/更新订单中的货品
type postOrderGood struct {
	Id           int64   `json:"id"`
	ProductName  string  `json:"productName"`
	OrderNum     int     `json:"orderNum"`
	Univalence   float64 `json:"univalence"`
	PartnerRatio float64 `json:"partnerRatio"`
}

func (postData *postOrderGood) Valid() error {
	postData.ProductName = strings.TrimSpace(postData.ProductName)
	lenProductName := utf8.RuneCountInString(postData.ProductName)
	if lenProductName == 0 {
		return lib.ThrowError(lib.ARG_ERROR, "商品名称必填")
	}
	if lenProductName > 50 {
		return lib.ThrowError(lib.ARG_ERROR, "商品名称最多50位")
	}
	if postData.OrderNum >= 1e16 {
		return lib.ThrowError(lib.ARG_ERROR, "商品数量最多16位")
	}
	if postData.Univalence >= 1e16 {
		return lib.ThrowError(lib.ARG_ERROR, "商品单价最多16位")
	}
	if postData.PartnerRatio > 100 {
		return lib.ThrowError(lib.ARG_ERROR, "合伙人分红比例超额")
	}
	partnerRatio := fmt.Sprint(postData.PartnerRatio)
	regexpStr := `^(100|[1-9]\d|\d)(.\d{1,2})?$`
	ok := regexp.MustCompile(regexpStr).MatchString(partnerRatio)
	if !ok {
		return lib.ThrowError(lib.ARG_ERROR, "合伙人分红比例精确到小数点2位")
	}

	return nil
}

type postOrderPurposeDelivery struct {
	ShipmentsId   string          `json:"shipmentsId"` //发货单号
	Id            string          `json:"id"`          //订单id
	ProductDetail []postOrderGood `json:"productDetail"`
}

func (postData *postOrderPurposeDelivery) Valid() error {
	postData.ShipmentsId = strings.TrimSpace(postData.ShipmentsId)
	lenShipmentsId := utf8.RuneCountInString(postData.ShipmentsId)
	if lenShipmentsId == 0 {
		return lib.ThrowError(lib.ARG_ERROR, "发货单号必填")
	}
	if lenShipmentsId > 50 {
		return lib.ThrowError(lib.ARG_ERROR, "发货单号最多50位")
	}

	for i := range postData.ProductDetail {
		if err := postData.ProductDetail[i].Valid(); err != nil {
			return err
		}
	}
	return nil
}

/**
 * @Author SteveChan
 * @Description // 获取实发订单列表,修改搜索条件
 * @Date 20:23 2021/1/10
 * @Param
 * @return
 **/
func (c *OrderInfoController) PageListOrderReal() {
	type Parameter struct {
		PartnerName         string   `json:"partnerName"`         // 合伙人姓名
		OrderCode           string   `json:"orderCode"`           // 订单号
		DeliveryCode        string   `json:"deliveryCode"`        // 发货单号
		PartnerCategory     int      `json:"partnerCategory"`     // 合伙人类型id
		PartnerCategoryName string   `json:"partnerCategoryName"` // 合伙人类型名称
		PageSize            int      `json:"pageSize"`
		PageNumber          int      `json:"pageNumber"`
		UpdateTime          []string `json:"updateTime"` // 订单更新时间
		CreateTime          []string `json:"createTime"` // 订单创建时间
		SaleDate            []string `json:"saleDate"`   // 销售时间
	}
	var (
		param Parameter
		err   error
	)
	if err = c.BindJsonData(&param); err != nil {
		logs.Error(err)
		c.ResponseError(errors.New("json数据解析失败"))
		return
	}
	if param.PageNumber == 0 {
		param.PageNumber = 1
	}
	if param.PageSize == 0 {
		param.PageSize = 20
	}
	// 订单更新时间处理
	var (
		updateTimeBegin string
		updateTimeEnd   string
	)
	if len(param.UpdateTime) > 0 {
		if len(param.UpdateTime[0]) > 0 {
			t, err := time.ParseInLocation("2006-01-02", param.UpdateTime[0], time.Local)
			if err != nil {
				c.ResponseError(errors.New("UpdateTimeBegin 时间格式错误"))
				return
			}
			updateTimeBegin = t.Format("2006-01-02 15:04:05-07")
		}
	}
	if len(param.UpdateTime) > 1 {
		if len(param.UpdateTime[1]) > 0 {
			t, err := time.ParseInLocation("2006-01-02", param.UpdateTime[1], time.Local)
			if err != nil {
				c.ResponseError(errors.New("UpdateTimeEnd 时间格式错误"))
				return
			}
			//设定时间边界
			t = t.Add(86399 * time.Second)
			updateTimeEnd = t.Format("2006-01-02 15:04:05-07")
		}
	}
	// 订单创建时间处理
	var (
		createTimeBegin string
		createTimeEnd   string
	)
	if len(param.CreateTime) > 0 {
		if len(param.CreateTime[0]) > 0 {
			t, err := time.ParseInLocation("2006-01-02", param.CreateTime[0], time.Local)
			if err != nil {
				c.ResponseError(errors.New("UpdateTimeBegin 时间格式错误"))
				return
			}
			createTimeBegin = t.Format("2006-01-02 15:04:05-07")
		}
	}
	if len(param.CreateTime) > 1 {
		if len(param.CreateTime[1]) > 0 {
			t, err := time.ParseInLocation("2006-01-02", param.CreateTime[1], time.Local)
			if err != nil {
				c.ResponseError(errors.New("UpdateTimeEnd 时间格式错误"))
				return
			}
			//设定时间边界
			t = t.Add(86399 * time.Second)
			createTimeEnd = t.Format("2006-01-02 15:04:05-07")
		}
	}
	// 订单销售时间处理
	var (
		saleDateBegin string
		saleDateEnd   string
	)
	if len(param.SaleDate) > 0 {
		if len(param.SaleDate[0]) > 0 {
			t, err := time.ParseInLocation("2006-01-02", param.SaleDate[0], time.Local)
			if err != nil {
				c.ResponseError(errors.New("销售开始时间格式错误"))
				return
			}
			saleDateBegin = t.Format("2006-01-02 15:04:05-07")
		}
	}
	if len(param.SaleDate) > 1 {
		if len(param.SaleDate[1]) > 0 {
			t, err := time.ParseInLocation("2006-01-02", param.SaleDate[1], time.Local)
			if err != nil {
				c.ResponseError(errors.New("销售结束时间格式错误"))
				return
			}
			//设定时间边界
			t = t.Add(86399 * time.Second)
			saleDateEnd = t.Format("2006-01-02 15:04:05-07")
		}
	}
	companyId := c.GetUserCompany()
	orderSrv := orderService.NewOrderInfoService(nil)
	orderInfos, cnt, err := orderSrv.PageListOrderBase(orderQuery.ListOrderBaseQuery{
		PartnerName:         param.PartnerName,
		OrderCode:           param.OrderCode,
		DeliveryCode:        param.DeliveryCode,
		OrderType:           domain.OrderReal,
		Limit:               param.PageSize,
		Offset:              (param.PageNumber - 1) * param.PageSize,
		CompanyId:           companyId,
		PartnerCategory:     param.PartnerCategory,
		PartnerCategoryName: param.PartnerCategoryName,
		UpdateTimeBegin:     updateTimeBegin,
		UpdateTimeEnd:       updateTimeEnd,
		CreateTimeBegin:     createTimeBegin,
		CreateTimeEnd:       createTimeEnd,
		SaleDateBegin:       saleDateBegin,
		SaleDateEnd:         saleDateEnd,
	})
	if err != nil {
		c.ResponseError(err)
		return
	}
	c.ResponsePageList(orderInfos, cnt, param.PageNumber)
	return
}

//GetOrderReal 获取实发订单详情
func (c *OrderInfoController) GetOrderReal() {
	type Parameter struct {
		Id string `json:"id"`
	}
	var (
		param Parameter
		err   error
	)
	if err = c.BindJsonData(&param); err != nil {
		logs.Error(err)
		c.ResponseError(errors.New("json数据解析失败"))
		return
	}
	orderid, _ := strconv.ParseInt(param.Id, 10, 64)
	if orderid == 0 {
		c.ResponseError(errors.New("参数错误"))
		return
	}
	companyId := c.GetUserCompany()
	orderSrv := orderService.NewOrderInfoService(nil)
	orderinfo, err := orderSrv.GetOrderDetail(orderQuery.GetOrderQuery{
		OrderId:   orderid,
		CompanyId: companyId,
	})
	if err != nil {
		c.ResponseError(err)
		return
	}
	if orderinfo.OrderType != domain.OrderReal {
		c.ResponseError(errors.New("参数错误"))
		return
	}
	allGoods := []map[string]interface{}{}
	for _, v := range orderinfo.Goods {
		m := map[string]interface{}{
			//"id":              fmt.Sprint(v.Id),
			"id":              v.Id,
			"productName":     v.GoodName,
			"orderNum":        v.PlanGoodNumber,
			"univalence":      v.Price,
			"partnerRatio":    v.PartnerBonusPercent,
			"orderPrice":      v.GoodCompute.PlanAmount,
			"quantityControl": "",
			"priceControl":    "",
		}
		if v.GoodCompute.UseAmount >= 0 {
			m["priceControl"] = fmt.Sprint(v.GoodCompute.UseAmount)
		}
		if v.UseGoodNumber >= 0 {
			m["quantityControl"] = fmt.Sprint(v.UseGoodNumber)
		}
		allGoods = append(allGoods, m)
	}
	rsp := map[string]interface{}{
		"buyer":                             orderinfo.Buyer.BuyerName,
		"id":                                orderinfo.Id,
		"partnerID":                         orderinfo.PartnerInfo.Id,
		"partner":                           orderinfo.PartnerInfo.PartnerName,
		"orderDist":                         orderinfo.RegionInfo.RegionName,
		"orderId":                           orderinfo.OrderCode,
		"shipmentsId":                       orderinfo.DeliveryCode,
		"commissionProportion":              orderinfo.SalesmanBonusPercent,
		"orderNumCount":                     orderinfo.OrderCompute.PlanOrderCount,
		"orderAmountAdjustmentCount":        orderinfo.OrderCompute.PlanOrderAmount,
		"orderNumCountControl":              "",
		"orderAmountAdjustmentCountControl": "",
		"product":                           allGoods,
		"create_time":                       orderinfo.CreateTime.Local().Format("2006-01-02 15:04:05"),
		"update_time":                       orderinfo.UpdateTime.Local().Format("2006-01-02 15:04:05"),
		"saleDate":                          orderinfo.SaleDate.Local().Format("2006-01-02 15:04:05"),
		"partnerCategoryId":                 orderinfo.PartnerCategory.Id,
		"partnerCategoryName":               orderinfo.PartnerCategory.Name,
	}
	if orderinfo.OrderCompute.UseOrderAmount >= 0 {
		rsp["orderNumCountControl"] = fmt.Sprint(orderinfo.OrderCompute.UseOrderCount)
	}
	if orderinfo.OrderCompute.UseOrderCount >= 0 {
		rsp["orderAmountAdjustmentCountControl"] = fmt.Sprint(orderinfo.OrderCompute.UseOrderAmount)
	}
	c.ResponseData(rsp)
	return
}

//实际订单
type postRealOrderDetail struct {
	postPurposeOrderDetail
	PartnerCategoryId int64  `json:"partnerCategoryId"`
	ShipmentsId       string `json:"shipmentsId"` //发货单号
	SaleDate          string `json:"saleDate"`    // 销售日期
}

func (postData *postRealOrderDetail) Valid() error {
	postData.ShipmentsId = strings.TrimSpace(postData.ShipmentsId)
	if len(postData.ShipmentsId) == 0 {
		return lib.ThrowError(lib.ARG_ERROR, "订单的发货单号必填")
	}
	if err := postData.postPurposeOrderDetail.Valid(); err != nil {
		return err
	}
	return nil
}

//UpdateOrderReal 编辑实际订单
func (c *OrderInfoController) UpdateOrderReal() {
	//用与适配前端定义的数据结构
	var (
		param postRealOrderDetail
		err   error
	)
	if err = c.BindJsonData(&param); err != nil {
		logs.Error(err)
		c.ResponseError(errors.New("json数据解析失败"))
		return
	}
	if err := param.Valid(); err != nil {
		c.ResponseError(err)
		return
	}
	var orderDataReturn *domain.OrderBase
	saleDate, err := time.ParseInLocation("2006-01-02 15:04:05", param.SaleDate, time.Local)
	saleDateWithTz := time.Date(saleDate.Year(), saleDate.Month(), saleDate.Day(), time.Now().Hour(), time.Now().Minute(), time.Now().Second(), time.Now().Nanosecond(), time.Local)

	if err != nil {
		e := lib.ThrowError(lib.ARG_ERROR, err.Error())
		c.ResponseError(e)
		return
	}
	if param.Id == 0 {
		orderDataReturn, err = c.addOrderReal(param, saleDateWithTz)
	} else {
		err = c.editOrderReal(param, saleDateWithTz)
	}
	if err != nil {
		c.ResponseError(err)
		return
	}
	if orderDataReturn != nil {
		c.ResponseData(map[string]interface{}{
			"id": orderDataReturn.Id,
		})
		return
	}
	c.ResponseData(nil)
	return
}

func (c *OrderInfoController) addOrderReal(param postRealOrderDetail, saleDate time.Time) (*domain.OrderBase, error) {
	orderSrv := orderService.NewOrderInfoService(nil)
	newGoods := []orderCmd.OrderGoodData{}
	for _, v := range param.Product {
		g := orderCmd.OrderGoodData{
			GoodName:            v.ProductName,
			PlanGoodNumber:      v.OrderNum,
			Price:               v.Univalence,
			PartnerBonusPercent: v.PartnerRatio,
		}
		newGoods = append(newGoods, g)
	}
	companyId := c.GetUserCompany()
	createcmd := orderCmd.CreateOrderCommand{
		OrderType:            domain.OrderReal,
		OrderCode:            param.OrderId,
		DeliveryCode:         param.ShipmentsId,
		BuyerName:            param.BuyerName,
		OrderRegion:          param.OrderDist,
		PartnerId:            param.PartnerId,
		SalesmanBonusPercent: param.CommissionProportion,
		Goods:                newGoods,
		CompanyId:            companyId,
		PartnerCategory:      param.PartnerCategoryId,
		SaleDate:             saleDate,
	}
	orderData, err := orderSrv.CreateNewOrder(createcmd)
	return orderData, err
}

func (c *OrderInfoController) editOrderReal(param postRealOrderDetail, saleDate time.Time) error {

	newGoods := []orderCmd.OrderGoodData{}
	for _, v := range param.Product {
		g := orderCmd.OrderGoodData{
			GoodName:            v.ProductName,
			PlanGoodNumber:      v.OrderNum,
			Price:               v.Univalence,
			PartnerBonusPercent: v.PartnerRatio,
		}
		newGoods = append(newGoods, g)
	}
	companyId := c.GetUserCompany()
	updatecmd := orderCmd.UpdateOrderCommand{
		Id:                   param.Id,
		OrderType:            domain.OrderReal,
		OrderCode:            param.OrderId,
		DeliveryCode:         param.ShipmentsId,
		BuyerName:            param.BuyerName,
		OrderRegion:          param.OrderDist,
		PartnerId:            param.PartnerId,
		SalesmanBonusPercent: param.CommissionProportion,
		Goods:                newGoods,
		CompanyId:            companyId,
		PartnerCategory:      param.PartnerCategoryId,
		SaleDate:             saleDate,
	}
	orderSrv := orderService.NewOrderInfoService(nil)
	_, err := orderSrv.UpdateOrderData(updatecmd)
	return err
}

//OrderDisable 关闭开启订单,限实发订单可操作
func (c *OrderInfoController) OrderDisable() {
	//用与适配前端定义的数据结构
	type PostParameter struct {
		Id     string `json:"id"`
		Status int    `json:"status"`
	}
	var (
		param PostParameter
		err   error
	)
	if err = c.BindJsonData(&param); err != nil {
		logs.Error(err)
		c.ResponseError(errors.New("json数据解析失败"))
		return
	}
	orderId, _ := strconv.ParseInt(param.Id, 10, 64)
	if orderId == 0 {
		c.ResponseError(errors.New("参数错误"))
		return
	}
	if !(param.Status == domain.OrderDisableNot || param.Status == domain.OrderDisableYes) {
		c.ResponseError(errors.New("参数错误"))
		return
	}
	companyId := c.GetUserCompany()
	cmd := orderCmd.DisableOrderCommand{
		OrderId:   orderId,
		IsDisable: param.Status,
		OrderType: domain.OrderReal,
		CompanyId: companyId,
	}
	orderSrv := orderService.NewOrderInfoService(nil)
	err = orderSrv.DisableOrEnable(cmd)
	if err != nil {
		c.ResponseError(err)
	}
	c.ResponseData(nil)
	return
}

//RemoveOrderReal 删除意向订单
func (c *OrderInfoController) RemoveOrderReal() {
	type Parameter struct {
		Id string `json:"id"`
	}
	var (
		param Parameter
		err   error
	)
	if err = c.BindJsonData(&param); err != nil {
		logs.Error(err)
		c.ResponseError(errors.New("json数据解析失败"))
		return
	}
	companyId := c.GetUserCompany()
	id, _ := strconv.ParseInt(param.Id, 10, 64)
	orderSrv := orderService.NewOrderInfoService(nil)
	err = orderSrv.DeleteOrder(id, companyId)
	if err != nil {
		c.ResponseError(err)
		return
	}
	c.ResponseData(nil)
}

//ListOrderForExcel excel 导出实际订单的列表
func (c *OrderInfoController) ListOrderForExcel() {
	//type Parameter struct {
	//	PartnerName         string   `json:"partnerName"`         // 合伙人姓名
	//	OrderCode           string   `json:"orderCode"`           // 订单号
	//	DeliveryCode        string   `json:"deliveryCode"`        // 发货单号
	//	PartnerCategory     int      `json:"partnerCategory"`     // 合伙人类型
	//	PartnerCategoryName string   `json:"partnerCategoryName"` // 合伙人类型名称
	//	UpdateTime          []string `json:"updateTime"`          // 更新时间
	//	CreateTime          []string `json:"createTime"`          // 创建时间
	//	SaleDate            []string `json:"saleDate"`            // 销售日期
	//}

	var (
		//param Parameter
		param orderQuery.ListOrderForExcelQuery
		err   error
	)
	if err = c.BindJsonData(&param); err != nil {
		logs.Error(err)
		c.ResponseError(errors.New("json数据解析失败"))
		return
	}
	if param.Type != "ORDER_BASE" {
		logs.Error(err)
		c.ResponseError(errors.New("错误的操作类型"))
		return
	}
	// 订单更新时间
	var (
		updateTimeBegin string
		updateTimeEnd   string
	)
	if len(param.Where.UpdateTime) > 0 {
		if len(param.Where.UpdateTime[0]) > 0 {
			t, err := time.ParseInLocation("2006-01-02", param.Where.UpdateTime[0], time.Local)
			if err != nil {
				c.ResponseError(errors.New("UpdateTimeBegin 时间格式错误"))
				return
			}
			updateTimeBegin = t.Format("2006-01-02 15:04:05-07")
		}
	}
	if len(param.Where.UpdateTime) > 1 {
		if len(param.Where.UpdateTime[1]) > 0 {
			t, err := time.ParseInLocation("2006-01-02", param.Where.UpdateTime[1], time.Local)
			if err != nil {
				c.ResponseError(errors.New("UpdateTimeEnd 时间格式错误"))
				return
			}
			//设定时间边界
			t = t.Add(86399 * time.Second)
			updateTimeEnd = t.Format("2006-01-02 15:04:05-07")
		}
	}
	// 订单创建时间
	var (
		createTimeBegin string
		createTimeEnd   string
	)
	if len(param.Where.CreateTime) > 0 {
		if len(param.Where.CreateTime[0]) > 0 {
			t, err := time.ParseInLocation("2006-01-02", param.Where.CreateTime[0], time.Local)
			if err != nil {
				c.ResponseError(errors.New("UpdateTimeBegin 时间格式错误"))
				return
			}
			createTimeBegin = t.Format("2006-01-02 15:04:05-07")
		}
	}
	if len(param.Where.CreateTime) > 1 {
		if len(param.Where.CreateTime[1]) > 0 {
			t, err := time.ParseInLocation("2006-01-02", param.Where.CreateTime[1], time.Local)
			if err != nil {
				c.ResponseError(errors.New("UpdateTimeEnd 时间格式错误"))
				return
			}
			//设定时间边界
			t = t.Add(86399 * time.Second)
			createTimeEnd = t.Format("2006-01-02 15:04:05-07")
		}
	}
	// 订单销售时间处理
	var (
		saleDateBegin string
		saleDateEnd   string
	)
	if len(param.Where.SaleDate) > 0 {
		if len(param.Where.SaleDate[0]) > 0 {
			t, err := time.ParseInLocation("2006-01-02", param.Where.SaleDate[0], time.Local)
			if err != nil {
				c.ResponseError(errors.New("销售开始时间格式错误"))
				return
			}
			saleDateBegin = t.Format("2006-01-02 15:04:05-07")
		}
	}
	if len(param.Where.SaleDate) > 1 {
		if len(param.Where.SaleDate[1]) > 0 {
			t, err := time.ParseInLocation("2006-01-02", param.Where.SaleDate[1], time.Local)
			if err != nil {
				c.ResponseError(errors.New("销售结束时间格式错误"))
				return
			}
			//设定时间边界
			t = t.Add(86399 * time.Second)
			saleDateEnd = t.Format("2006-01-02 15:04:05-07")
		}
	}
	companyId := c.GetUserCompany()
	uid := c.GetUserId()
	orderSrv := orderService.NewOrderInfoService(nil)
	orderInfos, columns, err := orderSrv.ListOrderForExcel(orderQuery.ListOrderBaseQuery{
		PartnerName:         param.Where.PartnerName,
		OrderCode:           param.Where.OrderCode,
		DeliveryCode:        param.Where.DeliveryCode,
		OrderType:           domain.OrderReal,
		CompanyId:           companyId,
		Uid:                 uid,
		PartnerCategory:     param.Where.PartnerCategory,
		PartnerCategoryName: param.Where.PartnerCategoryName,
		UpdateTimeBegin:     updateTimeBegin,
		UpdateTimeEnd:       updateTimeEnd,
		CreateTimeBegin:     createTimeBegin,
		CreateTimeEnd:       createTimeEnd,
		SaleDateBegin:       saleDateBegin,
		SaleDateEnd:         saleDateEnd,
	})
	if err != nil {
		c.ResponseError(err)
		return
	}
	var excelHeaders []exceltool.ExcelHead
	for i := range columns {
		h := exceltool.ExcelHead{
			Key:  columns[i][0],
			Name: columns[i][1],
		}
		excelHeaders = append(excelHeaders, h)
	}
	excelMaker := exceltool.NewExcelMaker()
	excelMaker.SetListHead(excelHeaders)
	_ = excelMaker.MakeListExcel(orderInfos)
	_ = c.ResponseExcelByFile(c.Ctx, excelMaker)
	return
}

/**
 * @Author SteveChan
 * @Description // 下载导入模板
 * @Date 16:48 2021/1/8
 * @Param
 * @return
 **/
func (c *OrderInfoController) DownloadTemplate() {
	type Parameter struct {
		TYPE string `json:"type"`
	}

	var (
		param Parameter
		err   error
	)

	if err = c.BindJsonData(&param); err != nil {
		logs.Error(err)
		c.ResponseError(errors.New("json数据解析失败"))
		return
	}

	// 校验类型编码
	if param.TYPE != "PARTNER_ORDER_FILE" {
		c.ResponseError(errors.New("类型编码错误"))
	}

	// 创建下载文件夹
	mkErr := os.Mkdir("download", os.ModePerm)
	if mkErr != nil {
		fmt.Println(mkErr)
	}

	// 获取导入模板
	req := httplib.Get("http://suplus-file-dev.fjmaimaimai.com/upload/file/2021020111293523855.xlsx")
	err = req.ToFile(constant.IMPORT_EXCEL)
	if err != nil {
		logs.Error("could not save to file: ", err)
	}

	// 返回字段定义
	ret := map[string]interface{}{}

	resp, err := req.Response()
	if err != nil {
		logs.Error("could not get response: ", err)
	} else {
		logs.Info(resp)
		ret = map[string]interface{}{
			"url": "http://" + c.Ctx.Request.Host + "/" + constant.APP_NAME + "/download/订单数据模板.xlsx",
		}
		c.ResponseData(ret)
	}
}

/**
 * @Author SteveChan
 * @Description // 导入excel订单
 * @Date 10:52 2021/1/6
 * @Param
 * @return
 **/
func (c *OrderInfoController) ImportOrderFromExcel() {
	// 获取参数
	typeCode := c.GetString("type")
	file, h, _ := c.GetFile("file")
	companyId := c.GetUserCompany()

	if typeCode != "PARTNER_ORDER_FILE" {
		c.ResponseError(errors.New("类型编码错误"))
	}

	// 返回字段定义
	ret := map[string]interface{}{}

	// 返回信息表头定义 0: 订单号, 1: 发货单号, 2: 客户名称, 3: 订单区域, 4: 销售日期, 5: 编号, 6: 合伙人, 7: 类型, 8: 业务员抽成比例, 9: 产品名称, 10: 数量, 11: 单价, 12: 合伙人分红比例
	var tableHeader = []string{"错误详情", "行号", "订单号", "发货单号", "客户名称", "订单区域", "销售日期", "编号", "合伙人", "类型", "业务员抽成比例", "产品名称", "数量", "单价", "合伙人分红比例"}

	// 文件后缀名校验
	ext := path.Ext(h.Filename)
	AllowExtMap := map[string]bool{
		".xlsx": true,
	}
	if _, ok := AllowExtMap[ext]; !ok {
		c.ResponseError(errors.New("文件后缀名不符合上传要求,请上传正确格式的文件"))
		return
	}

	// 打开文件
	xlsx, err := excelize.OpenReader(file)
	if err != nil {
		c.ResponseError(errors.New("文件打开失败,请确定文件能够正常打开"))
		return
	}

	// 文件行数校验
	rows, _ := xlsx.GetRows("工作表1")
	if len(rows) > 303 {
		c.ResponseError(errors.New("导入文件的行数超过300行,请调整行数后重新导入"))
		return
	}

	// 文件列数据校验
	overColumnLine := make([]interface{}, 0)
	for i, row := range rows {
		if i > 2 && row != nil {
			if len(row) > constant.EXCEL_COLUMN {
				var tmpRow []string
				tmpRow = append(tmpRow, "存在无效的数据列,请删除无效的列数据") // 错误信息
				s := strconv.Itoa(i + 1)
				tmpRow = append(tmpRow, s)      // 行号
				tmpRow = append(tmpRow, row...) // 错误行数据
				overColumnLine = append(overColumnLine, tmpRow)
			}
		}
	}
	if len(overColumnLine) > 0 {
		ret = map[string]interface{}{
			"successCount": 0,
			"fail": map[string]interface{}{
				"tableHeader": tableHeader,
				"tableData":   overColumnLine,
			},
		}
		c.ResponseData(ret)
		return
	}

	// 数据行计数
	rowCnt := 0

	// 空文件校验
	if len(rows) < 3 {
		c.ResponseError(errors.New("导入的excel文件为空文件,请上传正确的文件"))
	}

	// 必填项校验
	nullLine := make([]interface{}, 0)

	nullFlag := false
	for i, row := range rows {
		if i > 2 && row != nil {
			rowCnt++
			if len(row) == constant.EXCEL_COLUMN { // 必填项内容为空
				var tmpRow = row
				nullCell := make([]interface{}, 0)
				var myRow []string
				for j, _ := range row {
					if j != 8 { // 业务员抽成比例非必填
						if row[j] == "" || row[j] == " " { // 空字符补位
							tmpRow[j] = ""
							col := strconv.Itoa(j + 1)
							nullCell = append(nullCell, col)
							nullFlag = true
						}
					}
				}
				if nullFlag {
					s := strconv.Itoa(i + 1)
					b := strings.Replace(strings.Trim(fmt.Sprint(nullCell), "[]"), " ", ",", -1)
					myRow = append(myRow, "第"+s+"行的第"+b+"列必填项为空") // 错误信息
					myRow = append(myRow, s)                      // 行号
					myRow = append(myRow, tmpRow...)              // 错误行数据
					nullLine = append(nullLine, myRow)
					nullFlag = false
				}
			} else if len(row) > 0 && len(row) < constant.EXCEL_COLUMN { // 必填项不存在
				var myRow []string
				myRow = append(myRow, "必填项为空")
				s := strconv.Itoa(i + 1)
				myRow = append(myRow, s)      // 行号
				myRow = append(myRow, row...) // 错误行数据
				emptyCell := make([]interface{}, 0)
				//  错误信息
				for k := 0; k < constant.EXCEL_COLUMN-len(row); k++ { // 空字符补位
					myRow = append(myRow, "")
				}
				for k, cell := range myRow {
					if k != 0 && cell == "" {
						emptyCell = append(emptyCell, k-1)
					}
				}
				b := strings.Replace(strings.Trim(fmt.Sprint(emptyCell), "[]"), " ", ",", -1)
				myRow[0] = "第" + s + "行的第" + b + "列必填项为空"
				nullLine = append(nullLine, myRow)
			}
		}
	}

	// 空单元格返回
	if len(nullLine) > 0 {
		ret = map[string]interface{}{
			"successCount": 0,
			"fail": map[string]interface{}{
				"tableHeader": tableHeader,
				"tableData":   nullLine,
			},
		}
		c.ResponseData(ret)
		return
	}

	// 内容校验
	errorLine := make([]interface{}, 0)
	var partnerType = []string{"事业合伙", "业务合伙", "研发合伙", "业务-产品应用合伙"}
	for i, row := range rows {
		if i > 2 && row != nil && len(row) == constant.EXCEL_COLUMN { // 数据行
			var myRow []string
			for j, cell := range row {

				r := strconv.Itoa(i + 1)
				col := strconv.Itoa(j + 1)

				switch j {
				case 0, 1, 2, 3, 5, 6, 9: // 订单号、发货单号、客户名称、订单区域、编号、合伙人、产品名称长度校验
					{
						cellStr := strings.TrimSpace(cell)
						lenCellStr := utf8.RuneCountInString(cellStr)

						if lenCellStr > 50 {
							var tmpRow []string
							tmpRow = append(tmpRow, "第"+r+"行第"+col+"列"+tableHeader[j+2]+"长度超过50位,请重新输入") // 错误信息
							tmpRow = append(tmpRow, r)                                                   // 行号
							tmpRow = append(tmpRow, row...)                                              // 错误行数据
							myRow = tmpRow
						}
					}
				case 4: // 销售日期格式和有效性校验
					{
						regexpStr := `(\d{4})/(\d{2})/(\d{2})`
						ok := regexp.MustCompile(regexpStr).MatchString(cell)
						if !ok {
							var tmpRow []string
							tmpRow = append(tmpRow, "第"+r+"行第"+col+"列销售日期格式错误,请输入正确的销售日期") // 错误信息
							tmpRow = append(tmpRow, r)                                     // 行号
							tmpRow = append(tmpRow, row...)                                // 错误行数据
							myRow = tmpRow
						}
					}
				case 7: // 合伙人类型校验(事业合伙、业务合伙、研发合伙、业务-产品应用合伙)
					{
						if !utils.IsContain(partnerType, cell) {
							var tmpRow []string
							tmpRow = append(tmpRow, "第"+r+"行第"+col+"列合伙人类型错误,合伙人类型必须为以下类型:事业合伙、业务合伙、研发合伙、业务-产品应用合伙") // 错误信息
							tmpRow = append(tmpRow, r)                                                               // 行号
							tmpRow = append(tmpRow, row...)                                                          // 错误行数据
							myRow = tmpRow
						}
					}
				case 8: // 业务员抽成比例,非必填,精确到小数点后两位
					{
						if len(cell) > 0 {

							// 参数类型转换
							shareRatio, err := strconv.ParseFloat(cell, 64)
							if err != nil {
								var tmpRow []string
								tmpRow = append(tmpRow, "第"+r+"行第"+col+"列业务员抽成比例格式错误,业务员抽成比例必须为数字") // 错误信息
								tmpRow = append(tmpRow, r)                                          // 行号
								tmpRow = append(tmpRow, row...)                                     // 错误行数据
								myRow = tmpRow
							}

							// 比例不能超过100%
							if shareRatio > 100 {
								var tmpRow []string
								tmpRow = append(tmpRow, "第"+r+"行第"+col+"列业务员抽成比例超过限额,请输入正确的业务员抽成比例,并保留两位小数") // 错误信息
								tmpRow = append(tmpRow, r)                                                   // 行号
								tmpRow = append(tmpRow, row...)                                              // 错误行数据
								myRow = tmpRow
							}

							// 长度校验
							regexpStr := `^(100|[1-9]\d|\d)(.\d{1,2})?$`
							ok := regexp.MustCompile(regexpStr).MatchString(cell)
							if !ok {
								var tmpRow []string
								tmpRow = append(tmpRow, "第"+r+"行第"+col+"列业务员抽成比例超过最大长度,请输入正确的业务员抽成比例,并保留两位小数") // 错误信息
								tmpRow = append(tmpRow, r)                                                     // 行号
								tmpRow = append(tmpRow, row...)                                                // 错误行数据
								myRow = tmpRow
							}
						}
					}
				case 10: // 产品数量不超过16位正整数
					{
						//参数类型转换
						orderNum, err := strconv.ParseInt(cell, 10, 64)
						if err != nil {
							var tmpRow []string
							tmpRow = append(tmpRow, "第"+r+"行第"+col+"列产品数量格式错误,产品数量必须整数") // 错误信息
							tmpRow = append(tmpRow, r)                                   // 行号
							tmpRow = append(tmpRow, row...)                              // 错误行数据
							myRow = tmpRow
						}

						// 长度校验
						if orderNum > 1e16 {
							var tmpRow []string
							tmpRow = append(tmpRow, "第"+r+"行第"+col+"列产品数量长度超过最大限制十六位整数,请重新填写") // 错误信息
							tmpRow = append(tmpRow, r)                                         // 行号
							tmpRow = append(tmpRow, row...)                                    // 错误行数据
							myRow = tmpRow
						}
					}
				case 11: // 单价,精确到小数点后两位,小数点左侧最多可输入16位数字
					{

						// 参数类型转换
						univalent, typeErr := strconv.ParseFloat(cell, 64)
						if typeErr != nil {
							var tmpRow []string
							tmpRow = append(tmpRow, "第"+r+"行第"+col+"列单价格式错误,产品单价必须为数字类型") // 错误信息
							tmpRow = append(tmpRow, r)                                    // 行号
							tmpRow = append(tmpRow, row...)                               // 错误行数据
							myRow = tmpRow
						}

						// 长度校验
						if univalent >= 1e16 {
							var tmpRow []string
							tmpRow = append(tmpRow, "第"+r+"行第"+col+"列产品单价超过最大限制,产品单价小数点前面不能超过十六位数字,并保留两位小数") // 错误信息
							tmpRow = append(tmpRow, r)                                                       // 行号
							tmpRow = append(tmpRow, row...)                                                  // 错误行数据
							myRow = tmpRow
						}
					}
				case 12: // 合伙人分红比例,精确到小数点后两位
					{
						//参数类型转换
						partnerRatio, parseErr := strconv.ParseFloat(cell, 64)
						if parseErr != nil {
							var tmpRow []string
							tmpRow = append(tmpRow, "第"+r+"行第"+col+"列合伙人分红比例类型错误,合伙人分红比例必须为数字") // 错误信息
							tmpRow = append(tmpRow, r)                                          // 行号
							tmpRow = append(tmpRow, row...)                                     // 错误行数据
							myRow = tmpRow
						}

						// 合伙人分红比例超额
						if partnerRatio > 100 {
							var tmpRow []string
							tmpRow = append(tmpRow, "第"+r+"行第"+col+"列合伙人分红比例超过限额,请输入正确的合伙人分红比例,并保留两位小数") // 错误信息
							tmpRow = append(tmpRow, r)                                                   // 行号
							tmpRow = append(tmpRow, row...)                                              // 错误行数据
							myRow = tmpRow
						}

						// 长度判断
						regexpStr := `^(100|[1-9]\d|\d)(.\d{1,2})?$`
						ok := regexp.MustCompile(regexpStr).MatchString(cell)
						if !ok {
							var tmpRow []string
							tmpRow = append(tmpRow, "第"+r+"行第"+col+"列合伙人分红比例超过最大长度,请输入正确的合伙人分红比例,并保留两位小数") // 错误信息
							tmpRow = append(tmpRow, r)                                                     // 行号
							tmpRow = append(tmpRow, row...)                                                // 错误行数据
							myRow = tmpRow
						}
					}
				}
			}
			if myRow != nil {
				errorLine = append(errorLine, myRow)
			}
		}
	}

	// 内容错误行返回
	if len(errorLine) > 0 {
		ret = map[string]interface{}{
			"successCount": 0,
			"fail": map[string]interface{}{
				"tableHeader": tableHeader,
				"tableData":   errorLine,
			},
		}
		c.ResponseData(ret)
		return
	}

	// 创建订单服务
	orderSrv := orderService.NewOrderInfoService(nil)

	// 合伙人检索错误
	partnerDataList := make([]interface{}, 0)

	// 聚合订单产品
	var orderCommands = make(map[string]*orderCmd.CreateOrderCommand, 0)
	for i, row := range rows {
		if i > 2 && len(row) == constant.EXCEL_COLUMN {
			hashValue := md5.Sum([]byte(row[0] + row[1] + row[5] + row[7])) // 根据:订单号+发货单号+合伙人编号+合伙类型计算哈希值
			hashString := hex.EncodeToString(hashValue[:])

			if _, ok := orderCommands[hashString]; !ok {
				//订单相关,0: 订单号, 1: 发货单号, 2: 客户名称, 3: 订单区域, 4: 销售日期, 5: 编号, 6: 合伙人, 7: 类型, 8: 业务抽成比例,
				sbPercent, _ := strconv.ParseFloat(row[8], 64) //业务抽成比例

				//产品相关,9: 产品名称, 10: 数量, 11: 单价, 12: 合伙人分红比例
				amount, _ := strconv.ParseInt(row[10], 10, 64) // 数量
				price, _ := strconv.ParseFloat(row[11], 64)    // 单价
				percent, _ := strconv.ParseFloat(row[12], 64)  // 合伙人分红比例

				// 获取partnerId
				var partnerInfo *domain.PartnerInfo

				// 5: 合伙人编号
				orderQueryData := orderQuery.GetPartnerIdQuery{
					Code:            row[5],
					PartnerCategory: 0,
					CompanyId:       companyId,
				}

				// 7: 合伙人类型 1: 事业合伙、2: 业务合伙、3: 研发合伙、4: 业务-产品应用合伙
				switch row[7] {
				case "事业合伙":
					orderQueryData.PartnerCategory = 1
				case "业务合伙":
					orderQueryData.PartnerCategory = 2
				case "研发合伙":
					orderQueryData.PartnerCategory = 3
				case "业务-产品应用合伙":
					orderQueryData.PartnerCategory = 4
				default:
					orderQueryData.PartnerCategory = 0
				}

				// 销售日期时间格式转换
				timeValue, err := time.ParseInLocation("2006/01/02", row[4], time.Local)
				if err != nil {
					var tmpRow []string
					tmpRow = append(tmpRow, "无效的销售日期") // 错误信息
					s := strconv.Itoa(i + 1)
					tmpRow = append(tmpRow, s)      // 行号
					tmpRow = append(tmpRow, row...) // 错误行数据
					partnerDataList = append(partnerDataList, tmpRow)
					break
				}

				saleDateWithTz := time.Date(timeValue.Year(), timeValue.Month(), timeValue.Day(), time.Now().Hour(), time.Now().Minute(), time.Now().Second(), time.Now().Nanosecond(), time.Local)

				fmt.Print("销售日期:", saleDateWithTz, "\n")

				// 初始化建订单命令集
				orderCommands[hashString] = &orderCmd.CreateOrderCommand{
					OrderType:            0,
					OrderCode:            row[0],
					DeliveryCode:         row[1],
					BuyerName:            row[2],
					OrderRegion:          row[3],
					SaleDate:             saleDateWithTz,
					PartnerId:            0, // 根据合伙人类型+合伙人编号查找合伙人id
					SalesmanBonusPercent: sbPercent,
					Goods: []orderCmd.OrderGoodData{
						{
							GoodName:            row[9],
							PlanGoodNumber:      int(amount),
							Price:               price,
							PartnerBonusPercent: percent,
							LineNumber:          i,
						},
					},
					CompanyId:       companyId,
					PartnerCategory: int64(orderQueryData.PartnerCategory),
					LineNumbers:     []int{i}, // 记录行号
				}

				partnerInfo, err = orderSrv.GetPartnerIdByCodeAndCategory(orderQueryData)
				if err != nil || partnerInfo == nil { // 检索合伙人错误
					var tmpRow []string
					tmpRow = append(tmpRow, err.Error()) // 错误信息
					s := strconv.Itoa(i + 1)
					tmpRow = append(tmpRow, s)      // 行号
					tmpRow = append(tmpRow, row...) // 错误行数据
					partnerDataList = append(partnerDataList, tmpRow)
				}
				if partnerInfo != nil {
					orderCommands[hashString].PartnerId = partnerInfo.Partner.Id
				}
			} else {
				//产品相关,9: 产品名称, 10: 数量, 11: 单价, 12: 合伙人分红比例
				amount, _ := strconv.ParseInt(row[10], 10, 64) // 数量
				price, _ := strconv.ParseFloat(row[11], 64)    // 单价
				percent, _ := strconv.ParseFloat(row[12], 64)  // 合伙人分红比例

				// 记录同一笔订单产品
				orderCommands[hashString].Goods = append(orderCommands[hashString].Goods, orderCmd.OrderGoodData{
					GoodName:            row[9],
					PlanGoodNumber:      int(amount),
					Price:               price,
					PartnerBonusPercent: percent,
					LineNumber:          i, // 记录行号
				})

				// 记录聚合行号
				orderCommands[hashString].LineNumbers = append(orderCommands[hashString].LineNumbers, i)
			}
		}
	}
	if len(partnerDataList) > 0 {
		ret = map[string]interface{}{
			"successCount": 0,
			"fail": map[string]interface{}{
				"tableHeader": tableHeader,
				"tableData":   partnerDataList,
			},
		}
		c.ResponseData(ret)
		return
	}

	// 产品数量校验
	productNumberError := make([]interface{}, 0)

	// 批量创建订单命令集和产品数量校验
	var createOrderCommands []*orderCmd.CreateOrderCommand
	for _, orderCommand := range orderCommands {
		if len(orderCommand.Goods) > 50 { // 产品数量校验
			for _, line := range orderCommand.LineNumbers {
				var tmpRow []string
				tmpRow = append(tmpRow, "单笔订单产品超过50种") // 错误信息
				s := strconv.Itoa(line + 1)
				tmpRow = append(tmpRow, s)             // 行号
				tmpRow = append(tmpRow, rows[line]...) // 错误行数据
				productNumberError = append(productNumberError, tmpRow)
			}
		} else {
			createOrderCommands = append(createOrderCommands, orderCommand)
		}
	}

	if len(productNumberError) > 0 {
		ret = map[string]interface{}{
			"successCount": 0,
			"fail": map[string]interface{}{
				"tableHeader": tableHeader,
				"tableData":   productNumberError,
			},
		}
		c.ResponseData(ret)
		return
	}

	// 新增失败记录
	failureDataList := make([]interface{}, 0)

	// 新增成功记录计数
	var successDataCount int64

	// 批量新增订单
	errorDataList, createError := orderSrv.CreateNewOrderByImport(createOrderCommands)
	if createError != nil {
		c.ResponseError(createError)
		return
	} else {
		if len(errorDataList) > 0 { // 导入失败返回
			successDataCount = 0
			// 错误记录处理
			for _, errorData := range errorDataList {
				if len(errorData.GoodLine) == 0 { // 订单错误
					for _, line := range errorData.LineNumbers {
						var tmpRow []string
						tmpRow = append(tmpRow, errorData.Error.Error()) // 错误信息
						s := strconv.Itoa(line + 1)
						tmpRow = append(tmpRow, s)             // 行号
						tmpRow = append(tmpRow, rows[line]...) // 错误行数据
						failureDataList = append(failureDataList, tmpRow)
					}
				} else if len(errorData.GoodLine) > 0 { // 订单产品错误
					for line := range errorData.GoodLine {
						var tmpRow []string
						tmpRow = append(tmpRow, errorData.Error.Error()) // 错误信息
						s := strconv.Itoa(line + 1)
						tmpRow = append(tmpRow, s)             // 行号
						tmpRow = append(tmpRow, rows[line]...) // 错误行数据
						failureDataList = append(failureDataList, tmpRow)
					}
				}
			}

			ret = map[string]interface{}{
				"successCount": successDataCount,
				"fail": map[string]interface{}{
					"tableHeader": tableHeader,
					"tableData":   failureDataList,
				},
			}
		} else { // 导入成功返回
			successDataCount = int64(rowCnt - len(failureDataList))
			if successDataCount == int64(rowCnt) {
				ret = map[string]interface{}{
					"successCount": successDataCount,
					"fail":         nil,
				}
			}
		}
	}

	// 返回错误详情
	c.ResponseData(ret)
	return
}