consumer.go 27.2 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
package repository

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

	"github.com/uniplaces/carbon"
)

func ConsumerAnalysisRes(db *sql.DB, t string) (interface{}, error) {

	// 计算时间 及格式化的模板
	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")
	}

	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")
	}

	var response models.ConsumerAnalysis

	// 1. 查询数据逻辑

	// 查询 筛选时间发哪位内的 所有已结账单
	rows, err := db.Query(`select his_consumer_id, DATE_FORMAT(paytime, ?) as time from his_bill
where delflag = 0 
and billtype in (1,4,6,7)
and his_consumer_id != 0
and DATE_FORMAT(paytime, ?) >= ?
and DATE_FORMAT(paytime, ?) <= ?`, formatSQL, formatSQL, endTime, formatSQL, t)
	if err != nil {
		return nil, err
	}

	type tempStruct struct {
		ConsumerID int
		PayTime    string
	}

	tempS := make([]tempStruct, 0)

	for rows.Next() {
		var temp tempStruct
		err = rows.Scan(&temp.ConsumerID, &temp.PayTime)
		if err != nil {
			return nil, err
		}
		tempS = append(tempS, temp)
	}

	// 2. 组装数据
	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)
		}

		var shopCustomer models.ShopCustomer
		shopCustomer.Type = "到店顾客"
		shopCustomer.Date = str
		var shopCustomerBill models.ShopCustomer
		shopCustomerBill.Type = "支付笔数"
		shopCustomerBill.Date = str

		shopCustomerMap := make(map[int]int, 0)

		for _, v := range tempS {
			if v.PayTime == str {
				shopCustomerBill.Number++
				shopCustomerMap[v.ConsumerID] = 0
			}
		}
		shopCustomer.Number = len(shopCustomerMap)

		if t == str {
			response.PayNumber = shopCustomerBill.Number
			response.Arrival = shopCustomer.Number
		}
		response.ShopCustomers = append(response.ShopCustomers, shopCustomer, shopCustomerBill)
	}

	return response, nil
}

func SourceDistributeRes(db *sql.DB) (interface{}, error) {

	var response models.Annular

	// 顾客来源
	rows, err := db.Query(`select understand, count(understand) as counts from his_consumer
where delflag = 0 and understand != ''
GROUP BY understand
order by counts desc limit 6`)
	if err != nil {
		return nil, err
	}

	sources := make([]models.ConsumerSource, 0)
	for rows.Next() {
		var temp models.ConsumerSource
		temp.A = "1"
		err = rows.Scan(&temp.Type, &temp.Cost)
		if err != nil {
			return nil, err
		}
		response.ConsumerSourceSum += temp.Cost
		sources = append(sources, temp)
	}

	// 顾客分布
	rows, err = db.Query(`select address, count(address) as counts from his_consumer
where delflag = 0 and address != ''
GROUP BY address 
order by counts desc limit 6`)
	if err != nil {
		return nil, err
	}

	distributes := make([]models.ConsumerDistribute, 0)
	for rows.Next() {
		var temp models.ConsumerDistribute
		temp.A = "1"
		err = rows.Scan(&temp.Type, &temp.Cost)
		if err != nil {
			return nil, err
		}
		response.ConsumerDistributeSum += temp.Cost
		distributes = append(distributes, temp)
	}

	response.ConsumerSources = sources
	response.ConsumerDistributes = distributes

	return response, nil
}

