employee.go 36.3 KB
Newer Older
haoyanbin's avatar
1  
haoyanbin committed
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 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401
package repository

import (
	"database/sql"
	"errors"
	"fmt"
	"gin-vue-admin/models"
	"strconv"
	"strings"
	"time"

	"github.com/uniplaces/carbon"
)

// QueryUserList 查询用户列表
func QueryEmployeeList(db *sql.DB, t string, HospitalLocalId int) (interface{}, error) {

	var format string

	if len(t) == 10 {
		format = "%Y-%m-%d"
	} else if len(t) == 7 {
		format = "%Y-%m"
	} else if len(t) == 4 {
		format = "%Y"
	} else {
		return nil, errors.New("time error")
	}

	response := make([]models.Employee, 0)

	rows, err := db.Query(`select e.id, e.image_uri, e._name, e.con_role_id, ifnull(r._name, ''), e.job_state
from con_employee as e
	left join con_role as r on r.id = e.con_role_id
	where e.con_role_id != 0 and e.job_state = 0 and e.sys_hospital_id = ? 
	ORDER BY job_state DESC`, HospitalLocalId)

	if err != nil {
		return nil, err
	}

	var r models.EmployeeManage

	for rows.Next() {
		var t models.Employee
		var roleID int
		// 获取员工的相关信息
		err = rows.Scan(&t.ID, &t.ImageURL, &t.EmployeeName, &roleID, &t.RoleName, &t.JobState)
		if err != nil {
			return nil, err
		}
		t.Royalty = 0
		//t.BillNumber = 0
		response = append(response, t)
	}

	sqlStr := `select c.sale_type,
ifnull(convert(c.sale_price / 1000, decimal(11,3)), 0),
ifnull(convert(c.sale_percent / 1000, decimal(11,3)), 0), 
c.service_type,
ifnull(convert(c.service_price / 1000, decimal(11,3)), 0),
ifnull(convert(c.service_percent / 1000, decimal(11,3)), 0), 
ifnull(convert(c.quantity*c.payprice / 1000000, decimal(11,3)), 0),
ifnull(convert(c.quantity / 1000, decimal(11,3)), 0),
c.sale_employee_id, 
c.service_employee_id
from his_consumption as c
left join his_bill as b on b.id = c.his_bill_id
where c.delflag = 0 and c.his_retreatbill_id = 0 
and c.commodity_ismeal = 0
and c.meter_num = 0
and b.billtype in (1,4,6,7)
and DATE_FORMAT(b.paytime, ?) = ?
and c.sale_employee_id = ? 
and c.sys_hospital_id = ? `

	// 计算营业额 和 提成
	for k, v := range response {

		// 计算提成

		rows, err = db.Query(sqlStr, format, t, v.ID, HospitalLocalId)
		if err != nil {
			return nil, err
		}

		for rows.Next() {

			var saleType, serviceType int
			var saleEmployeeID, serviceEmployeeID int64
			var salePrice, salePercent, servicePrice, servicePercent float64
			var consumptionPrice, quantity float64

			err = rows.Scan(&saleType, &salePrice, &salePercent, &serviceType, &servicePrice, &servicePercent,
				&consumptionPrice, &quantity, &saleEmployeeID, &serviceEmployeeID)
			if err != nil {
				return nil, err
			}

			if saleEmployeeID == v.ID {
				r.SumMoney += consumptionPrice
				if saleType == 1 { // 按金额
					response[k].Royalty += quantity * salePrice
				} else if saleType == 2 { // 按百分比
					if salePercent != 0 {
						response[k].Royalty += consumptionPrice * (salePercent / 100)
					}
				}
			}

			if serviceEmployeeID == v.ID {
				if serviceType == 1 { // 按金额
					response[k].Royalty += quantity * servicePrice
				} else if serviceType == 2 { // 按百分比
					if servicePercent != 0 {
						response[k].Royalty += consumptionPrice * (servicePercent / 100)
					}
				}
			}
		}

		r.SumRoyalty += response[k].Royalty

		meterCardRecharge, err := MeterCardRecharge(db, t, format, int(v.ID), HospitalLocalId)
		if err != nil {
			return nil, err
		}
		r.SumMoney += meterCardRecharge
	}

	r.Employees = response

	return r, nil
}

func QueryEmployeeDetailList(db *sql.DB, HospitalLocalId int) (interface{}, error) {

	response := make([]models.Employee, 0)

	rows, err := db.Query(`select e.id, e.image_uri, e._name, e.con_role_id, ifnull(r._name, ''), e.job_state
from con_employee as e
	left join con_role as r on r.id = e.con_role_id
	where e.con_role_id != 0 and e.job_state = 0 and e.sys_hospital_id = ? 
	ORDER BY job_state DESC`, HospitalLocalId)

	if err != nil {
		return nil, err
	}

	for rows.Next() {
		var t models.Employee
		var roleID int
		// 获取员工的相关信息
		err = rows.Scan(&t.ID, &t.ImageURL, &t.EmployeeName, &roleID, &t.RoleName, &t.JobState)
		if err != nil {
			return nil, err
		}
		t.Royalty = 0
		//t.BillNumber = 0
		response = append(response, t)
	}

	return response, nil
}

