package data_stat

import (
	"encoding/json"
	"eta/eta_mobile/controllers"
	"eta/eta_mobile/models"
	"eta/eta_mobile/models/data_manage"
	"eta/eta_mobile/models/data_stat"
	"eta/eta_mobile/utils"
	"fmt"
	"github.com/rdlucklib/rdluck_tools/paging"
	"strings"
	"time"
)

// EdbSourceStatController 数据源统计表管理模块
type EdbSourceStatController struct {
	controllers.BaseAuthController
}

// Column
// @Title 数据源统计表自定义列列表
// @Description 查询 数据源统计表自定义列列表
// @Success 200 {object} data_stat.StatColumnList
// @router /source_column [get]
func (this *EdbSourceStatController) Column() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	columnType, _ := this.GetInt("ColumnType")
	if columnType <= 0 {
		br.Msg = "请选择表类型"
		return
	}
	tmpList, err := data_stat.GetStatColumn(columnType)
	if err != nil {
		br.Msg = "获取自定义列失败"
		br.ErrMsg = "获取自定义列失败,Err:" + err.Error()
		return
	}
	var list []*data_stat.EdbInfoStatColumnListItem
	for _, v := range tmpList {
		tmp := new(data_stat.EdbInfoStatColumnListItem)
		tmp.ColumnKey = v.ColumnKey
		tmp.IsShow = v.IsShow
		tmp.ColumnName = v.ColumnName
		tmp.Id = v.Id
		tmp.IsMust = v.IsMust
		tmp.IsSort = v.IsSort
		tmp.Type = v.Type
		list = append(list, tmp)
	}
	var statColumnList data_stat.StatColumnList
	statColumnList.List = list
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = statColumnList
}

// EditColumn
// @Title 编辑数据源统计表自定义列
// @Description 编辑 数据源统计表自定义列列表
// @Success 200 {object} data_stat.StatColumnList
// @router /source_column/edit [post]
func (this *EdbSourceStatController) EditColumn() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	var req data_stat.EditStatColumnReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	if len(req.List) <= 0 {
		br.Msg = "请选择要修改的列"
		br.IsSendEmail = false
		return
	}

	tmpList, err := data_stat.GetAllStatColumn()
	if err != nil {
		br.Msg = "获取自定义列失败"
		br.ErrMsg = "获取自定义列失败,Err:" + err.Error()
		return
	}
	isMustMap := make(map[int]data_stat.EdbInfoStatColumn)
	if len(tmpList) > 0 {
		for _, v := range tmpList {
			if v.IsMust == 1 {
				isMustMap[v.Id] = v
			}
		}
	}

	var list []*data_stat.EdbInfoStatColumn
	for k, v := range req.List {
		if v.Id == 0 {
			br.Msg = "列序号不能为空"
			return
		}

		if v.IsShow == 0 {
			if exist, ok := isMustMap[v.Id]; ok {
				br.Msg = exist.ColumnName + "为必选列！"
				return
			}
		}
		tmp := new(data_stat.EdbInfoStatColumn)
		tmp.Id = v.Id
		tmp.Sort = k + 1
		tmp.IsShow = v.IsShow
		list = append(list, tmp)
	}

	err = data_stat.UpdateStatColumn(list)
	if err != nil {
		br.Msg = "更新自定义列操作失败！"
		br.ErrMsg = "更新自定义列操作失败，Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	return
}

