package repository

import (
	"database/sql"
	"errors"
	"gin-vue-admin/common"
)

// QueryEmployeeByPhone 查询手机号是否开通
func QueryEmployeeByPhone(phone string) (int, int, error) {

	var isOpen, hospitalID, jobState int

	db, err := common.NewAccountConn()
	if err != nil {
		return isOpen, hospitalID, err
	}

	// 判断是否有这个用户
	err = db.QueryRow(`select e.id, h.id, e.job_state
from employee_main as e
left join hospital_main as h on h.id = e.hospital_id
left join chain_main as c on c.id = h.chain_id
left join chain_config as cc on cc.chain_main_id = c.id
where e.delflag = 0
and h.delflag = 0
and h.id != 0
and cc.store_type = 0
and e.phone = ? limit 1`, phone).Scan(&isOpen, &hospitalID, &jobState)
	switch {
	case err == sql.ErrNoRows:
		return isOpen, hospitalID, errors.New("此账号不存在")
	case err != nil:
		return isOpen, hospitalID, err
	}

	if jobState > 0 {
		return 0, 0, errors.New("没有此用户")
	}

	return isOpen, hospitalID, nil
}

// RelationOpenID 用户的手机号 和 open_id 进行关联, 因为只有手机号是唯一的、用户id 也可能是多个
func RelationOpenID(phone, openID string) error {

	var userLength int

	db, err := common.NewAccountConn()
	if err != nil {
		return err
	}

	err = db.QueryRow(`select count(id) from employee_wx
	where employee_phone = ?`, phone).
		Scan(&userLength)
	if err != nil {
		return err
	}

	if userLength == 0 {
		res, err := db.Exec(`insert employee_wx set employee_phone = ?, 
		wx_open_id = ?`, phone, openID)
		if err != nil {
			return err
		}
		_, err = res.LastInsertId()
		if err != nil {
			return err
		}
	} else {
		res, err := db.Exec(`update employee_wx set wx_open_id = ? where employee_phone = ?`,
			openID, phone)
		if err != nil {
			return err
		}
		_, err = res.RowsAffected()
		if err != nil {
			return err
		}
	}

	return nil
}

// QueryEmployeeByOpenID 查询微信是否绑定了用户
func QueryEmployeeByOpenID(openID string) (int, error) {

	var isOpen int

	db, err := common.NewAccountConn()
	if err != nil {
		return isOpen, err
	}

	err = db.QueryRow(`select count(id)
	from employee_wx
	where wx_open_id = ?`, openID).
		Scan(&isOpen)
	if err != nil {
		return 0, err
	}

	return isOpen, nil
}

// QueryEmployeePhoneByOpenID 根据open_id 查询用户手机号
func QueryEmployeePhoneByOpenID(openID string) (string, error) {

	var phone string

	db, err := common.NewAccountConn()
	if err != nil {
		return "", err
	}

	err = db.QueryRow(`select employee_phone from employee_wx
	where wx_open_id = ?`, openID).Scan(&phone)
	if err != nil {
		return "", err
	}

	return phone, nil
}