// 查询员工 工作记录信息
func QueryEmployeeByID(db *sql.DB, t string, employeeID int) (interface{}, error) {

	hospitalLocalId, err := QueryHospitalLocalIDByEmployeeLocalID(db, employeeID)
	if err != nil {
		return nil, err
	}

	var formatSQL, formatTime string
	var sub int

	if len(t) == 10 {
		formatSQL = "%Y-%m-%d"
		formatTime = "2006-01-02"
		sub = 6
	} else if len(t) == 7 {
		formatSQL = "%Y-%m"
		formatTime = "2006-01"
		sub = 6
	} else if len(t) == 4 {
		formatSQL = "%Y"
		formatTime = "2006"
		sub = 3
	} else {
		return nil, errors.New("time error")
	}

	var anEmployee models.AnEmployee

	// 工作趋势

	c, err := carbon.Parse(formatTime, t, "UTC")
	if err != nil {
		return nil, err
	}

	var endT *carbon.Carbon
	var endTime string

	if len(t) == 10 {
		endT = c.SubDays(sub)
		endTime = c.SubDays(sub).Format(formatTime)
	} else if len(t) == 7 {
		endT = c.SubMonths(sub)
		endTime = c.SubMonths(sub).Format(formatTime)
	} else if len(t) == 4 {
		endT = c.SubYears(sub)
		endTime = c.SubYears(sub).Format(formatTime)
	} else {
		return nil, errors.New("time error")
	}

	res := make([]*models.WorkTrendData, 0)

	// 把每个时间都抽出来
	temp := make(map[string]*models.WorkTrend, 0)

	// 业绩额 - 这个人卖出去的商品的总额
	// 提成 -  这个人卖出去的商品的总额 的提成

	sqlStr := `select c.sale_type,
ifnull(convert(c.sale_price / 1000, decimal(11,3)), 0),
ifnull(convert(c.sale_percent / 1000, decimal(11,3)), 0), 
c.service_type,
ifnull(convert(c.service_price / 1000, decimal(11,3)), 0),
ifnull(convert(c.service_percent / 1000, decimal(11,3)), 0), 
ifnull(convert(c.quantity*c.payprice / 1000000, decimal(11,3)), 0),
ifnull(convert(c.quantity / 1000, decimal(11,3)), 0),
sale_employee_id, 
service_employee_id, 
DATE_FORMAT(b.paytime, ?)
from his_consumption as c
left join his_bill as b on b.id = c.his_bill_id
where c.delflag = 0 and c.his_retreatbill_id = 0 
and c.commodity_ismeal = 0
and c.meter_num = 0
and b.billtype in (1,4,6,7)
and DATE_FORMAT(b.paytime, ?) >= ? 
and DATE_FORMAT(b.paytime, ?) <= ? 
and c.sale_employee_id = ? 
and c.sys_hospital_id in (0,?) 
`

	rows, err := db.Query(sqlStr, formatSQL, formatSQL, endTime, formatSQL, t, employeeID, hospitalLocalId)
	if err != nil {
		return nil, err
	}

	for rows.Next() {

		var saleType, serviceType, saleEmployeeID, serviceEmployeeID int
		var salePrice, salePercent, servicePrice, servicePercent float64
		var consumptionPrice, quantity float64
		var billTime string

		err = rows.Scan(&saleType, &salePrice, &salePercent, &serviceType, &servicePrice, &servicePercent,
			&consumptionPrice, &quantity, &saleEmployeeID, &serviceEmployeeID, &billTime)
		if err != nil {
			return nil, err
		}

		// 如果没有、则加入一个
		if _, ok := temp[billTime]; !ok {
			r := new(models.WorkTrend)
			temp[billTime] = r
		}

		if _, ok := temp[billTime]; ok {

			// 计算出当天的、某一条商品的销售提成 和 服务提成
			if saleEmployeeID == employeeID {

				temp[billTime].Money += consumptionPrice

				if t == billTime {
					anEmployee.SumMoney += consumptionPrice
				}

				if saleType == 1 { // 按金额
					temp[billTime].Royalty += quantity * salePrice
				} else if saleType == 2 { // 按百分比
					if salePercent != 0 {
						temp[billTime].Royalty += consumptionPrice * (salePercent / 100)
					}
				}
			}
			if serviceEmployeeID == employeeID {
				if serviceType == 1 { // 按金额
					temp[billTime].Royalty += quantity * servicePrice
				} else if serviceType == 2 { // 按百分比
					if servicePercent != 0 {
						temp[billTime].Royalty += consumptionPrice * (servicePercent / 100)
					}
				}
			}
			if t == billTime {
				anEmployee.SumRoyalty = temp[billTime].Royalty
			}
		}
	}

	// 工作趋势

	for i := 0; i <= sub; i++ {
		var str string
		if len(t) == 10 {
			str = endT.AddDays(i).Format(formatTime)
		} else if len(t) == 7 {
			str = endT.AddMonths(i).Format(formatTime)
		} else {
			str = endT.AddYears(i).Format(formatTime)
		}

		meterCardRecharge, err := MeterCardRecharge(db, t, formatSQL, employeeID, hospitalLocalId)
		if err != nil {
			return nil, err
		}

		if _, ok := temp[str]; ok {
			y1 := new(models.WorkTrendData)
			y1.Year = str
			y1.Type = "业绩额"
			y1.Value = temp[str].Money + meterCardRecharge
			y2 := new(models.WorkTrendData)
			y2.Year = str
			y2.Type = "提成"
			y2.Value = temp[str].Royalty
			res = append(res, y1, y2)
		} else {
			y1 := new(models.WorkTrendData)
			y1.Year = str
			y1.Type = "业绩额"
			y1.Value = meterCardRecharge
			y2 := new(models.WorkTrendData)
			y2.Year = str
			y2.Type = "提成"
			res = append(res, y1, y2)
		}
	}

	meterCardRecharge, err := MeterCardRecharge(db, t, formatSQL, employeeID, hospitalLocalId)
	if err != nil {
		return nil, err
	}

	anEmployee.SumMoney += meterCardRecharge

	anEmployee.WorkTrends = res

	return anEmployee, nil
}