// EdbDeleteLog
// @Title 查询删除指标列表
// @Description 查询删除指标列表接口
// @Success 200 {object} data_stat.GetEdbDeleteLogResp
// @router /edb_delete_log [get]
func (this *EdbSourceStatController) EdbDeleteLog() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	sortParamReq := this.GetString("SortParam", "")
	sortType := this.GetString("SortType", "desc")
	createTime := this.GetString("CreateTime", "")

	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")

	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}

	startSize = paging.StartIndex(currentIndex, pageSize)

	condition := " and source = ?"
	var pars []interface{}
	pars = append(pars, utils.DATA_SOURCE_MYSTEEL_CHEMICAL)

	if createTime != "" {
		startT, err := time.ParseInLocation(utils.FormatDate, createTime, time.Local)
		if err != nil {
			br.Msg = "请求时间格式错误"
			return
		}
		endT := startT.AddDate(0, 0, 1)
		condition += " AND create_time >= ? AND create_time < ?"
		pars = append(pars, createTime, endT.Format(utils.FormatDate))
	}

	sortStr := ``
	sortParam := ``
	if sortParamReq != `` {
		switch sortParamReq {
		case "CreateTime":
			sortParam = "create_time"
		case "DataUpdateTime":
			sortParam = "data_update_time"
		case "ErDataUpdateDate":
			sortParam = "er_data_update_date"
		case "LatestDate":
			sortParam = "latest_date"
		case "StartDate":
			sortParam = "start_date"
		}
		if sortParam == "" {
			br.Msg = "请输入正确的排序字段"
			return
		}
		if strings.ToLower(sortType) != "asc" && strings.ToLower(sortType) != "desc" {
			br.Msg = "请输入正确的排序类型"
			return
		}
		sortStr = fmt.Sprintf(" order by %s %s, id desc ", sortParam, sortType)
	}
	total, err := data_stat.GetEdbDeleteLogCount(condition, pars)
	if err != nil {
		if err.Error() != utils.ErrNoRow() {
			br.Msg = "获取指标删除列表总数失败"
			br.ErrMsg = "获取指标删除列表总数失败,Err:" + err.Error()
			return
		} else {
			err = nil
		}
	}
	list := make([]*data_stat.EdbInfoDeleteLogItem, 0)
	page := paging.GetPaging(currentIndex, pageSize, total)
	if total == 0 {
		resp := data_stat.GetEdbDeleteLogResp{
			Paging: page,
			List:   list,
		}
		br.Ret = 200
		br.Success = true
		br.Msg = "获取成功"
		br.Data = resp
		return
	}
	tmpList, err := data_stat.GetEdbDeleteLogByCondition(condition, pars, sortStr, pageSize, startSize)
	if err != nil {
		br.Msg = "获取指标删除列表失败"
		br.ErrMsg = "获取指标删除列表失败,Err:" + err.Error()
		return
	}

	for _, v := range tmpList {
		tmp := new(data_stat.EdbInfoDeleteLogItem)
		tmp.EdbCode = v.EdbCode
		tmp.EdbInfoId = v.EdbInfoId
		tmp.Id = v.Id
		tmp.StartDate = v.StartDate
		tmp.EndDate = v.EndDate
		tmp.Unit = v.Unit
		tmp.TerminalCode = v.TerminalCode
		tmp.CreateTime = v.CreateTime
		tmp.EdbCreateTime = v.EdbCreateTime
		tmp.Frequency = v.Frequency
		tmp.Source = v.Source
		tmp.SourceName = v.SourceName
		tmp.EdbName = v.EdbName
		tmp.EdbNameEn = v.EdbNameEn
		tmp.EdbNameSource = v.EdbNameSource
		tmp.LatestDate = v.LatestDate

		tmp.DelSysUserId = v.DelSysUserId
		tmp.DelSysUserRealName = v.DelSysUserRealName
		tmp.SysUserId = v.SysUserId
		tmp.SysUserRealName = v.SysUserRealName
		tmp.LatestValue = v.LatestValue
		if v.DataUpdateTime != utils.EmptyDateTimeStr {
			tmp.DataUpdateTime = v.DataUpdateTime
		}
		if v.ErDataUpdateDate != utils.EmptyDateStr {
			tmp.ErDataUpdateDate = v.ErDataUpdateDate
		}
		list = append(list, tmp)
	}

	resp := data_stat.GetEdbDeleteLogResp{
		Paging: page,
		List:   list,
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// EdbUpdateLog
// @Title 查询指标信息变更列表
// @Description 查询指标信息变更列表接口
// @Success 200 {object} data_stat.GetEdbUpdateLogResp
// @router /edb_update_log [get]
func (this *EdbSourceStatController) EdbUpdateLog() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	sortParamReq := this.GetString("SortParam", "")
	sortType := this.GetString("SortType", "desc")
	createTime := this.GetString("CreateTime", "")
	updateType, _ := this.GetInt("UpdateType", -1)

	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")

	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}

	startSize = paging.StartIndex(currentIndex, pageSize)

	condition := " and source = ? and (data_update_result=1 or data_update_result=0)"
	var pars []interface{}
	pars = append(pars, utils.DATA_SOURCE_MYSTEEL_CHEMICAL)

	if createTime != "" {
		startT, err := time.ParseInLocation(utils.FormatDate, createTime, time.Local)
		if err != nil {
			br.Msg = "请求时间格式错误"
			return
		}
		endT := startT.AddDate(0, 0, 1)
		condition += " AND create_time >= ? AND create_time < ?"
		pars = append(pars, createTime, endT.Format(utils.FormatDate))
	}
	if updateType >= 0 {
		condition += " AND update_type =? "
		pars = append(pars, updateType)
	}
	sortStr := ``
	sortParam := ``
	if sortParamReq != `` {
		switch sortParamReq {
		case "CreateTime":
			sortParam = "create_time"
		case "DataUpdateTime":
			sortParam = "data_update_time"
		case "ErDataUpdateDate":
			sortParam = "er_data_update_date"
		case "LatestDate":
			sortParam = "latest_date"
		case "StartDate":
			sortParam = "start_date"
		}
		if sortParam == "" {
			br.Msg = "请输入正确的排序字段"
			return
		}
		if strings.ToLower(sortType) != "asc" && strings.ToLower(sortType) != "desc" {
			br.Msg = "请输入正确的排序类型"
			return
		}
		sortStr = fmt.Sprintf(" order by %s %s, id desc ", sortParam, sortType)
	}
	total, err := data_stat.GetEdbUpdateLogCount(condition, pars)
	if err != nil {
		if err.Error() != utils.ErrNoRow() {
			br.Msg = "获取指标删除列表总数失败"
			br.ErrMsg = "获取指标删除列表总数失败,Err:" + err.Error()
			return
		} else {
			err = nil
		}
	}
	list := make([]*data_stat.EdbInfoUpdateLogItem, 0)
	page := paging.GetPaging(currentIndex, pageSize, total)
	if total == 0 {
		resp := data_stat.GetEdbUpdateLogResp{
			Paging: page,
			List:   list,
		}
		br.Ret = 200
		br.Success = true
		br.Msg = "获取成功"
		br.Data = resp
		return
	}
	tmpList, err := data_stat.GetEdbUpdateLogByCondition(condition, pars, sortStr, pageSize, startSize)
	if err != nil {
		br.Msg = "获取指标更新列表失败"
		br.ErrMsg = "获取指标更新列表失败,Err:" + err.Error()
		return
	}

	for _, v := range tmpList {
		tmp := new(data_stat.EdbInfoUpdateLogItem)
		tmp.Id = v.Id
		tmp.EdbInfoId = v.EdbInfoId
		tmp.SourceName = v.SourceName
		tmp.Source = v.Source
		tmp.EdbCode = v.EdbCode
		tmp.EdbName = v.EdbName
		tmp.EdbNameSource = v.EdbNameSource
		tmp.Frequency = v.Frequency
		tmp.Unit = v.Unit
		tmp.StartDate = v.StartDate
		tmp.EndDate = v.EndDate
		tmp.SysUserId = v.SysUserId
		tmp.SysUserRealName = v.SysUserRealName
		tmp.UpdateSysUserRealName = v.UpdateSysUserRealName
		tmp.UpdateSysUserId = v.UpdateSysUserId
		tmp.UniqueCode = v.UniqueCode
		tmp.CreateTime = v.CreateTime.Format(utils.FormatDateTime)
		tmp.LatestDate = v.LatestDate
		tmp.LatestValue = v.LatestValue
		tmp.TerminalCode = v.TerminalCode
		if v.DataUpdateTime != utils.EmptyDateTimeStr {
			tmp.DataUpdateTime = v.DataUpdateTime
		}
		if v.ErDataUpdateDate != utils.EmptyDateStr {
			tmp.ErDataUpdateDate = v.ErDataUpdateDate
		}
		tmp.UpdateType = v.UpdateType
		list = append(list, tmp)
	}

	resp := data_stat.GetEdbUpdateLogResp{
		Paging: page,
		List:   list,
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// EdbUpdateStat
// @Title 查询数据源明细列表
// @Description 查询数据源明细列表接口
// @Success 200 {object} data_stat.GetEdbUpdateStatResp
// @router /edb_update_stat [get]
func (this *EdbSourceStatController) EdbUpdateStat() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	sortParamReq := this.GetString("SortParam", "")
	sortType := this.GetString("SortType", "desc")
	terminalCode := this.GetString("TerminalCode", "")
	sysUserId := this.GetString("SysUserId", "")
	frequency := this.GetString("Frequency", "")
	keyWord := this.GetString("KeyWord", "") //指标编码/指标名称

	createTime := this.GetString("CreateTime", "")

	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")

	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}

	startSize = paging.StartIndex(currentIndex, pageSize)

	condition := " and source = ?"
	var pars []interface{}
	pars = append(pars, utils.DATA_SOURCE_MYSTEEL_CHEMICAL)
	if createTime != "" {
		startT, err := time.ParseInLocation(utils.FormatDate, createTime, time.Local)
		if err != nil {
			br.Msg = "请求时间格式错误"
			return
		}
		endT := startT.AddDate(0, 0, 1)
		condition += " AND create_time >= ? AND create_time < ?"
		pars = append(pars, createTime, endT.Format(utils.FormatDate))
	}

	if terminalCode != "" {
		codeSlice := strings.Split(terminalCode, ",")
		condition += ` AND terminal_code IN (` + utils.GetOrmInReplace(len(codeSlice)) + `)`
		pars = append(pars, codeSlice)
	}

	if sysUserId != "" {
		sysUserIdSlice := strings.Split(sysUserId, ",")
		condition += ` AND sys_user_id IN (` + utils.GetOrmInReplace(len(sysUserIdSlice)) + `)`
		pars = append(pars, sysUserIdSlice)
	}

	if frequency != "" {
		frequencySlice := strings.Split(frequency, ",")
		condition += ` AND frequency IN (` + utils.GetOrmInReplace(len(frequencySlice)) + `)`
		pars = append(pars, frequencySlice)
	}

	if keyWord != "" {
		condition += ` AND (edb_name LIKE ? OR edb_code LIKE ? ) `
		pars = append(pars, "%"+keyWord+"%", "%"+keyWord+"%")
	}

	sortStr := ``
	sortParam := ``
	if sortParamReq != `` {
		switch sortParamReq {
		case "CreateTime":
			sortParam = "create_time"
		case "UpdateTime":
			sortParam = "update_time"
		case "DataUpdateTime":
			sortParam = "data_update_time"
		case "ErDataUpdateDate":
			sortParam = "er_data_update_date"
		case "LatestDate":
			sortParam = "latest_date"
		case "StartDate":
			sortParam = "start_date"
		}
		if sortParam == "" {
			br.Msg = "请输入正确的排序字段"
			return
		}
		if strings.ToLower(sortType) != "asc" && strings.ToLower(sortType) != "desc" {
			br.Msg = "请输入正确的排序类型"
			return
		}
		sortStr = fmt.Sprintf(" order by %s %s, id desc ", sortParam, sortType)
	}
	total, err := data_stat.GetEdbUpdateStatCount(condition, pars)
	if err != nil {
		if err.Error() != utils.ErrNoRow() {
			br.Msg = "获取指标列表总数失败"
			br.ErrMsg = "获取指标列表总数失败,Err:" + err.Error()
			return
		} else {
			err = nil
		}
	}
	list := make([]*data_stat.EdbInfoUpdateStatItemMore, 0)
	page := paging.GetPaging(currentIndex, pageSize, total)
	if total == 0 {
		resp := data_stat.GetEdbUpdateStatResp{
			Paging: page,
			List:   list,
		}
		br.Ret = 200
		br.Success = true
		br.Msg = "获取成功"
		br.Data = resp
		return
	}
	tmpList, err := data_stat.GetEdbUpdateStatByCondition(condition, pars, sortStr, pageSize, startSize)
	if err != nil {
		br.Msg = "获取指标更新列表失败"
		br.ErrMsg = "获取指标更新列表失败,Err:" + err.Error()
		return
	}

	// 获取初始数据源名称
	var edbCodeList []string
	for _, v := range tmpList {
		edbCodeList = append(edbCodeList, v.EdbCode)
	}
	initSourceMap := make(map[string]string)
	if len(edbCodeList) > 0 {
		baseCond := " and index_code in (" + utils.GetOrmInReplace(len(edbCodeList)) + ")"
		var basePars []interface{}
		basePars = append(basePars, edbCodeList)
		indexList, tErr := data_manage.GetMysteelChemicalIndexList(baseCond, basePars, 0, 1000, "")
		if tErr != nil {
			br.Msg = "获取初始指标信息失败"
			br.ErrMsg = "获取初始指标信息失败,Err:" + tErr.Error()
			return
		}
		for _, v := range indexList {
			initSourceMap[v.IndexCode] = v.Source
		}
	}
	for _, v := range tmpList {
		tmp := new(data_stat.EdbInfoUpdateStatItemMore)
		tmp.Id = v.Id
		tmp.EdbInfoId = v.EdbInfoId
		tmp.SourceName = v.SourceName
		tmp.Source = v.Source
		tmp.EdbCode = v.EdbCode
		tmp.EdbName = v.EdbName
		tmp.EdbNameSource = v.EdbNameSource
		tmp.Frequency = v.Frequency
		tmp.Unit = v.Unit
		tmp.StartDate = v.StartDate
		tmp.SysUserId = v.SysUserId
		tmp.SysUserRealName = v.SysUserRealName
		tmp.LatestDate = v.LatestDate
		tmp.LatestValue = v.LatestValue
		tmp.TerminalCode = v.TerminalCode
		if v.DataUpdateTime != utils.EmptyDateTimeStr {
			tmp.DataUpdateTime = v.DataUpdateTime
		}
		if v.ErDataUpdateDate != utils.EmptyDateStr {
			tmp.ErDataUpdateDate = v.ErDataUpdateDate
		}
		tmp.DataUpdateResult = v.DataUpdateResult
		tmp.DataUpdateFailedReason = v.DataUpdateFailedReason
		if v.UpdateTime != utils.EmptyDateTimeStr {
			tmp.UpdateTime = v.UpdateTime
		}
		tmp.IsAdd = v.IsAdd
		tmp.NeedRefresh = v.NeedRefresh
		tmp.HasRefresh = v.HasRefresh
		tmp.InitSourceName, _ = initSourceMap[v.EdbCode]
		list = append(list, tmp)
	}

	resp := data_stat.GetEdbUpdateStatResp{
		Paging: page,
		List:   list,
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// EdbSourceStat
// @Title 查询数据源统计列表
// @Description 查询数据源统计列表接口
// @Success 200 {object} data_stat.GetEdbUpdateLogResp
// @router /source_stat [get]
func (this *EdbSourceStatController) EdbSourceStat() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	sortParamReq := this.GetString("SortParam", "")
	sortType := this.GetString("SortType", "desc")
	createTime := this.GetString("CreateTime", "")

	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")

	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}

	startSize = paging.StartIndex(currentIndex, pageSize)

	condition := " and source = ?"
	var pars []interface{}
	pars = append(pars, utils.DATA_SOURCE_MYSTEEL_CHEMICAL)

	if createTime != "" {
		startT, err := time.ParseInLocation(utils.FormatDate, createTime, time.Local)
		if err != nil {
			br.Msg = "请求时间格式错误"
			return
		}
		endT := startT.AddDate(0, 0, 1)
		condition += " AND create_time >= ? AND create_time < ?"
		pars = append(pars, createTime, endT.Format(utils.FormatDate))
	}

	sortStr := ``
	sortParam := ``
	if sortParamReq != `` {
		switch sortParamReq {
		case "EdbNum":
			sortParam = "edb_num"
		case "NeedRefreshNum":
			sortParam = "need_refresh_num"
		case "hasRefreshNum":
			sortParam = "has_refresh_num"
		case "UpdateSuccessNum":
			sortParam = "update_success_num"
		case "UpdateFailedNum":
			sortParam = "update_failed_num"
		}

		if sortParam == "" {
			br.Msg = "请输入正确的排序字段"
			return
		}
		if strings.ToLower(sortType) != "asc" && strings.ToLower(sortType) != "desc" {
			br.Msg = "请输入正确的排序类型"
			return
		}
		sortStr = fmt.Sprintf(" order by %s %s, id desc ", sortParam, sortType)
	}
	total, err := data_stat.GetEdbSourceStatCount(condition, pars)
	if err != nil {
		if err.Error() != utils.ErrNoRow() {
			br.Msg = "获取数据源统计列表总数失败"
			br.ErrMsg = "获取数据源统计列表总数失败,Err:" + err.Error()
			return
		} else {
			err = nil
		}
	}
	list := make([]*data_stat.EdbInfoSourceStatItem, 0)
	page := paging.GetPaging(currentIndex, pageSize, total)
	if total == 0 {
		resp := data_stat.GetEdbSourceStatResp{
			Paging: page,
			List:   list,
		}
		br.Ret = 200
		br.Success = true
		br.Msg = "获取成功"
		br.Data = resp
		return
	}
	tmpList, err := data_stat.GetEdbSourceStatByCondition(condition, pars, sortStr, pageSize, startSize)
	if err != nil {
		br.Msg = "获取指标删除列表失败"
		br.ErrMsg = "获取指标删除列表失败,Err:" + err.Error()
		return
	}

	for _, v := range tmpList {
		tmp := new(data_stat.EdbInfoSourceStatItem)
		tmp.Id = v.Id
		tmp.SourceName = v.SourceName
		tmp.Source = v.Source
		tmp.TerminalCode = v.TerminalCode
		tmp.EdbNum = v.EdbNum
		tmp.EdbNewNum = v.EdbNewNum
		tmp.EdbDelNum = v.EdbDelNum
		tmp.NeedRefreshNum = v.NeedRefreshNum
		tmp.HasRefreshNum = v.HasRefreshNum
		tmp.UpdateSuccessNum = v.UpdateSuccessNum
		tmp.UpdateFailedNum = v.UpdateFailedNum
		tmp.RefreshSuccessNum = v.RefreshSuccessNum
		tmp.RefreshFailedNum = v.RefreshFailedNum
		list = append(list, tmp)
	}

	resp := data_stat.GetEdbSourceStatResp{
		Paging: page,
		List:   list,
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// EdbUpdateFailedList
// @Title 查询指标更新失败详情汇总列表
// @Description 查询指标更新失败详情汇总列表
// @Success 200 {object} data_stat.GetEdbUpdateLogResp
// @router /edb_update_stat/failed [get]
func (this *EdbSourceStatController) EdbUpdateFailedList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	terminalCode := this.GetString("TerminalCode", "")
	createTime := this.GetString("CreateTime", "")

	if terminalCode == "" {
		br.Msg = "请选择对应的终端信息"
		return
	}
	terminalInfo, err := data_manage.GetEdbTerminalByTerminalCode(terminalCode)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "终端不存在"
			return
		}
		br.Msg = "查询终端信息出错"
		br.ErrMsg = "查询终端信息出错 Err：" + err.Error()
		return
	}
	condition := " and source = ? and terminal_code = ?"
	var pars []interface{}
	pars = append(pars, utils.DATA_SOURCE_MYSTEEL_CHEMICAL, terminalCode)

	if createTime != "" {
		startT, err := time.ParseInLocation(utils.FormatDate, createTime, time.Local)
		if err != nil {
			br.Msg = "请求时间格式错误"
			return
		}
		endT := startT.AddDate(0, 0, 1)
		condition += " AND create_time >= ? AND create_time < ?"
		pars = append(pars, createTime, endT.Format(utils.FormatDate))
	}

	tmpList, err := data_stat.GetEdbUpdateStatFailedGroupByCondition(condition, pars)
	if err != nil {
		br.Msg = "获取指标更新失败详情列表 失败"
		br.ErrMsg = "获取指标更新失败详情列表 失败,Err:" + err.Error()
		return
	}

	list := make([]*data_stat.EdbUpdateFailedList, 0)
	successNum := 0
	failedNum := 0
	if len(tmpList) > 0 {
		for _, v := range tmpList {
			if v.SourceUpdateResult == 1 {
				successNum += v.Num
			} else {
				failedNum += v.Num
				list = append(list, v)
			}
		}
	}
	resp := data_stat.GetEdbUpdateFailedResp{
		List:             list,
		Name:             terminalInfo.Name,
		TerminalCode:     terminalCode,
		DirPath:          terminalInfo.DirPath,
		UpdateSuccessNum: successNum,
		UpdateFailedNum:  failedNum,
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// EdbUpdateFailedDetailList
// @Title 查询指标更新失败详情列表
// @Description 查询指标更新失败详情列表
// @Success 200 {object} data_stat.GetEdbUpdateLogResp
// @router /edb_update_stat/failed/detail [get]
func (this *EdbSourceStatController) EdbUpdateFailedDetailList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")

	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}

	startSize = paging.StartIndex(currentIndex, pageSize)

	terminalCode := this.GetString("TerminalCode", "")
	createTime := this.GetString("CreateTime", "")
	frequency := this.GetString("Frequency", "")
	sourceUpdateFailedReason := this.GetString("SourceUpdateFailedReason", "")

	if createTime == "" {
		br.Msg = "请选择创建时间"
		return
	}

	if terminalCode == "" {
		br.Msg = "请选择对应的终端信息"
		return
	}
	if frequency == "" {
		br.Msg = "请选择对应的频度"
		return
	}

	condition := " and source = ? and terminal_code = ? and frequency=? and data_update_failed_reason=? and data_update_result = 2"
	var pars []interface{}
	pars = append(pars, utils.DATA_SOURCE_MYSTEEL_CHEMICAL, terminalCode, frequency, sourceUpdateFailedReason)

	if createTime != "" {
		startT, err := time.ParseInLocation(utils.FormatDate, createTime, time.Local)
		if err != nil {
			br.Msg = "请求时间格式错误"
			return
		}
		endT := startT.AddDate(0, 0, 1)
		condition += " AND create_time >= ? AND create_time < ?"
		pars = append(pars, createTime, endT.Format(utils.FormatDate))
	}

	total, err := data_stat.GetEdbUpdateStatCount(condition, pars)
	if err != nil {
		if err.Error() != utils.ErrNoRow() {
			br.Msg = "获取指标列表总数失败"
			br.ErrMsg = "获取指标列表总数失败,Err:" + err.Error()
			return
		} else {
			err = nil
		}
	}
	list := make([]*data_stat.EdbInfoUpdateStatItemMore, 0)
	page := paging.GetPaging(currentIndex, pageSize, total)
	if total == 0 {
		resp := data_stat.GetEdbUpdateStatResp{
			Paging: page,
			List:   list,
		}
		br.Ret = 200
		br.Success = true
		br.Msg = "获取成功"
		br.Data = resp
		return
	}
	tmpList, err := data_stat.GetEdbUpdateStatByCondition(condition, pars, "", pageSize, startSize)
	if err != nil {
		br.Msg = "获取指标更新列表失败"
		br.ErrMsg = "获取指标更新列表失败,Err:" + err.Error()
		return
	}

	for _, v := range tmpList {
		tmp := new(data_stat.EdbInfoUpdateStatItemMore)
		tmp.Id = v.Id
		tmp.EdbInfoId = v.EdbInfoId
		tmp.SourceName = v.SourceName
		tmp.Source = v.Source
		tmp.EdbCode = v.EdbCode
		tmp.EdbName = v.EdbName
		tmp.EdbNameSource = v.EdbNameSource
		tmp.Frequency = v.Frequency
		tmp.Unit = v.Unit
		tmp.StartDate = v.StartDate
		tmp.SysUserId = v.SysUserId
		tmp.SysUserRealName = v.SysUserRealName
		tmp.LatestDate = v.LatestDate
		tmp.LatestValue = v.LatestValue
		tmp.TerminalCode = v.TerminalCode
		tmp.CreateTime = v.CreateTime.Format(utils.FormatDateTime)
		if v.DataUpdateTime != utils.EmptyDateTimeStr {
			tmp.DataUpdateTime = v.DataUpdateTime
		}
		if v.ErDataUpdateDate != utils.EmptyDateStr {
			tmp.ErDataUpdateDate = v.ErDataUpdateDate
		}
		tmp.DataUpdateResult = v.DataUpdateResult
		tmp.DataUpdateFailedReason = v.DataUpdateFailedReason
		if v.UpdateTime != utils.EmptyDateTimeStr {
			tmp.UpdateTime = v.UpdateTime
		}
		tmp.IsAdd = v.IsAdd
		tmp.NeedRefresh = v.NeedRefresh
		tmp.HasRefresh = v.HasRefresh
		list = append(list, tmp)
	}

	resp := data_stat.GetEdbUpdateStatResp{
		Paging: page,
		List:   list,
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}
