package service

import (
	"errors"
	"fmt"
	"time"

	"gopkg.in/guregu/null.v3"

	"xiaoniaokuaiyan.com/xiaoniao/entity"
	"xiaoniaokuaiyan.com/xiaoniao/util"
)

type SystemService struct{}

func (srv *SystemService) GetFirstPagePicList() (interface{}, error) {
	db := util.GetSqlDB()
	strSql := "select title, value from t_dictionaries where class = ? and flag = 'Y';"
	var rList = []struct {
		Title string `db:"title" json:"title"`
		Value string `db:"value", json:"value"`
	}{}
	err := db.Select(&rList, strSql, "indexpic")
	return rList, err
}

func (srv *SystemService) GetWorkdays(n int) (interface{}, error) {
	if n <= 0 {
		n = 7
	}
	today := time.Now().Format("2006-01-02")
	strSql := "select curr_date from t_workdays where isworkday = 'Y' and curr_date > ? order by curr_date asc limit ?;"
	workDays := []string{}
	db := util.GetWriteSqlDB()
	err := db.Select(&workDays, strSql, today, n)
	return workDays, err
}

func (srv *SystemService) GetQuestion(qid int) (interface{}, error) {
	if qid == 0 {
		qid = 5
	}
	db := util.GetSqlDB()
	strSql := "select title from t_activity_title where id = ?;"
	var qTitle string
	err := db.Get(&qTitle, strSql, qid)
	if err != nil {
		return nil, err
	}
	var qlist = []struct {
		Id           int           `json:"id" db:"id"`
		AtId         int           `json:"at_id" db:"at_iq"`
		Title        string        `json:"title" db:"title"`
		Type         string        `json:"type" db:"type"`
		IsShow       string        `json:"is_show" db:"is_show"`
		IsMust       string        `json:"is_must" db:"is_must"`
		VerifyRule   string        `json:"verify_rule" db:"verify_rule"`
		LogicAllAqId string        `json:"logic_all_aq_id" db:"logic_all_aq_id"`
		DefaultValue string        `json:"default_value" db:"default_value"`
		Order        string        `json:"order" db:"order"`
		OptionList   []interface{} `json:"option_list" db:"-"`
	}{}
	strSql = "select * from t_activity_question where at_iq = ? order by `order`;"
	err = db.Select(&qlist, strSql, qid)
	if err != nil {
		return nil, err
	}
	if len(qlist) == 0 {
		return nil, errors.New("数据错误")
	}
	var (
		strAqIds    string
		qlistIdxMap = map[int]int{}
	)
	for idx, qitem := range qlist {
		strAqIds += fmt.Sprintf("%d,", qitem.Id)
		qlistIdxMap[qitem.Id] = idx
	}
	strAqIds = strAqIds[0 : len(strAqIds)-1]
	strSql = "select * from t_activity_option where aq_id in(" + strAqIds + ") order by aq_id,`order`;"
	var optionList = []struct {
		Id             int           `json:"id" db:"id"`
		AqId           int           `json:"aq_id" db:"aq_id"`
		Name           string        `json:"name" db:"name"`
		LogicAqId      null.String   `json:"logic_aq_id" db:"logic_aq_id"`
		Order          string        `json:"order" db:"order"`
		DetectProducts []interface{} `json:"detect_products" db:"-"`
	}{}
	err = db.Select(&optionList, strSql)
	if err != nil {
		return nil, err
	}

	if len(optionList) == 0 {
		return nil, errors.New("数据错误1")
	}
	var (
		strOpids    string
		olistIdxMap = map[int]int{}
	)
	for idx, oitem := range optionList {
		strOpids += fmt.Sprintf("%d,", oitem.Id)
		olistIdxMap[oitem.Id] = idx
	}
	strOpids = strOpids[0 : len(strOpids)-1]
	strSql = "select t1.*, t2.price from t_activity_detect t1 left join t_detect_product t2 on t1.detect_product_id=t2.id where ap_id in(" + strOpids + ") or ap_id is NULL order by ap_id;"
	var dpList = []struct {
		Id                int      `json:"id" db:"id"`
		ApId              null.Int `json:"ap_id" db:"ap_id"`
		DetectProductId   int      `json:"detect_product_id" db:"detect_product_id"`
		DetectProductName string   `json:"detect_product_name" db:"detect_product_name"`
		Price             int      `json:"price" db:"price"`
		IsBase            string   `json:"is_base" db:"is_base"`
	}{}

	err = db.Select(&dpList, strSql)
	if err != nil {
		return nil, err
	}

	if len(dpList) == 0 {
		return nil, errors.New("数据错误3")
	}
	var result = struct {
		BaseDetectProducts []interface{} `json:"base_detect_products"`
		Title              string        `json:"title"`
		QuestionList       interface{}   `json:"question_list"`
	}{
		Title: qTitle,
	}

	for _, dpItem := range dpList {
		if idx, ok := olistIdxMap[int(dpItem.ApId.Int64)]; ok {
			optionList[idx].DetectProducts = append(optionList[idx].DetectProducts, dpItem)
		} else {
			result.BaseDetectProducts = append(result.BaseDetectProducts, dpItem)
		}
	}
	for _, oitem := range optionList {
		if idx, ok := qlistIdxMap[oitem.AqId]; ok {
			qlist[idx].OptionList = append(qlist[idx].OptionList, oitem)
		}
	}
	result.QuestionList = qlist
	return result, nil
}

func (srv *SystemService) GetDictList(className, ordernum string) (interface{}, error) {
	var dictList = []entity.DictItem{}
	db := util.GetSqlDB()
	if len(ordernum) == 0 {
		strSql := "select * from t_dictionaries where class = ? and flag = 'Y';"
		err := db.Select(&dictList, strSql, className)
		return dictList, err
	} else {
		strSql := "select * from t_dictionaries where class = ? and ordernum = ? and flag='Y';"
		err := db.Select(&dictList, strSql, className, ordernum)
		return dictList, err
	}
}