// 查询员工销售列表
func QueryEmployeeSaleRoyalty(db *sql.DB, t string, employeeID int) (interface{}, error) {

	hospitalLocalId, err := QueryHospitalLocalIDByEmployeeLocalID(db, employeeID)
	if err != nil {
		return nil, err
	}

	var formatSQL string

	if len(t) == 10 {
		formatSQL = "%Y-%m-%d"
	} else if len(t) == 7 {
		formatSQL = "%Y-%m"
	} else if len(t) == 4 {
		formatSQL = "%Y"
	} else {
		return nil, errors.New("time error")
	}

	rows, err := db.Query(`select c.id, ifnull(c.commodity_name, ''), ifnull(category._name, ''),  
convert(c.quantity / 1000, decimal(11,3)), 
convert(c.payprice / 1000, decimal(11,3)), 
convert(c.sale_price / 1000, decimal(11,3)),
convert(c.sale_percent / 1000, decimal(11,3)),
c.sale_type
from his_consumption as c
left join his_bill as b on b.id = c.his_bill_id
left join con_category as category on category.id = c.con_category_id
where c.delflag = 0 and c.his_retreatbill_id = 0 
and c.commodity_ismeal = 0 
and c.meter_num = 0
and b.billtype in (1,4,6,7)
and DATE_FORMAT(b.paytime, ?) = ? 
and sale_employee_id = ?
and c.sys_hospital_id in (0,?)  `, formatSQL, t, employeeID, hospitalLocalId)
	if err != nil {
		return nil, err
	}

	res := make([]*models.Sale, 0)
	resTemp := make(map[string]*models.Sale, 0)

	sale := new(models.Sale)
	sale.Date = t
	sale.Seledetail = make([]models.Seledetail, 0)
	res = append(res, sale)
	resTemp[t] = sale

	for rows.Next() {
		var r models.Seledetail
		var saleType int
		var salePrice, salePercent float64
		err = rows.Scan(&r.ID, &r.Project, &r.Projecttype, &r.Num, &r.Amount, &salePrice, &salePercent, &saleType)
		if err != nil {
			return nil, err
		}

		sumPrice := r.Num * r.Amount
		r.Amount = sumPrice

		if saleType == 1 { // 按金额
			r.Royalty = r.Num * salePrice
		} else if saleType == 2 { // 按百分比
			if salePercent != 0 {
				r.Royalty = sumPrice * (salePercent / 100)
			}
		}

		resTemp[t].Sale++
		resTemp[t].Amounts += r.Royalty
		resTemp[t].Seledetail = append(resTemp[t].Seledetail, r)
	}

	return res, nil
}

// 查询员工服务列表
func QueryEmployeeServiceRoyalty(db *sql.DB, t string, employeeID int) (interface{}, error) {

	hospitalLocalId, err := QueryHospitalLocalIDByEmployeeLocalID(db, employeeID)
	if err != nil {
		return nil, err
	}

	var formatSQL string

	if len(t) == 10 {
		formatSQL = "%Y-%m-%d"
	} else if len(t) == 7 {
		formatSQL = "%Y-%m"
	} else if len(t) == 4 {
		formatSQL = "%Y"
	} else {
		return nil, errors.New("time error")
	}

	rows, err := db.Query(`select c.id, ifnull(c.commodity_name, ''), ifnull(category._name, ''), 
convert(c.quantity / 1000, decimal(11,3)), 
convert(c.payprice / 1000, decimal(11,3)), 
convert(c.service_price / 1000, decimal(11,3)),
convert(c.service_percent / 1000, decimal(11,3)),
c.service_type
from his_consumption as c
left join his_bill as b on b.id = c.his_bill_id
left join con_category as category on category.id = c.con_category_id
where c.delflag = 0 and c.his_retreatbill_id = 0 
and c.commodity_ismeal = 0 
and c.meter_num = 0
and b.billtype in (1,4,6,7)
and DATE_FORMAT(b.paytime, ?) = ?
and c.service_employee_id = ?
and c.sys_hospital_id in (0,?)  `, formatSQL, t, employeeID, hospitalLocalId)
	if err != nil {
		return nil, err
	}

	res := make([]*models.Sale, 0)
	resTemp := make(map[string]*models.Sale, 0)

	sale := new(models.Sale)
	sale.Date = t
	sale.Seledetail = make([]models.Seledetail, 0)
	res = append(res, sale)
	resTemp[t] = sale

	for rows.Next() {
		var r models.Seledetail
		var serviceType int
		var servicePrice, servicePercent float64

		err = rows.Scan(&r.ID, &r.Project, &r.Projecttype, &r.Num, &r.Amount, &servicePrice, &servicePercent, &serviceType)
		if err != nil {
			return nil, err
		}

		sumPrice := r.Num * r.Amount
		r.Amount = sumPrice

		if serviceType == 1 { // 按金额
			r.Royalty = r.Num * servicePrice
		} else if serviceType == 2 { // 按百分比
			if servicePercent != 0 {
				r.Royalty = sumPrice * (servicePercent / 100)
			}
		}
		resTemp[t].Sale++
		resTemp[t].Amounts += r.Royalty
		resTemp[t].Seledetail = append(resTemp[t].Seledetail, r)
	}

	return res, nil
}