func ConsumptionRankRes(db *sql.DB, t string) (interface{}, error) {

	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 ifnull(m._name, ''), ifnull(m.telephone, ''),
ifnull(convert(sum(c.quantity*c.payprice) / 1000000, decimal(11,3)), 0) as money
from his_consumption as c
left join his_bill as b on b.id = c.his_bill_id
left join his_consumer as m on m.id = c.his_consumer_id
where c.delflag = 0 and c.his_retreatbill_id = 0 
and c.commodity_ismeal = 0 
and c.meter_num = 0
and c.his_bill_id != 0
and b.billtype in (1,4,6,7)
and DATE_FORMAT(b.paytime, ?) = ?
GROUP BY c.his_consumer_id 
order by money desc`, formatSQL, t)
	if err != nil {
		return nil, err
	}

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

	for rows.Next() {
		var temp models.ConsumptionRank
		err = rows.Scan(&temp.Name, &temp.Phone, &temp.Money)
		if err != nil {
			return nil, err
		}
		if temp.Name == "" {
			temp.Name = "散客"
		}
		response = append(response, temp)
	}

	return response, nil
}

func CardPreviewRes(db *sql.DB, t string, hospitalID int) (interface{}, error) {

	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")
	}

	// 实充金额、赠送金额、支出金额

	var response models.CardPreview

	err := db.QueryRow(`select b.*, t.* from (
select 
ifnull(convert(sum(money) / 1000, decimal(11,3)), 0), 
ifnull(convert(sum(presentmoney) / 1000, decimal(11,3)), 0)
from his_card_detail where delflag = 0 and eventtype in (1,3,4) and DATE_FORMAT(eventtime, ?) = ?
) as b
left join
(
select 
 ifnull(convert(sum(money) / 1000, decimal(11,3)), 0) + ifnull(convert(sum(presentmoney) / 1000, decimal(11,3)), 0) 
from his_card_detail where delflag = 0 and eventtype in (5,6,11,12,13) and DATE_FORMAT(eventtime, ?) = ?
) as t
on 1=1`, formatSQL, t, formatSQL, t).Scan(&response.MoneySum, &response.PresentMoneySum, &response.ExpendMoney)
	if err != nil {
		return nil, err
	}

	var expendTemp float64
	err = db.QueryRow(`select 
 ifnull(convert(sum(money) / 1000, decimal(11,3)), 0) + ifnull(convert(sum(presentmoney) / 1000, decimal(11,3)), 0) 
from his_card_detail where delflag = 0 and eventtype in (7,8,9,10) and DATE_FORMAT(eventtime, ?) = ?`, formatSQL, t).Scan(&expendTemp)
	if err != nil {
		return nil, err
	}

	//  支出总和 - 取消支出
	response.ExpendMoney -= expendTemp

	// 新增会员
	// 会员数量

	err = db.QueryRow(`
select b.*, t.* from (
select count(*) from his_consumer where delflag = 0 and sys_hospital_id in (0, ?)
) as b
left join
(
select count(*) from his_consumer where delflag = 0 and DATE_FORMAT(addtime, ?) = ?
) as t
on 1=1`, hospitalID, formatSQL, t).Scan(&response.ConsumerSum, &response.AddConsumer)
	if err != nil {
		return nil, err
	}

	return response, nil
}

func CardPreviewChartRes(db *sql.DB, t string) (interface{}, error) {

	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")
	}

	response, err := cardRes(db, formatSQL, t)
	if err != nil {
		return nil, err
	}

	//meterCardResponse, err := meterCardRes(db, formatSQL, t)
	//if err != nil {
	//	return nil, err
	//}
	//
	//response = append(response, meterCardResponse...)

	return response, nil
}

func cardRes(db *sql.DB, format, t string) ([]*models.CardPreviewChart, error) {

	rows, err := db.Query(`select id, _name from con_cardtype`)
	if err != nil {
		return nil, err
	}

	response := make([]*models.CardPreviewChart, 0)
	resTemp := make([]*models.CardPreviewChartTemp, 0)

	for rows.Next() {
		temp := new(models.CardPreviewChartTemp)
		err = rows.Scan(&temp.ID, &temp.Name)
		if err != nil {
			return nil, err
		}

		resTemp = append(resTemp, temp)
	}

	chartCardTemp := make(map[int]*models.CardChartTemp, 0)

	rows, err = db.Query(`select card.con_cardtype_id, 
ifnull(convert(sum(d.money) / 1000, decimal(11,3)), 0),
ifnull(convert(sum(d.presentmoney) / 1000, decimal(11,3)), 0)
from his_card_detail as d
left join his_card as card on card.id = d.his_card_id 
left join con_cardtype as c on c.id = card.con_cardtype_id
where d.delflag = 0 and d.eventtype in (1,3,4) and DATE_FORMAT(d.eventtime, ?) = ?
GROUP BY card.con_cardtype_id`, format, t)
	if err != nil {
		return nil, err
	}

	for rows.Next() {
		temp := new(models.CardChartTemp)
		err = rows.Scan(&temp.CardID, &temp.Money, &temp.PresentMoney)
		if err != nil {
			return nil, err
		}
		chartCardTemp[temp.CardID] = temp
	}

	rows, err = db.Query(`select d.eventtype, card.con_cardtype_id, 
ifnull(convert(d.money / 1000, decimal(11,3)), 0),
ifnull(convert(d.presentmoney / 1000, decimal(11,3)), 0)
from his_card_detail as d
left join his_card as card on card.id = d.his_card_id 
left join con_cardtype as c on c.id = card.con_cardtype_id
where d.delflag = 0 and d.eventtype in (5,6,7,8,9,10,11,12,13) and DATE_FORMAT(d.eventtime, ?) = ? `, format, t)
	if err != nil {
		return nil, err
	}

	for rows.Next() {
		temp := new(models.CardChartTemp)
		var eventType int
		err = rows.Scan(&eventType, &temp.CardID, &temp.ExpendMoney, &temp.PresentMoney)
		if err != nil {
			return nil, err
		}

		if eventType == 5 || eventType == 6 || eventType == 11 || eventType == 12 || eventType == 13 {
			if _, ok := chartCardTemp[temp.CardID]; ok {
				chartCardTemp[temp.CardID].ExpendMoney += temp.ExpendMoney
				chartCardTemp[temp.CardID].ExpendMoney += temp.PresentMoney
			} else {
				chartCardTemp[temp.CardID] = temp
			}
		} else {
			if _, ok := chartCardTemp[temp.CardID]; ok {
				chartCardTemp[temp.CardID].ExpendMoney -= temp.ExpendMoney
				chartCardTemp[temp.CardID].ExpendMoney -= temp.PresentMoney
			} else {
				chartCardTemp[temp.CardID] = temp
			}
		}

	}

	for _, v := range resTemp {

		temp1 := new(models.CardPreviewChart)
		temp2 := new(models.CardPreviewChart)
		temp3 := new(models.CardPreviewChart)

		temp1.Name = v.Name
		temp1.Type = "支出金额"
		temp2.Name = v.Name
		temp2.Type = "赠送金额"
		temp3.Name = v.Name
		temp3.Type = "实充金额"

		if res, ok := chartCardTemp[v.ID]; ok {

			temp1.Value = res.ExpendMoney
			temp2.Value = res.PresentMoney
			temp3.Value = res.Money
		}

		response = append(response, temp1, temp2, temp3)
	}

	return response, nil
}

// 次卡这版本先不做
func meterCardRes(db *sql.DB, format, t string) ([]*models.CardPreviewChart, error) {

	rows, err := db.Query(`select id, _name from con_metercardtype`)
	if err != nil {
		return nil, err
	}

	response := make([]*models.CardPreviewChart, 0)
	resTemp := make([]*models.CardPreviewChartTemp, 0)

	for rows.Next() {
		temp := new(models.CardPreviewChartTemp)
		err = rows.Scan(&temp.ID, &temp.Name)
		if err != nil {
			return nil, err
		}

		resTemp = append(resTemp, temp)
	}

	chartCardTemp := make(map[int]*models.CardChartTemp, 0)

	rows, err = db.Query(`select card.con_metercardtype_id, 
ifnull(convert(sum(d.money) / 1000, decimal(11,3)), 0)
from his_metercard_detail as d
left join his_metercard as card on card.id = d.his_metercard_id 
left join con_metercardtype as c on c.id = card.con_metercardtype_id
where d.delflag = 0 and d.eventtype in (1,2) and DATE_FORMAT(d.eventtime, ?) = ?
GROUP BY card.con_metercardtype_id`, format, t)
	if err != nil {
		return nil, err
	}

	for rows.Next() {
		temp := new(models.CardChartTemp)
		err = rows.Scan(&temp.CardID, &temp.Money)
		if err != nil {
			return nil, err
		}
		chartCardTemp[temp.CardID] = temp
	}

	rows, err = db.Query(`select card.con_metercardtype_id, 
ifnull(convert(sum(d.money) / 1000, decimal(11,3)), 0)
from his_metercard_detail as d
left join his_metercard as card on card.id = d.his_metercard_id 
left join con_metercardtype as c on c.id = card.con_metercardtype_id
where d.delflag = 0 and d.eventtype in (3,4) and DATE_FORMAT(d.eventtime, ?) = ?
GROUP BY card.con_metercardtype_id`, format, t)
	if err != nil {
		return nil, err
	}

	for rows.Next() {
		temp := new(models.CardChartTemp)
		err = rows.Scan(&temp.CardID, &temp.ExpendMoney)
		if err != nil {
			return nil, err
		}
		if _, ok := chartCardTemp[temp.CardID]; ok {
			chartCardTemp[temp.CardID].ExpendMoney += temp.ExpendMoney
		} else {
			chartCardTemp[temp.CardID] = temp
		}
	}

	for _, v := range resTemp {

		temp1 := new(models.CardPreviewChart)
		temp2 := new(models.CardPreviewChart)
		temp3 := new(models.CardPreviewChart)

		temp1.Name = v.Name
		temp1.Type = "支出金额"
		temp2.Name = v.Name
		temp2.Type = "赠送金额"
		temp3.Name = v.Name
		temp3.Type = "实充金额"

		if res, ok := chartCardTemp[v.ID]; ok {

			temp1.Value = res.ExpendMoney
			temp2.Value = res.PresentMoney
			temp3.Value = res.Money
		}

		response = append(response, temp1, temp2, temp3)
	}

	return response, nil
}

func CardTypeRes(db *sql.DB) (interface{}, error) {

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

	rows, err := db.Query(`select id, _name from con_cardtype`)
	if err != nil {
		return nil, err
	}

	for rows.Next() {
		var temp models.CardType
		temp.Type = 1
		err = rows.Scan(&temp.ID, &temp.CardName)
		if err != nil {
			return nil, err
		}
		response = append(response, &temp)
	}

	// 次卡这个版本先不做
	//rows, err = db.Query(`select id, _name from con_metercardtype`)
	//if err != nil {
	//	return nil, err
	//}
	//for rows.Next() {
	//	var temp models.CardType
	//	temp.Type = 2
	//	err = rows.Scan(&temp.ID, &temp.CardName)
	//	if err != nil {
	//		return nil, err
	//	}
	//	response = append(response, &temp)
	//}

	return response, nil
}

// 会员卡
func CardDetailByIDRes(db *sql.DB, t string, cardID int) (*models.CardDetailInfo, error) {

	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")
	}
	sqlStr := `select d.eventtime, consumer._name, d.eventtype, 
ifnull(convert(d.money / 1000, decimal(11,3)), 0), 
ifnull(convert(d.presentmoney / 1000, decimal(11,3)), 0)
from his_card_detail as d
join his_card as c on c.id = d.his_card_id
join his_consumer as consumer on consumer.id = c.his_consumer_id
where d.delflag = 0 
and DATE_FORMAT(eventtime,?) = ? `

	if cardID != 0 {
		sqlStr += fmt.Sprintf(` and c.con_cardtype_id = %v`, cardID)
	}

	sqlStr += ` order by d.id desc`

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

	var response models.CardDetailInfo
	response.CardDetails = make([]*models.CardDetail, 0)

	for rows.Next() {
		var temp models.CardDetail
		var Type int
		err = rows.Scan(&temp.Time, &temp.ConsumerName, &Type, &temp.Money, &temp.PresentMoney)
		if err != nil {
			return nil, err
		}

		if Type == 1 || Type == 3 || Type == 4 {
			response.MoneySum += temp.Money
			response.PresentMoneySum += temp.PresentMoney
		} else if Type == 5 || Type == 6 || Type == 11 || Type == 12 || Type == 13 {
			response.ExpendMoneySum += temp.Money
			response.ExpendMoneySum += temp.PresentMoney
		} else if Type == 7 || Type == 8 || Type == 9 || Type == 10 {
			response.ExpendMoneySum -= temp.Money
			response.ExpendMoneySum -= temp.PresentMoney
		}

		temp.Type = common.CardType[Type]
		response.CardDetails = append(response.CardDetails, &temp)
	}

	return &response, nil
}

// 次卡
func MeterCardDetailByIDRes(db *sql.DB, t string, cardID, listType int) (*models.CardDetailInfo, error) {

	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")
	}

	sqlStr := `select ifnull(d.eventtime, ''), ifnull(consumer._name, ''), ifnull(d.eventtype, 0), 
ifnull(convert(sum(d.money) / 1000, decimal(11,3)), 0)
from his_metercard_detail as d
join his_metercard as c on d.his_metercard_id = c.id
join his_consumer as consumer on c.his_consumer_id = consumer.id
where d.delflag = 0 
and DATE_FORMAT(eventtime,?) = ? `

	if cardID != 0 {
		sqlStr += fmt.Sprintf(` and c.con_metercardtype_id = %v`, cardID)
	}

	sqlStr += ` order by d.id desc`

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

	var response models.CardDetailInfo
	response.CardDetails = make([]*models.CardDetail, 0)

	for rows.Next() {
		var temp models.CardDetail
		var Type int
		err = rows.Scan(&temp.Time, &temp.ConsumerName, &Type, &temp.Money)
		if err != nil {
			return nil, err
		}

		if Type == 2 {
			temp.Type = "充值"
			response.MoneySum += temp.Money
			if listType == 0 || listType == 1 {
				response.CardDetails = append(response.CardDetails, &temp)
			}
		} else if Type == 3 {
			temp.Type = "消费"
			response.ExpendMoneySum += temp.Money
			if listType == 0 || listType == 2 {
				response.CardDetails = append(response.CardDetails, &temp)
			}
		} else if Type == 4 {
			temp.Type = "退卡"
			response.ExpendMoneySum += temp.Money
			if listType == 0 || listType == 2 {
				response.CardDetails = append(response.CardDetails, &temp)
			}
		}
	}

	return &response, nil
}

func GetConsumerListByCondition(db *sql.DB, p *models.ConsumerListCondition, hospitalId int64, page, pageSize int64) (interface{}, error) {

	queryConsumerSQL := `SELECT
	c.id,
	c._name,
	c.namepy,
	c.sex,
	c.telephone,
	ifnull( c.birthday, '' ),
	c.address,
	c.understand,
	c.email,
	CONVERT (
		c.bonus / 1000,
	DECIMAL ( 11, 3 )),
	CONVERT (
		c.deposit_money / 1000,
	DECIMAL ( 11, 3 )),
	c.addtime,
	c.is_blacklist,
	ifnull( c.blacklist_content, '' ),
	c.sys_hospital_id,
	h.hospital_code,
	h._name 
FROM
	his_consumer c
	LEFT JOIN sys_hospital h ON c.sys_hospital_id = h.id 
	LEFT JOIN his_pet p ON p.his_consumer_id = c.id AND p.delflag = 0 
	LEFT JOIN his_card card ON card.his_consumer_id = c.id   AND card.delflag = 0 
WHERE
	c.delflag = 0  `

	if p.Keyword != "" {
		queryConsumerSQL = SqlHandle(p, queryConsumerSQL)
	}

	if p.IsChain == 0 {
		queryConsumerSQL += fmt.Sprintf(` and c.sys_hospital_id =  %v `, hospitalId)
	} else {
		queryConsumerSQL += fmt.Sprintf(` and c.sys_hospital_id !=  %v `, hospitalId)
	}

	queryConsumerSQL += " group by c.id  ORDER BY id  DESC  limit ?,?  "

	rows, err := db.Query(queryConsumerSQL, page, pageSize)
	if err != nil {
		return nil, err
	}

	consumers := make([]models.Consumer, 0)
	for rows.Next() {
		var c models.Consumer
		err = rows.Scan(&c.ID, &c.Name, &c.Namepy, &c.Sex, &c.Telephone,
			&c.Birthday, &c.Address, &c.Understand, &c.Email, &c.Bonus, &c.DepositMoney, &c.AddTime, &c.IsBlackList, &c.BlackList, &c.HospitalID, &c.HospitalCode, &c.HospitalName)
		if err != nil {
			return nil, err
		}

		if c.HospitalID == hospitalId {
			c.IsChain = 0
		} else {
			c.IsChain = 1
		}

		if len(c.Telephone) > 11 {
			c.Telephone = utils.DescrySignPhone(c.Telephone)
		}

		consumers = append(consumers, c)
	}

	return consumers, nil
}

func GetConsumerTotalByCondition(db *sql.DB, p *models.ConsumerListCondition, hospitalId int64) (int64, error) {

	var total int64

	queryConsumerSQL := `  
SELECT  COUNT(0) FROM (  SELECT
count(0)
FROM
	his_consumer c
	LEFT JOIN sys_hospital h ON c.sys_hospital_id = h.id 
	LEFT JOIN his_pet p ON p.his_consumer_id = c.id AND p.delflag = 0 
	LEFT JOIN his_card card ON card.his_consumer_id = c.id   AND card.delflag = 0 
WHERE
	c.delflag = 0  `

	if p.Keyword != "" {
		queryConsumerSQL = SqlHandle(p, queryConsumerSQL)
	}

	if p.IsChain == 0 {
		queryConsumerSQL += fmt.Sprintf(` and c.sys_hospital_id =  %v `, hospitalId)
	} else {
		queryConsumerSQL += fmt.Sprintf(` and c.sys_hospital_id !=  %v `, hospitalId)
	}

	queryConsumerSQL += " group by c.id  ) a"

	err := db.QueryRow(queryConsumerSQL).Scan(&total)
	switch {
	case err == sql.ErrNoRows:
		return total, nil
	case err != nil:
		return 0, err
	}

	return total, nil
}

func SqlHandle(p *models.ConsumerListCondition, queryConsumerSQL string) string {
	if p.Keyword != "" {
		p.Keyword = "%" + p.Keyword + "%"
		switch p.Type {
		case 1:
			return queryConsumerSQL + fmt.Sprintf(` AND ( c._name  LIKE '%s' OR c.telephone  LIKE '%s' OR  p._name LIKE '%s'  OR  p._code LIKE '%s' OR card.cardtype LIKE '%s' OR  card._code LIKE '%s'  OR  	p.species LIKE '%s' )   `, p.Keyword, p.Keyword, p.Keyword, p.Keyword, p.Keyword, p.Keyword, p.Keyword)
		case 2:
			return queryConsumerSQL + fmt.Sprintf(` AND ( c._name  LIKE '%s'  ) `, p.Keyword)
		case 3:
			return queryConsumerSQL + fmt.Sprintf(` AND (  c.telephone  LIKE '%s' )   `, p.Keyword)
		case 4:
			return queryConsumerSQL + fmt.Sprintf(` AND ( p._name LIKE '%s' )   `, p.Keyword)
		case 5:
			return queryConsumerSQL + fmt.Sprintf(` AND ( p._code LIKE '%s' )   `, p.Keyword)
		case 6:
			return queryConsumerSQL + fmt.Sprintf(` AND ( card.cardtype LIKE '%s' )   `, p.Keyword)
		case 7:
			return queryConsumerSQL + fmt.Sprintf(` AND ( card._code LIKE '%s' )   `, p.Keyword)
		case 8:
			return queryConsumerSQL + fmt.Sprintf(` AND ( p.species LIKE '%s' )   `, p.Keyword)
		}
	}
	return queryConsumerSQL
}

func GetConsumerDetailById(db *sql.DB, consumerId string, hospitalId int64) (interface{}, error) {

	queryConsumerSQL := `select c.id, c._name, c.namepy, c.sex, c.telephone, ifnull(c.birthday,""), c.address, c.understand, c.email, convert(c.bonus / 1000, decimal(11,3)), convert(c.deposit_money / 1000, decimal(11,3)), c.addtime,h.id,h.hospital_code,h._name  from his_consumer  c   left join  sys_hospital  h on c.sys_hospital_id  = h.id
where c.delflag = 0 and c.id = ?`

	var c models.Consumers

	err := db.QueryRow(queryConsumerSQL, consumerId).Scan(&c.ID, &c.Name, &c.Namepy, &c.Sex, &c.Telephone, &c.Birthday, &c.Address, &c.Understand, &c.Email, &c.Bonus, &c.DepositMoney, &c.AddTime, &c.HospitalID, &c.HospitalCode, &c.HospitalName)
	switch {
	case err == sql.ErrNoRows:
	case err != nil:
		return nil, err
	}

	if len(c.Telephone) > 11 {
		c.Telephone = utils.DescrySignPhone(c.Telephone)
	}

	pet, err := GetPetInfoByConsumerId(db, consumerId, hospitalId)
	if err != nil {
		return nil, err
	}

	card, err := GetCardInfoByPetId(db, consumerId, hospitalId)
	if err != nil {
		return nil, err
	}

	c.Pets = pet
	c.CardAndMeterCard = card

	return c, err

}

func GetPetInfoByConsumerId(db *sql.DB, consumerId string, hospitalId int64) ([]models.Pet, error) {

	queryPetSQL := `select p.id, p.his_consumer_id, p.con_kind_id, p.kind, p.con_species_id, p.species,
	p._code, p._name, p.namepy, p.birthday, p.sex, p.coatcolor, p.is_dead, p.is_immunity, p.is_sterilized, p.is_insecticide,
	p.discription, p.addtime, p.weight,h.id,h.hospital_code,h._name, p.sys_file_id from his_pet p left join sys_hospital h on p.sys_hospital_id=h.id where p.delflag = 0 and p.his_consumer_id = ?`

	pets := make([]models.Pet, 0)

	rows, err := db.Query(queryPetSQL, consumerId)
	if err != nil {
		return nil, err
	}

	for rows.Next() {
		var pet models.Pet

		err = rows.Scan(&pet.ID, &pet.HisConsumerId, &pet.ConKindId, &pet.Kind, &pet.ConSpeciesID, &pet.Species,
			&pet.PetCode, &pet.PetName, &pet.PetNamepy, &pet.PetBirthday, &pet.PetSex, &pet.CoatColor, &pet.IsDead,
			&pet.IsImmunity, &pet.IsSterilized, &pet.IsInsecticide, &pet.Discription, &pet.AddTime, &pet.Weight,
			&pet.HospitalID, &pet.HospitalCode, &pet.HospitalName, &pet.SysFileID)

		if err != nil {
			return nil, err
		}

		if pet.HospitalID != hospitalId {
			pet.IsChain = 1
		}

		if pet.SysFileID != 0 {
			err = db.QueryRow(`select guid, extension from sys_file where id =  ?`, pet.SysFileID).Scan(&pet.SysFileGuid, &pet.SysFileExtension)
			if err != nil {
				return nil, err
			}
		}

		pets = append(pets, pet)

	}

	return pets, err
}

func GetCardInfoByPetId(db *sql.DB, consumerId string, hospitalId int64) ([]models.CardAndMeterCard, error) {

	// 查询会员卡sql
	queryCardSQL := `select id, _code, con_cardtype_id, cardtype, createtime, 
					convert(money / 1000, decimal(11,3)), 
					convert(presentmoney / 1000, decimal(11,3)), 
					isuse_password, _password, 
					convert(off / 1000, decimal(11,3))
					from his_card
					where delflag = 0 and his_consumer_id = ?
					order by id desc`

	querySecondCardSQL := `select id, _code, con_metercardtype_id, metercardtype_name, 
							meter, overtime, opentime 
							from his_metercard
							where delflag = 0 and sys_hospital_id = ? and his_consumer_id = ?
							order by id desc`

	rows, err := db.Query(queryCardSQL, consumerId)
	if err != nil {
		return nil, err
	}

	returnListModel := make([]models.CardAndMeterCard, 0)

	for rows.Next() {
		var t models.CardAndMeterCard
		t.Type = 1
		err = rows.Scan(&t.ID, &t.Code, &t.ConCardTypeID, &t.ConCardTypeName,
			&t.CreateTime, &t.Money, &t.PresentMoney, &t.IsusePassword, &t.Password, &t.Off)
		if err != nil {
			return nil, err
		}
		returnListModel = append(returnListModel, t)
	}

	rowsSecond, err := db.Query(querySecondCardSQL, hospitalId, consumerId)
	if err != nil {
		return nil, err
	}

	for rowsSecond.Next() {
		var t models.CardAndMeterCard
		t.Type = 2
		err = rowsSecond.Scan(&t.ID, &t.Code, &t.ConCardTypeID, &t.ConCardTypeName, &t.Meter, &t.Overtime, &t.Opentime)
		if err != nil {
			return nil, err
		}
		returnListModel = append(returnListModel, t)
	}

	return returnListModel, nil
}

func AddAppointment(db *sql.DB, p *models.AppointmentParam, hospitalId int) (interface{}, error) {

	sqlStr := fmt.Sprintf(`insert his_appointment set sys_hospital_id = ?, his_consumer_id = ?, his_consumer_name = ?, his_consumer_telephone =?,
	 his_pet_id=  ?, his_pet_name = ?, con_employee_id = ?, con_employee_name  = ?, appointment_type = ?, 
	 appointment_name = ?, appointment_time = ?, state =  0, description = ?, eventtime = ?, source = 2 , ispre_weixinnotify = ?, ispre_smsnotify = ?, 
iscur_weixinnotify = ?, iscur_smsnotify = ?,pre_weixinnum = ?, pre_smsnum = ? `)
	_, err := db.Exec(sqlStr, hospitalId, p.ConsumerID, p.ConsumerName, p.ConsumerPhone, p.PetID, p.PetName, p.DoctorID, p.DoctorName,
		p.ProjectID, p.ProjectName, p.AppointmentTime, p.Description, time.Now().Format("2006-01-02 15:04:05"), p.IspreWeixinnotify, p.IspreSmsnotify,
		p.IscurWeixinnotify, p.IscurSmsnotify, p.PreWeixinnum, p.PreSmsnum)
	if err != nil {
		return nil, err
	}

	return nil, nil
}

func GetLastPetCode(db *sql.DB, hospitalID int) (interface{}, error) {
	var (
		resp models.PetCode
		code string
	)

	tag := "P"

	err := db.QueryRow("select _code from his_pet where delflag = 0 and sys_hospital_id = ? order by id desc limit 1", hospitalID).Scan(&code)
	switch {
	case err == sql.ErrNoRows:
		resp.Code = tag + "000001"
		return resp.Code, nil
	case err != nil:
		return resp.Code, err
	}
	codeLength := len(code)
	index := 0
	for i := codeLength; i > 0; i-- {
		_, err := strconv.Atoi(code[i-1 : i])
		if err != nil {
			index = i
			break
		}
	}
	pre := code[:index]
	numstr := code[index:]
	num, err := strconv.ParseInt(numstr, 10, 0)
	if err != nil {
		resp.Code = tag + "000001"
		return resp.Code, nil
	}
	code = fmt.Sprintf("%s%0"+fmt.Sprintf("%d", len(numstr))+"d", pre, num+1)

	resp.Code = code
	return resp.Code, nil
}

func GetSpeciesList(db *sql.DB, hospitalID int, speciesId string) (interface{}, error) {

	sqlStr := "select id, creater, updater, sys_hospital_id, _name as 'name', namepy, sys_kind_id, ordervalue, remarks from con_species where delflag = 0 and sys_kind_id = ? ORDER BY ordervalue desc"

	return QueryArray(db, sqlStr, speciesId)

}

func CheckPhoneIsHave(db *sql.DB, phone string, hospitalID int) (int, error) {

	var isHave int

	sqlStr := ` select count(0)  from   his_consumer where  telephone = ?  and  sys_hospital_id = ?	 `

	err := db.QueryRow(sqlStr, phone, hospitalID).Scan(&isHave)
	if err != nil {
		return isHave, err
	}

	return isHave, err

}