package customer

import (
	"errors"
	"spaceofcheng/services/models"
	"spaceofcheng/services/models/model"
	"spaceofcheng/services/utils"
	"time"

	"github.com/yl10/kit/guid"

	"github.com/go-xorm/xorm"
)

// CustomerDAO 当前数据库操作对象
type CustomerDAO struct {
	ctx *utils.Context
	db  *xorm.Session
}

// NewCustomerDAO New Inst
func NewCustomerDAO(ctx *utils.Context) *CustomerDAO {
	return &CustomerDAO{
		ctx: ctx,
		db:  ctx.DB,
	}
}

// CustWithWXList 客户列表
func (m *CustomerDAO) CustWithWXList(phone string, page ...int) ([]CustWithWX, int64, error) {
	org := m.ctx.Get("org").(model.SysOrg)

	if phone == "" {
		phone = "%"
	} else {
		phone = "%" + phone + "%"
	}

	pageNum := 10
	if m.ctx.Get("pageNum") != nil {
		pageNum = m.ctx.Get("pageNum").(int)
	}
	if len(page) > 1 {
		pageNum = page[1]
	}

	pg := 1
	if len(page) > 0 {
		pg = page[0]
	}
	offset := (pg - 1) * pageNum
	if offset < 0 {
		offset = 0
	}

	query := `
		SELECT
			t.*, s.account_info,
			s.account_type,
			s.mapping_id,
			s.openid,
			s.user_id as map_user,
			s.user_type,
			s.uuid
		FROM
			ta_customer t
		LEFT JOIN ta_user_mapping s ON t.customer_id = s.user_id
			AND s.user_type = '` + models.USERMAP_CUSTOMER + `'
			AND s.account_type = '` + models.ACCMAP_WECHAT + `'
		WHERE
			t.phone like ?
		AND t.status > ?
		AND t.org_id = '` + org.OrgId + `'
		ORDER BY
			t.create_date DESC
	`

	var cust []CustWithWX

	cnt, err := utils.NewPageNaviEngine(m.ctx).GetPageList(&cust, query, []int{pageNum, offset}, phone, models.STATUS_DEL)
	if err != nil {
		return nil, 0, err
	}

	return cust, cnt, nil
}

// GetCustWithWXByID 获取客户(微信)信息
func (m *CustomerDAO) GetCustWithWXByID(custID string) (*CustWithWX, error) {
	if custID == "" {
		return nil, errors.New("获取客户信息失败")
	}

	cust := CustWithWX{}
	query := `
		SELECT *, t.user_id as map_user
		FROM
			ta_customer t
		LEFT JOIN ta_user_mapping s ON t.customer_id = s.user_id
			AND s.user_type = '` + models.USERMAP_CUSTOMER + `'
			AND s.account_type = '` + models.ACCMAP_WECHAT + `'
		WHERE
			t.customer_id = ?
	`

	if _, err := m.db.SQL(query, custID).Get(&cust); err != nil {
		return nil, err
	}

	return &cust, nil
}

// GetCustomerByPhone 依据手机号获取客户信息
func (m *CustomerDAO) GetCustomerByPhone(phone string) (*model.TaCustomer, error) {
	custs := []model.TaCustomer{}

	if err := m.db.Where("phone=?", phone).Find(&custs); err != nil {
		return nil, err
	}

	if len(custs) == 0 {
		return nil, nil
	}

	if len(custs) > 0 {
		return nil, errors.New("数据异常, 一个手机绑定了多个用户")
	}

	cust := custs[0]

	return &cust, nil
}

// UpdateUserMapping 更新用户映射
func (m *CustomerDAO) UpdateUserMapping(userMap *model.TaUserMapping, cols []string) error {
	if userMap.MappingId == "" {
		return errors.New("用户映射信息不存在")
	}

	_, err := m.db.Where("mapping_id=?", userMap.MappingId).Cols(cols...).Update(userMap)
	return err
}

// GetCaseByID 获取案场
// func (m *CustomerDAO) GetCaseByID(caseID string) (*model.SysCase, error) {
// 	if caseID == "" {
// 		return nil, errors.New("获取案场信息失败")
// 	}

// 	cs := model.SysCase{}
// 	has, err := m.db.Where("case_id=?", caseID).Get(&cs)
// 	if err != nil {
// 		return nil, err
// 	}

// 	if !has {
// 		return nil, nil
// 	}

// 	return &cs, nil
// }

// GetUserByID 获取系统用户
func (m *CustomerDAO) GetUserByID(userID string) (*model.SysUser, error) {
	if userID == "" {
		return nil, errors.New("获取相关人员信息失败")
	}

	user := model.SysUser{}
	has, err := m.db.Where("user_id=?", userID).Get(&user)
	if err != nil {
		return nil, err
	}

	if !has {
		return nil, nil
	}

	return &user, nil
}

// GetUserByPhone 依据手机号获取人员信息
func (m *CustomerDAO) GetUserByPhone(phone string) (*model.SysUser, error) {
	user := model.SysUser{}

	has, err := m.db.Where("phone=?", phone).Get(&user)
	if err != nil {
		return nil, err
	}

	if !has {
		return nil, nil
	}

	return &user, nil
}

// SaveCustomer 新增客户
func (m *CustomerDAO) SaveCustomer(cust *model.TaCustomer) error {
	cust.CustomerId = guid.NewGUIDString()
	cust.CreateDate = time.Now().Local()
	cust.Status = models.STATUS_NORMAL

	_, err := m.db.Insert(cust)
	return err
}

// GetCustomerByID 依据ID获取客户
func (m *CustomerDAO) GetCustomerByID(id string) (*model.TaCustomer, error) {
	cust := new(model.TaCustomer)

	if _, err := m.db.Where("customer_id=?", id).Get(cust); err != nil {
		return nil, err
	}

	return cust, nil
}