// 查询员工业绩列表
func QueryEmployeeAchievement(db *sql.DB, t string, employeeID int) (interface{}, error) {

	hospitalLocalId, err := QueryHospitalLocalIDByEmployeeLocalID(db, employeeID)
	if err != nil {
		return nil, err
	}

	// 查出数据

	// 计算时间 及格式化的模板
	var formatSQL string

	if len(t) == 10 {
		formatSQL = "%Y-%m-%d"
	} else if len(t) == 7 {
		formatSQL = "%Y-%m"
	} else if len(t) == 4 {
		formatSQL = "%Y"
	} else {
		return nil, errors.New("time error")
	}

	// 查这个员工所有的 已结订单
	rows, err := db.Query(`select id from his_bill
where delflag = 0 
and billtype in (1,4,6,7)
and DATE_FORMAT(billtime, ?) = ?
and sys_hospital_id in (0,?)  `, formatSQL, t, hospitalLocalId)
	if err != nil {
		return nil, err
	}

	bills := make([]string, 0)
	for rows.Next() {

		var billID int
		err = rows.Scan(&billID)
		if err != nil {
			return nil, err
		}

		bills = append(bills, fmt.Sprintf("%v", billID))
	}

	response := make([]*models.EmployeeAchievement, 0)

	if len(bills) <= 0 {
		return response, nil
	}

	billIDs := strings.Join(bills, ",")

	rows, err = db.Query(fmt.Sprintf(`select 
ifnull(convert(sum(quantity*payprice) / 1000000, decimal(11,3)), 0) as money,
bussinesstype
from his_consumption
where delflag = 0 
and his_retreatbill_id = 0 
and commodity_ismeal = 0
and meter_num = 0
and his_bill_id in (%s)
and sale_employee_id = ?
GROUP BY bussinesstype`, billIDs), employeeID)
	if err != nil {
		return nil, err
	}

	// 构建结构

	// DB:
	// 1:商品销售 2:挂号 3:住院每日消费 4.住院门诊 41:住院门诊化验  42:住院门诊影像 43:住院门诊处方
	// 44:住院门诊手术 45:住院门诊处置  5:住院商品销售 6:普通门诊 61:普通门诊化验  62:普通门诊影像
	// 63:普通门诊处方 64:普通门诊手术 65:普通门诊处置 7:美容 8:寄养每日消费 9:寄养商品销售 10:疫苗 11:驱虫

	//correspondingType := map[int]string{
	//	1:  "1",
	//	2:  "2",
	//	3:  "3,4,5,6",
	//	4:  "41,61",
	//	5:  "42,62",
	//	6:  "43,63",
	//	7:  "44,64",
	//	8:  "45,65",
	//	9:  "7",
	//	10: "8,9",
	//	11: "10",
	//	12: "11",
	//}

	// Map
	// 1 商品销售
	// 2 挂号
	// 3 住院每日消费
	// 4 化验
	// 5 影像
	// 6 处方
	// 7 手术
	// 8 处置
	// 9 美容
	// 10 寄养
	// 11 疫苗
	// 12 驱虫

	tempRes := map[int]*models.EmployeeAchievement{
		1:  {},
		2:  {},
		3:  {},
		4:  {},
		5:  {},
		6:  {},
		7:  {},
		8:  {},
		9:  {},
		10: {},
		11: {},
		12: {},
	}
	for businessType := range tempRes {
		temp := new(models.EmployeeAchievement)
		switch businessType {
		case 1:
			temp.Item = "商品销售"
			tempRes[1] = temp
		case 2:
			temp.Item = "挂号"
			tempRes[2] = temp
		case 3:
			temp.Item = "住院"
			tempRes[3] = temp
		case 4:
			temp.Item = "化验"
			tempRes[4] = temp
		case 5:
			temp.Item = "影像"
			tempRes[5] = temp
		case 6:
			temp.Item = "处方"
			tempRes[6] = temp
		case 7:
			temp.Item = "手术"
			tempRes[7] = temp
		case 8:
			temp.Item = "处置"
			tempRes[8] = temp
		case 9:
			temp.Item = "美容"
			tempRes[9] = temp
		case 10:
			temp.Item = "寄养"
			tempRes[10] = temp
		case 11:
			temp.Item = "疫苗"
			tempRes[11] = temp
		case 12:
			temp.Item = "驱虫"
			tempRes[12] = temp
		}
	}

	for rows.Next() {

		temp := new(models.EmployeeAchievement)
		var businessType int
		err = rows.Scan(&temp.Amount, &businessType)
		if err != nil {
			return nil, err
		}
		switch businessType {
		case 1:
			tempRes[1].Amount += temp.Amount
		case 2:
			tempRes[2].Amount += temp.Amount
		case 3:
			tempRes[3].Amount += temp.Amount
		case 4:
			tempRes[3].Amount += temp.Amount
		case 41:
			tempRes[4].Amount += temp.Amount
		case 42:
			tempRes[5].Amount += temp.Amount
		case 43:
			tempRes[6].Amount += temp.Amount
		case 44:
			tempRes[7].Amount += temp.Amount
		case 45:
			tempRes[8].Amount += temp.Amount
		case 5:
			tempRes[3].Amount += temp.Amount
		case 6:
			tempRes[3].Amount += temp.Amount
		case 61:
			tempRes[4].Amount += temp.Amount
		case 62:
			tempRes[5].Amount += temp.Amount
		case 63:
			tempRes[6].Amount += temp.Amount
		case 64:
			tempRes[7].Amount += temp.Amount
		case 65:
			tempRes[8].Amount += temp.Amount
		case 7:
			tempRes[9].Amount += temp.Amount
		case 8:
			tempRes[10].Amount += temp.Amount
		case 9:
			tempRes[10].Amount += temp.Amount
		case 10:
			tempRes[11].Amount += temp.Amount
		case 11:
			tempRes[12].Amount += temp.Amount
		}
	}

	// 组合数据
	business := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}

	employeeMoney, err := queryEmployeeMoney(db, billIDs, employeeID)
	if err != nil {
		return nil, err
	}

	// 次卡充值费用
	meterCardRecharge, err := MeterCardRecharge(db, t, formatSQL, employeeID, hospitalLocalId)
	if err != nil {
		return nil, err
	}

	// 总额
	employeeMoney += meterCardRecharge

	// 计算百分比
	if employeeMoney > 0 {

		for _, v := range business {
			s := fmt.Sprintf("%.3f", (tempRes[v].Amount/employeeMoney)*100)
			f, _ := strconv.ParseFloat(s, 64)
			tempRes[v].Per = f
			response = append(response, tempRes[v])
		}

		if meterCardRecharge > 0 {
			//meterCardRechargeSum, err := MeterCardRecharge(db, t, formatSQL, 0)
			//if err != nil {
			//	return nil, err
			//}

			meterCardByEmployee := new(models.EmployeeAchievement)
			meterCardByEmployee.Amount = meterCardRecharge
			meterCardByEmployee.Item = "次卡"
			if employeeMoney > 0 {
				s := fmt.Sprintf("%.3f", (meterCardByEmployee.Amount/employeeMoney)*100)
				f, _ := strconv.ParseFloat(s, 64)
				meterCardByEmployee.Per = f
			}

			response = append(response, meterCardByEmployee)
		}
	}

	return response, nil
}

// 查询某个员工某个时间段 所有的营业额
func queryEmployeeMoney(db *sql.DB, billIDs string, employeeID int) (float64, error) {

	var c float64
	err := db.QueryRow(fmt.Sprintf(`select 
convert(ifnull(sum(quantity*payprice), 0) / 1000000, decimal(11,3))
from his_consumption
where delflag = 0 
and his_retreatbill_id = 0 
and commodity_ismeal = 0
and meter_num = 0
and his_bill_id in (%s) 
and sale_employee_id = ?`, billIDs), employeeID).Scan(&c)

	return c, err
}

func EmployeeBusinessBillRes(db *sql.DB, t, formatSQL, timeFormat string, employeeID int, loginID string) (interface{}, error) {

	loginIDInt, _ := strconv.Atoi(loginID)

	hospitalLocalId, err := QueryHospitalLocalIDByEmployeeLocalID(db, loginIDInt)
	if err != nil {
		return 0, err
	}

	//已接诊、疫苗驱虫、美容洗澡、住院寄养
	response := new(models.EmployeeBusinessBill)

	appointmentSQL := fmt.Sprintf(`select count(*) as c from his_appointment 
where delflag = 0 
and DATE_FORMAT(appointment_time,'%v') = '%v'   and  sys_hospital_id in (0,%v)  `, formatSQL, t, hospitalLocalId)

	// 接诊
	clinicSQL := fmt.Sprintf(`select count(*) as c from his_clinic 
where delflag = 0 
and DATE_FORMAT(eventtime,'%v') = '%v'   and  sys_hospital_id in (0,%v)  `, formatSQL, t, hospitalLocalId)

	// 疫苗
	protectionSQL := fmt.Sprintf(`select count(*) as c from his_protection_detail 
where delflag = 0 
and DATE_FORMAT(eventtime,'%v') = '%v'     and  sys_hospital_id in (0,%v)  `, formatSQL, t, hospitalLocalId)

	// insect
	insectSQL := fmt.Sprintf(`select count(*) as c from his_insect_detail 
where delflag = 0 
and DATE_FORMAT(eventtime, '%v') = '%v'   and  sys_hospital_id in (0,%v)   `, formatSQL, t, hospitalLocalId)

	// 美容
	beautySQL := fmt.Sprintf(`select count(*) from his_beauty
where delflag = 0 
and DATE_FORMAT(eventtime,'%v') = '%v'    and  sys_hospital_id in (0,%v)  `, formatSQL, t, hospitalLocalId)

	if employeeID != 0 {

		appointmentSQL += fmt.Sprintf(` and con_employee_id = %v `, employeeID)
		clinicSQL += fmt.Sprintf(` and cure_employee_id = %v `, employeeID)
		protectionSQL += fmt.Sprintf(` and cure_employee_id = %v `, employeeID)
		insectSQL += fmt.Sprintf(` and cure_employee_id = %v `, employeeID)
		beautySQL += fmt.Sprintf(` and sale_employee_id = %v  `, employeeID)
	}
	var appointmentNumber, clinicNumber, protectionNumber, insectNumber, beautyNumber int

	//global.GVA_LOG.Info(fmt.Sprintf("appointmentSQL :%v  ", appointmentSQL))
	//global.GVA_LOG.Info(fmt.Sprintf("clinicSQL :%v  ", clinicSQL))
	//global.GVA_LOG.Info(fmt.Sprintf("protectionSQL :%v  ", protectionSQL))
	//global.GVA_LOG.Info(fmt.Sprintf("insectSQL :%v  ", insectSQL))
	//global.GVA_LOG.Info(fmt.Sprintf("beautySQL :%v  ", beautySQL))

	err = db.QueryRow(appointmentSQL).Scan(&appointmentNumber)
	if err != nil {
		return nil, err
	}
	err = db.QueryRow(clinicSQL).Scan(&clinicNumber)
	if err != nil {
		return nil, err
	}
	err = db.QueryRow(protectionSQL).Scan(&protectionNumber)
	if err != nil {
		return nil, err
	}
	err = db.QueryRow(insectSQL).Scan(&insectNumber)
	if err != nil {
		return nil, err
	}
	err = db.QueryRow(beautySQL).Scan(&beautyNumber)
	if err != nil {
		return nil, err
	}

	response.Appointment = appointmentNumber
	response.AlreadyAccepted = clinicNumber
	response.VaccineInsect = protectionNumber + insectNumber
	response.Beauty = beautyNumber

	hospitalFoster, err := QueryHospitalAndFosterBill(db, formatSQL, t, timeFormat, employeeID, hospitalLocalId)
	if err != nil {
		return nil, err
	}
	response.HospitalFoster = hospitalFoster

	return response, nil
}

// 首页 今日营业额、今日毛利、今日支出
func TodayDataRes(db *sql.DB, employeeID int, chainCode string) (interface{}, error) {

	hospitalLocalId, err := QueryHospitalLocalIDByEmployeeLocalID(db, employeeID)
	if err != nil {
		return nil, err
	}

	timeNow := time.Now().Format(`2006-01-02`)
	formatSQL := "%Y-%m-%d"

	response := new(models.TodayData)

	//1 - 首页营业额:
	//按已结账单 + 次卡充值+赠送金额结算 (不计算次卡消费)

	billOfSettlement, err := BillOfSettlement(db, timeNow, formatSQL, hospitalLocalId)
	if err != nil {
		return nil, err
	}

	meterCardRecharge, err := MeterCardRecharge(db, timeNow, formatSQL, 0, hospitalLocalId)
	if err != nil {
		return nil, err
	}

	response.Turnover = billOfSettlement + meterCardRecharge

	//3、毛利
	//毛利=营业额-成本
	billByCost, err := BillByCost(db, timeNow, formatSQL, hospitalLocalId, chainCode)
	if err != nil {
		return nil, err
	}

	response.GrossProfit = response.Turnover - billByCost

	//2 - 首页支出:
	//1. 退押金
	retreatDepositMoney, err := RetreatDepositMoney(db, timeNow, formatSQL, hospitalLocalId)
	if err != nil {
		return nil, err
	}

	//2. 退会员卡
	retreatConsumerCard, err := RetreatConsumerCard(db, timeNow, formatSQL, hospitalLocalId)
	if err != nil {
		return nil, err
	}

	//3. 退次卡
	retreatMeterCard, err := RetreatMeterCard(db, timeNow, formatSQL, hospitalLocalId)
	if err != nil {
		return nil, err
	}

	//4. 支出管理中的
	outChargeBill, err := OutChargeBill(db, timeNow, formatSQL, hospitalLocalId)
	if err != nil {
		return nil, err
	}

	//5. 预付款
	preOutFundBill, err := PreOutFundBill(db, timeNow, formatSQL, hospitalLocalId)
	if err != nil {
		return nil, err
	}

	//6. 入库结算
	stockInBill, err := StockInBill(db, timeNow, formatSQL, hospitalLocalId)
	if err != nil {
		return nil, err
	}

	response.Expenditure = retreatDepositMoney + retreatConsumerCard + retreatMeterCard + outChargeBill + preOutFundBill + stockInBill

	// 支出减掉 退预付款的金额
	//RetreatPreOutFundBill
	retreatPreOutFundBill, err := RetreatPreOutFundBill(db, timeNow, formatSQL, hospitalLocalId)
	if err != nil {
		return nil, err
	}

	response.Expenditure -= retreatPreOutFundBill

	return response, nil
}

func Appointment(db *sql.DB, formatSQL, t string, employeeID, hospitalLocalId int) (interface{}, error) {

	sqlStr := fmt.Sprintf(` select a.appointment_time, a.appointment_name, 
a.con_employee_name, a.his_pet_name, species, kind, 
his_consumer_name, c.telephone
from his_appointment as a
left join his_pet as p on a.his_pet_id = p.id
left join his_consumer as c on a.his_consumer_id = c.id
where a.delflag = 0 and DATE_FORMAT(a.appointment_time,?) = ?
and  a.sys_hospital_id in (0,%v)   and a.first_vaccine = 0
`, hospitalLocalId)
	if employeeID != 0 {
		sqlStr += fmt.Sprintf(` and a.con_employee_id = %v`, employeeID)
	}

	sqlStr += ` order by a.appointment_time asc `

	rows, err := db.Query(sqlStr, formatSQL, t)
	if err != nil {
		return nil, err
	}

	response := make([]*models.Appointment, 0)
	for rows.Next() {
		var temp models.Appointment
		err = rows.Scan(&temp.AppointmentTime, &temp.AppointmentName, &temp.ConEmployeeName,
			&temp.HisPetName, &temp.Species, &temp.Kind, &temp.HisConsumerName, &temp.Telephone)
		if err != nil {
			return nil, err
		}
		response = append(response, &temp)
	}

	return response, nil
}

func Clinic(db *sql.DB, formatSQL, t string, employeeID, hospitalLocalId int) (interface{}, error) {

	sqlStr := fmt.Sprintf(`select c.eventtime, c.cure_employee_name, p._name, p.kind, c.abstract
from his_clinic as c
left join his_pet as p on p.id = c.his_pet_id
where c.delflag = 0 and DATE_FORMAT(c.eventtime,?) = ?   and  c.sys_hospital_id in (0,%v) `, hospitalLocalId)

	if employeeID > 0 {
		var w string
		w = fmt.Sprintf(" and c.cure_employee_id = %v", employeeID)
		sqlStr += w
	}

	rows, err := db.Query(sqlStr, formatSQL, t)
	if err != nil {
		return nil, err
	}

	response := make([]*models.Clinic, 0)

	for rows.Next() {
		var temp models.Clinic
		var kind string
		err = rows.Scan(&temp.Time, &temp.EmployeeName, &temp.PetName, &kind, &temp.Diagnosis)
		if err != nil {
			return nil, err
		}
		temp.PetName = fmt.Sprintf("%s(%s)", temp.PetName, kind)
		response = append(response, &temp)
	}

	return response, nil
}

func ProtectionAndInsect(db *sql.DB, formatSQL, t string, employeeID, hospitalLocalId int) (interface{}, error) {

	sqlStr1 := fmt.Sprintf(`select d.eventtime, d.cure_employee_name, 
pet._name, pet.kind, d._name 
from his_protection_detail as d
left join his_protection as p on d.his_protection_id = p.id
left join his_pet as pet on pet.id = p.his_pet_id
where d.delflag = 0 and DATE_FORMAT(d.eventtime,?) = ?    and  d.sys_hospital_id in (0,%v)  `, hospitalLocalId)

	if employeeID > 0 {
		var w string
		w = fmt.Sprintf(" and d.cure_employee_id = %v", employeeID)
		sqlStr1 += w
	}

	sqlStr2 := fmt.Sprintf(`
UNION ALL
select d.eventtime, d.cure_employee_name, 
pet._name, pet.kind, d._name 
from his_insect_detail as d
left join his_insect as p on d.his_insect_id = p.id
left join his_pet as pet on pet.id = p.his_pet_id
where d.delflag = 0 and DATE_FORMAT(d.eventtime,?) = ? and  d.sys_hospital_id in (0,%v)  `, hospitalLocalId)

	if employeeID > 0 {
		var w string
		w = fmt.Sprintf(" and d.cure_employee_id = %v", employeeID)
		sqlStr2 += w
	}

	rows, err := db.Query(sqlStr1+sqlStr2, formatSQL, t, formatSQL, t)
	if err != nil {
		return nil, err
	}

	response := make([]*models.ProtectionInsect, 0)
	for rows.Next() {
		var temp models.ProtectionInsect
		var kind string
		err = rows.Scan(&temp.Time, &temp.EmployeeName, &temp.PetName, &kind, &temp.ProtectionOrInsect)
		if err != nil {
			return nil, err
		}
		temp.PetName = fmt.Sprintf("%s(%s)", temp.PetName, kind)
		response = append(response, &temp)
	}

	return response, nil
}

func Beauty(db *sql.DB, formatSQL, t string, employeeID, hospitalLocalId int) (interface{}, error) {

	sqlStr := fmt.Sprintf(`select b.eventtime, b.service_employee_name, p._name, p.kind
from his_beauty as b
left join his_pet as p on p.id = b.his_pet_id
where b.delflag = 0 and DATE_FORMAT(b.eventtime,?) = ?  and   and  c.sys_hospital_id in (0,%v)  `, hospitalLocalId)

	if employeeID > 0 {
		var w string
		w = fmt.Sprintf(" and b.sale_employee_id = %v", employeeID)
		sqlStr += w
	}

	rows, err := db.Query(sqlStr, formatSQL, t)
	if err != nil {
		return nil, err
	}

	response := make([]models.Beauty, 0)
	for rows.Next() {
		var temp models.Beauty
		var kind string
		err = rows.Scan(&temp.Time, &temp.EmployeeName, &temp.PetName, &kind)
		if err != nil {
			return nil, err
		}
		temp.PetName = fmt.Sprintf("%s(%s)", temp.PetName, kind)
		response = append(response, temp)
	}

	return response, nil
}

func HospitalAndFoster(db *sql.DB, formatSQL, t, timeFormat string, employeeID, hospitalLocalId int) (interface{}, error) {

	// 当天日期
	timeParam, err := time.Parse(timeFormat, t)
	if err != nil {
		return nil, err
	}

	sqlStr1 := fmt.Sprintf(`select DATE_FORMAT(h.intime,?), DATE_FORMAT(h.outtime,?), h.medical_employee_name, 
p._name, p.kind, convert(ifnull(c.deposit_money, 0) / 1000, decimal(11,2)), h.state, h.autoout, "住院"
from his_hospital as h
left join his_pet as p on p.id = h.his_pet_id
left join his_consumer as c on c.id = h.his_consumer_id
where h.delflag = 0 and  h.sys_hospital_id in (0,%v)  `, hospitalLocalId)

	if employeeID > 0 {
		var w string
		w = fmt.Sprintf(" and h.medical_employee_id = %v ", employeeID)
		sqlStr1 += w
	}

	sqlStr2 := fmt.Sprintf(` 
UNION ALL
select DATE_FORMAT(h.intime,?), DATE_FORMAT(h.outtime,?), h.main_employee_name, 
p._name, p.kind, convert(ifnull(c.deposit_money, 0) / 1000, decimal(11,2)), h.state, h.autoout, "寄养"
from his_foster as h
left join his_pet as p on p.id = h.his_pet_id
left join his_consumer as c on c.id = h.his_consumer_id
where h.delflag = 0  and  h.sys_hospital_id in (0,%v)   `, hospitalLocalId)

	if employeeID > 0 {
		var w string
		w = fmt.Sprintf(" and h.main_employee_id = %v ", employeeID)
		sqlStr2 += w
	}

	rows, err := db.Query(sqlStr1+sqlStr2, formatSQL, formatSQL, formatSQL, formatSQL)
	if err != nil {
		return nil, err
	}

	response := make([]*models.HospitalFoster, 0)

	for rows.Next() {
		temp := new(models.HospitalFoster)
		var inTime, outTime, kind string
		var state, autoout int

		err = rows.Scan(&inTime, &outTime, &temp.EmployeeName, &temp.PetName, &kind, &temp.DepositMoney, &state, &autoout, &temp.HospitalOrFoster)
		if err != nil {
			return nil, err
		}

		if temp.HospitalOrFoster == "住院" {

			if state == 0 { // 住院中

				// 如果是手动出院的话 截止时间就是今天
				// 如果是自动出院、截止日期就是 outTime
				if autoout == 0 {
					outTime = t
				}

				// 住院截止日期
				endTime, err := time.Parse(timeFormat, outTime)
				if err != nil {
					return nil, err
				}

				// 住院开始日期
				startTime, err := time.Parse(timeFormat, inTime)
				if err != nil {
					return nil, err
				}

				// 筛选日期、必须要大于等于 住院开始时间
				// 筛选日期、必须要小于等于 住院结束时间
				if timeParam.Sub(startTime).Hours() < 0 || timeParam.Sub(endTime).Hours() > 0 {
					continue
				}

				checkInDay := int(timeParam.Sub(startTime).Hours() / 24)

				temp.HospitalDay = fmt.Sprintf("%v", checkInDay+1)

				temp.PetName = fmt.Sprintf("%s(%s)", temp.PetName, kind)
				response = append(response, temp)

			} else { // 已出院

				// 住院截止日期
				endTime, err := time.Parse(timeFormat, outTime)
				if err != nil {
					return nil, err
				}

				// 住院开始日期
				startTime, err := time.Parse(timeFormat, inTime)
				if err != nil {
					return nil, err
				}

				// 筛选日期、必须要大于等于 住院开始时间
				// 筛选日期、必须要小于等于 住院结束时间
				if timeParam.Sub(startTime).Hours() < 0 || timeParam.Sub(endTime).Hours() > 0 {
					continue
				}

				checkInDay := int(endTime.Sub(startTime).Hours() / 24)

				temp.HospitalDay = fmt.Sprintf("%v", checkInDay+1)

				temp.PetName = fmt.Sprintf("%s(%s)", temp.PetName, kind)
				response = append(response, temp)
			}
		} else {
			// 寄养截止日期
			endTime, err := time.Parse(timeFormat, outTime)
			if err != nil {
				return nil, err
			}

			// 住院开始日期
			startTime, err := time.Parse(timeFormat, inTime)
			if err != nil {
				return nil, err
			}

			// 筛选日期、必须要大于等于 住院开始时间
			// 筛选日期、必须要小于等于 住院结束时间
			if timeParam.Sub(startTime).Hours() < 0 || timeParam.Sub(endTime).Hours() > 0 {
				continue
			}

			if timeParam.Sub(endTime).Hours() <= 0 {

				checkInDay := int(timeParam.Sub(startTime).Hours() / 24)
				temp.HospitalDay = fmt.Sprintf("%v", checkInDay+1)
			} else {
				checkInDay := int(endTime.Sub(startTime).Hours() / 24)
				temp.HospitalDay = fmt.Sprintf("%v", checkInDay+1)
			}

			temp.PetName = fmt.Sprintf("%s(%s)", temp.PetName, kind)
			response = append(response, temp)
		}

	}

	return response, nil
}

func QueryHospitalAndFosterBill(db *sql.DB, formatSQL, t, timeFormat string, employeeID, hospitalLocalId int) (int, error) {

	var bill int

	// 当天日期
	timeParam, err := time.Parse(timeFormat, t)
	if err != nil {
		return 0, err
	}

	sqlStr1 := fmt.Sprintf(`select DATE_FORMAT(h.intime,?), DATE_FORMAT(h.outtime,?), h.medical_employee_name, 
ifnull(p._name, ''), ifnull(p.kind, ''), convert(ifnull(c.deposit_money, 0) / 1000, decimal(11,2)), h.state, h.autoout, "住院"
from his_hospital as h
left join his_pet as p on p.id = h.his_pet_id
left join his_consumer as c on c.id = h.his_consumer_id
where h.delflag = 0  and  h.sys_hospital_id in (0,%v)  `, hospitalLocalId)

	if employeeID > 0 {
		var w string
		w = fmt.Sprintf(" and h.medical_employee_id = %v   ", employeeID)
		sqlStr1 += w
	}

	sqlStr2 := fmt.Sprintf(` 
UNION ALL
select DATE_FORMAT(h.intime,?), DATE_FORMAT(h.outtime,?), h.main_employee_name, 
ifnull(p._name, ''), ifnull(p.kind, ''), convert(ifnull(c.deposit_money, 0) / 1000, decimal(11,2)), h.state, h.autoout, "寄养"
from his_foster as h
left join his_pet as p on p.id = h.his_pet_id
left join his_consumer as c on c.id = h.his_consumer_id
where h.delflag = 0    and  h.sys_hospital_id in (0,%v)   `, hospitalLocalId)

	if employeeID > 0 {
		var w string
		w = fmt.Sprintf(" and h.main_employee_id = %v ", employeeID)
		sqlStr2 += w
	}

	rows, err := db.Query(sqlStr1+sqlStr2, formatSQL, formatSQL, formatSQL, formatSQL)
	if err != nil {
		return 0, err
	}

	for rows.Next() {
		temp := new(models.HospitalFoster)
		var inTime, outTime, kind string
		var state, autoout int

		err = rows.Scan(&inTime, &outTime, &temp.EmployeeName, &temp.PetName, &kind, &temp.DepositMoney, &state, &autoout, &temp.HospitalOrFoster)
		if err != nil {
			return 0, err
		}

		if temp.HospitalOrFoster == "住院" {

			if state == 0 { // 住院中

				// 如果是手动出院的话 截止时间就是今天
				// 如果是自动出院、截止日期就是 outTime
				if autoout == 0 {
					outTime = t
				}

				// 住院截止日期
				endTime, err := time.Parse(timeFormat, outTime)
				if err != nil {
					return 0, err
				}

				// 住院开始日期
				startTime, err := time.Parse(timeFormat, inTime)
				if err != nil {
					return 0, err
				}

				// 筛选日期、必须要大于等于 住院开始时间
				// 筛选日期、必须要小于等于 住院结束时间
				if timeParam.Sub(startTime).Hours() < 0 || timeParam.Sub(endTime).Hours() > 0 {
					continue
				}

				bill++
			} else { // 已出院

				// 住院截止日期
				endTime, err := time.Parse(timeFormat, outTime)
				if err != nil {
					return 0, err
				}

				// 住院开始日期
				startTime, err := time.Parse(timeFormat, inTime)
				if err != nil {
					return 0, err
				}

				// 筛选日期、必须要大于等于 住院开始时间
				// 筛选日期、必须要小于等于 住院结束时间
				if timeParam.Sub(startTime).Hours() < 0 || timeParam.Sub(endTime).Hours() > 0 {
					continue
				}

				bill++
			}
		} else {
			// 寄养截止日期
			endTime, err := time.Parse(timeFormat, outTime)
			if err != nil {
				return 0, err
			}

			// 住院开始日期
			startTime, err := time.Parse(timeFormat, inTime)
			if err != nil {
				return 0, err
			}

			// 筛选日期、必须要大于等于 住院开始时间
			// 筛选日期、必须要小于等于 住院结束时间
			if timeParam.Sub(startTime).Hours() < 0 || timeParam.Sub(endTime).Hours() > 0 {
				continue
			}

			bill++
		}

	}

	return bill, nil
}