package supply_analysis

import (
	"encoding/json"
	"eta/eta_mobile/controllers"
	"eta/eta_mobile/models"
	"eta/eta_mobile/models/data_manage"
	"eta/eta_mobile/models/data_manage/request"
	"eta/eta_mobile/models/data_manage/response"
	"eta/eta_mobile/models/data_manage/supply_analysis"
	"eta/eta_mobile/services/data"
	supply_analysisServ "eta/eta_mobile/services/data/supply_analysis"
	"eta/eta_mobile/utils"
	"fmt"
	"github.com/rdlucklib/rdluck_tools/paging"
	"strconv"
	"strings"
	"time"
)

// VarietyController 期货指标分类
type VarietyController struct {
	controllers.BaseAuthController
}

// List
// @Title 存量装置图表分类列表
// @Description 存量装置图表分类列表接口
// @Param   IsAnalyse   query   bool  true       "是否有权限的，true、false"
// @Param   Keyword   query   string  true       "关键字搜索"
// @Success 200 {object} response.VarietyListResp
// @router /variety/list [get]
func (this *VarietyController) List() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	isAnalyse, _ := this.GetBool("IsAnalyse")
	keyword := this.GetString("Keyword")

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

	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = utils.StartIndex(currentIndex, pageSize)

	var condition string
	var pars []interface{}

	if keyword != `` {
		condition += ` AND (a.variety_name like ? OR c.edb_code like ? ) `
		pars = utils.GetLikeKeywordPars(pars, keyword, 2)
	}

	// 是否超管
	isSuperAdmin := supply_analysisServ.IsVarietySuperAdmin(this.SysUser)

	varietyObj := supply_analysis.Variety{}
	var total int
	var list []*supply_analysis.VarietyItem
	var err error
	if isSuperAdmin || !isAnalyse {
		total, list, err = varietyObj.GetListBySuperAdminPage(condition, pars, startSize, pageSize)
	} else {
		if isAnalyse {
			condition += ` AND b.sys_user_id = ? `
			pars = append(pars, this.SysUser.AdminId)
		}
		total, list, err = varietyObj.GetListByPage(condition, pars, startSize, pageSize)
	}
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}

	for k, v := range list {
		button := supply_analysis.VarietyButton{}
		if isSuperAdmin {
			button.Edit = true
			button.Delete = true
			button.Analyse = true
		} else {
			if v.PermissionUserId != `` {
				tmpUserIdStrList := strings.Split(v.PermissionUserId, ",")
				if utils.InArrayByStr(tmpUserIdStrList, strconv.Itoa(this.SysUser.AdminId)) {
					button.Analyse = true
				}
			}
		}

		v.Button = button
		list[k] = v
	}

	resp := response.VarietyListResp{
		AddButton: isSuperAdmin,
		Paging:    paging.GetPaging(currentIndex, pageSize, total),
		List:      list,
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// Add
// @Title 新增品种
// @Description 新增品种接口
// @Param	request	body request.AddVarietyReq true "type json string"
// @Success 200 Ret=200 添加成功
// @router /variety/add [post]
func (this *VarietyController) Add() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req request.AddVarietyReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	isSuperAdmin := supply_analysisServ.IsVarietySuperAdmin(this.SysUser)
	if !isSuperAdmin {
		br.Msg = "无操作权限"
		br.IsSendEmail = false
		return
	}

	if req.VarietyName == "" {
		br.Msg = "请输入品种名称"
		br.IsSendEmail = false
		return
	}
	varietyName := utils.TrimStr(req.VarietyName)
	item, err := supply_analysis.GetVarietyByName(varietyName)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "添加失败"
		br.ErrMsg = "添加失败，Err:" + err.Error()
		return
	}
	if item != nil {
		br.Msg = "添加失败，品种名称不能重复"
		br.IsSendEmail = false
		return
	}

	variety := &supply_analysis.Variety{
		VarietyId:                 0,
		VarietyName:               varietyName,
		LastUpdateSysUserId:       this.SysUser.AdminId,
		LastUpdateSysUserRealName: this.SysUser.RealName,
		ProductionDay:             365,
		SysUserId:                 this.SysUser.AdminId,
		SysUserRealName:           this.SysUser.RealName,
		ModifyTime:                time.Now(),
		CreateTime:                time.Now(),
	}
	err = supply_analysis.CreateVariety(variety, req.AdminIdList)
	if err != nil {
		br.Msg = "添加品种失败"
		br.ErrMsg = "添加品种失败,Err:" + err.Error()
		return
	}

	br.Ret = 200
	br.Msg = "添加成功"
	br.IsAddLog = true
	br.Success = true
}

// Edit
// @Title 编辑品种接口
// @Description 编辑品种接口
// @Param	request	body request.EditVarietyReq true "type json string"
// @Success 200 Ret=200 修改成功
// @router /variety/edit [post]
func (this *VarietyController) Edit() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req request.EditVarietyReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	isSuperAdmin := supply_analysisServ.IsVarietySuperAdmin(this.SysUser)
	if !isSuperAdmin {
		br.Msg = "无操作权限"
		br.IsSendEmail = false
		return
	}
	if req.VarietyId <= 0 {
		br.Msg = "请选择品种"
		br.IsSendEmail = false
		return
	}
	if req.VarietyName == "" {
		br.Msg = "请输入品种名称"
		br.IsSendEmail = false
		return
	}
	varietyName := utils.TrimStr(req.VarietyName)

	item, err := supply_analysis.GetVarietyByName(varietyName)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "添加失败"
		br.ErrMsg = "添加失败，Err:" + err.Error()
		return
	}
	if item != nil && item.VarietyId != req.VarietyId {
		br.Msg = "添加失败，品种名称不能重复"
		br.IsSendEmail = false
		return
	}

	// 获取品种详情
	varietyInfo, err := supply_analysis.GetVarietyById(req.VarietyId)
	if err != nil {
		br.Msg = "查询品种失败"
		br.ErrMsg = "查询品种失败;ERR:" + err.Error()
		return
	}

	// 编辑
	varietyInfo.VarietyName = varietyName
	varietyInfo.LastUpdateSysUserId = this.SysUser.AdminId
	varietyInfo.LastUpdateSysUserRealName = this.SysUser.RealName
	varietyInfo.ModifyTime = time.Now()
	err = supply_analysis.EditVariety(varietyInfo, req.AdminIdList)
	if err != nil {
		br.Msg = "修改品种失败"
		br.ErrMsg = "修改品种失败,Err:" + err.Error()
		return
	}

	br.Ret = 200
	br.Msg = "修改成功"
	br.IsAddLog = true
	br.Success = true
}

// DeleteCheck
// @Title 删除品种检测接口
// @Description 删除品种检测接口
// @Param	request	body request.DelVarietyReq true "type json string"
// @Success 200 Ret=200 检测成功
// @router /variety/delete/check [post]
func (this *VarietyController) DeleteCheck() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req request.DelVarietyReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	if req.VarietyId <= 0 {
		br.Msg = "请选择品种"
		br.IsSendEmail = false
		return
	}
	var deleteStatus int
	var tipsMsg string

	//判断该品种是否生成指标
	count, err := supply_analysis.GetCountVarietyEdbInfoByVarietyId(req.VarietyId)
	if err != nil {
		br.Msg = "删除失败"
		br.ErrMsg = "查询品种下是否含有指标失败，Err:" + err.Error()
		return
	}

	// 是否超管
	isSuperAdmin := supply_analysisServ.IsVarietySuperAdmin(this.SysUser)
	if !isSuperAdmin {
		deleteStatus = 1
		tipsMsg = "无删除权限"
	} else {
		if count > 0 {
			deleteStatus = 1
			tipsMsg = "该品种已在指标库生成指标，不可删除"
		}
	}

	resp := response.VarietyDeleteCheckResp{
		DeleteStatus: deleteStatus,
		TipsMsg:      tipsMsg,
	}
	br.Ret = 200
	br.Msg = "检测成功"
	br.Success = true
	br.Data = resp
}

// Delete
// @Title 删除存量装置图表分类/图表
// @Description 删除存量装置图表分类/图表接口
// @Param	request	body data_manage.DeleteChartClassifyReq true "type json string"
// @Success 200 Ret=200 删除成功
// @router /variety/delete [post]
func (this *VarietyController) Delete() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req request.DelVarietyReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	if req.VarietyId <= 0 {
		br.Msg = "请选择品种"
		br.IsSendEmail = false
		return
	}

	//判断该品种是否生成指标
	count, err := supply_analysis.GetCountVarietyEdbInfoByVarietyId(req.VarietyId)
	if err != nil {
		br.Msg = "删除失败"
		br.ErrMsg = "查询品种下是否含有指标失败，Err:" + err.Error()
		return
	}

	// 是否超管
	isSuperAdmin := supply_analysisServ.IsVarietySuperAdmin(this.SysUser)
	if !isSuperAdmin {
		br.Msg = `无删除权限`
		br.IsSendEmail = false
		return
	}

	if count > 0 {
		br.Msg = `该品种已在指标库生成指标，不可删除`
		br.IsSendEmail = false
		return
	}

	varietyInfo, err := supply_analysis.GetVarietyById(req.VarietyId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "该品种不存在或已删除"
			br.IsSendEmail = false
		} else {
			br.Msg = "删除失败"
			br.ErrMsg = "查找品种失败，ERR：" + err.Error()
		}
		return
	}
	err = varietyInfo.Delete()
	if err != nil {
		br.Msg = "删除失败"
		br.ErrMsg = "查找品种失败，ERR：" + err.Error()
		return
	}

	br.Ret = 200
	br.Msg = "删除成功"
	br.Success = true
	br.IsAddLog = true
}

// Detail
// @Title 存量装置图表分类列表
// @Description 存量装置图表分类列表接口
// @Param   VarietyId   query   int  true       "品种id"
// @Success 200 {object} response.VarietyListResp
// @router /variety/detail [get]
func (this *VarietyController) Detail() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	varietyId, _ := this.GetInt("VarietyId")
	if varietyId < 0 {
		br.Msg = "不存在该品种或该品种已被删除"
		br.ErrMsg = "不存在该品种或该品种已被删除"
		br.IsSendEmail = false
	}

	// 获取品种详情
	varietyInfo, err := supply_analysis.GetVarietyById(varietyId)
	if err != nil {
		br.Msg = "查询品种失败"
		br.ErrMsg = "查询品种失败;ERR:" + err.Error()
		if err.Error() != utils.ErrNoRow() {
			br.Msg = "不存在该品种或该品种已被删除"
			br.ErrMsg = "不存在该品种或该品种已被删除"
			br.IsSendEmail = false
		}
		return
	}
	if varietyInfo == nil {
		br.Msg = "不存在该品种或该品种已被删除"
		br.ErrMsg = "不存在该品种或该品种已被删除"
		br.IsSendEmail = false
		return
	}

	resp := supply_analysis.VarietyItem{
		VarietyId:                 varietyInfo.VarietyId,
		VarietyName:               varietyInfo.VarietyName,
		ProductionDay:             varietyInfo.ProductionDay,
		LastUpdateSysUserId:       varietyInfo.LastUpdateSysUserId,
		LastUpdateSysUserRealName: varietyInfo.LastUpdateSysUserRealName,
		PermissionUserId:          ``,
		ModifyTime:                varietyInfo.ModifyTime.Format(utils.FormatDateTime),
		CreateTime:                varietyInfo.CreateTime.Format(utils.FormatDateTime),
		//Button:                    supply_analysis.VarietyButton{},
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// Analysis
// @Title 品种分析
// @Description 品种分析接口
// @Param	request	body request.AnalysisReq true "type json string"
// @Success 200 Ret=200 检测成功
// @router /variety/analysis [post]
func (this *VarietyController) Analysis() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req request.AnalysisReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	if req.VarietyId <= 0 {
		br.Msg = "请选择品种"
		br.IsSendEmail = false
		return
	}
	//加入缓存机制，避免创建同一时间，多人去分析 start
	redisKey := fmt.Sprint("supply_analysis:variety:", req.VarietyId)
	isExist := utils.Rc.IsExist(redisKey)
	if isExist {
		br.Msg = "品种正在分析中,请等待"
		br.IsSendEmail = false
		return
	} else {
		//设置3分钟缓存
		utils.Rc.SetNX(redisKey, 1, time.Second*300)
		defer func() {
			utils.Rc.Delete(redisKey)
		}()
	}
	//加入缓存机制，避免创建同一时间，多人去分析 end

	// 获取品种详情
	varietyInfo, err := supply_analysis.GetVarietyById(req.VarietyId)
	if err != nil {
		br.Msg = "查询品种失败"
		br.ErrMsg = "查询品种失败;ERR:" + err.Error()
		return
	}

	//判断该品种是否生成指标
	list, err := supply_analysis.GetVarietyEdbListByVarietyId(req.VarietyId)
	if err != nil {
		br.Msg = "分析失败"
		br.ErrMsg = "分析失败，Err:" + err.Error()
		return
	}

	// 如果没有生成过指标，那么就先生成指标
	if len(list) <= 0 {
		//randStr := utils.GetRandDigit(4)
		//prefixCode := "HZ_V"
		//suffixCode := time.Now().Format("060102") + randStr
		//`source` int(9) DEFAULT NULL COMMENT '来源，1：影响周度产量；2：周度产量变动；3：影响月度产量；4：月度产量变动',
		list := []*supply_analysis.VarietyEdbInfo{
			{
				//VarietyEdbId: 0,
				VarietyId: req.VarietyId,
				EdbName:   varietyInfo.VarietyName + "影响周度产量",
				Frequency: "日度",
				EdbInfoId: 0,
				//EdbCode:    fmt.Sprint(prefixCode, 1, suffixCode),
				Source:     1,
				ModifyTime: time.Now(),
				CreateTime: time.Now(),
			},
			{
				//VarietyEdbId: 0,
				VarietyId: req.VarietyId,
				EdbName:   varietyInfo.VarietyName + "周度产量变动",
				Frequency: "日度",
				EdbInfoId: 0,
				//EdbCode:    fmt.Sprint(prefixCode, 2, suffixCode),
				Source:     2,
				ModifyTime: time.Now(),
				CreateTime: time.Now(),
			},
			{
				//VarietyEdbId: 0,
				VarietyId: req.VarietyId,
				EdbName:   varietyInfo.VarietyName + "影响月度产量",
				Frequency: "月度",
				EdbInfoId: 0,
				//EdbCode:    fmt.Sprint(prefixCode, 3, suffixCode),
				Source:     3,
				ModifyTime: time.Now(),
				CreateTime: time.Now(),
			},
			{
				//VarietyEdbId: 0,
				VarietyId: req.VarietyId,
				EdbName:   varietyInfo.VarietyName + "月度产量变动",
				Frequency: "月度",
				EdbInfoId: 0,
				//EdbCode:    fmt.Sprint(prefixCode, 4, suffixCode),
				Source:     4,
				ModifyTime: time.Now(),
				CreateTime: time.Now(),
			},
		}
		err = supply_analysis.BatchCreateVarietyEdbInfo(list)
		if err != nil {
			br.Msg = `分析失败`
			br.ErrMsg = `分析失败，生成指标失败，ERR：` + err.Error()
			return
		}
	}

	tmpMap := map[string]interface{}{
		"VarietyId": req.VarietyId,
		"AdminId":   this.SysUser.AdminId,
		"AdminName": this.SysUser.RealName,
	}
	reqJson, err := json.Marshal(tmpMap)

	// 开始分析
	_, err = supply_analysisServ.Calculate(string(reqJson))
	if err != nil {
		br.Msg = `分析失败`
		br.ErrMsg = `分析失败，ERR：` + err.Error()
		return
	}

	// 更新ETA指标库信息
	{
		if len(list) > 0 {
			for _, v := range list {
				if v.EdbInfoId > 0 {
					edbInfo, err := data_manage.GetEdbInfoById(v.EdbInfoId)
					if err != nil {
						continue
					}
					// 刷新指标数据
					go data.RefreshEdbData(edbInfo.EdbInfoId, edbInfo.Source, edbInfo.SubSource, edbInfo.EdbCode, edbInfo.StartDate)
				}
			}
		}
	}

	// 变更品种的更新时间
	{
		varietyInfo.ModifyTime = time.Now()
		varietyInfo.LastUpdateSysUserId = this.SysUser.AdminId
		varietyInfo.LastUpdateSysUserRealName = this.SysUser.RealName
		go varietyInfo.Update([]string{"ModifyTime", "LastUpdateSysUserId", "LastUpdateSysUserRealName"})
	}

	br.Ret = 200
	br.Msg = "分析成功"
	br.Success = true
}

// ModifyProductionDay
// @Title 编辑品种的生产天数接口
// @Description 编辑品种的生产天数接口
// @Param	request	body request.ModifyProductionDayReq true "type json string"
// @Success 200 Ret=200 修改成功
// @router /variety/production_day/modify [post]
func (this *VarietyController) ModifyProductionDay() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req request.ModifyProductionDayReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	var hasPermission bool //是否有操作权限
	// 是否有装置的操作权限
	hasPermission, err = supply_analysisServ.HasVarietyPlantPermission(this.SysUser, req.VarietyId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取失败"
		br.ErrMsg = "查询是否有装置的操作权限失败;ERR:" + err.Error()
		return
	}
	if !hasPermission {
		br.Msg = "无操作权限"
		br.ErrMsg = "无操作权限"
		return
	}

	if req.VarietyId <= 0 {
		br.Msg = "请选择品种"
		br.IsSendEmail = false
		return
	}
	if req.Day <= 0 {
		br.Msg = "生产天数不能小于等于0"
		br.IsSendEmail = false
		return
	}

	// 获取品种详情
	varietyInfo, err := supply_analysis.GetVarietyById(req.VarietyId)
	if err != nil {
		br.Msg = "查询品种失败"
		br.ErrMsg = "查询品种失败;ERR:" + err.Error()
		return
	}

	// 编辑
	varietyInfo.ProductionDay = req.Day
	varietyInfo.LastUpdateSysUserId = this.SysUser.AdminId
	varietyInfo.LastUpdateSysUserRealName = this.SysUser.RealName
	varietyInfo.ModifyTime = time.Now()
	err = varietyInfo.Update([]string{"ProductionDay", "LastUpdateSysUserId", "LastUpdateSysUserRealName", "ModifyTime"})
	if err != nil {
		br.Msg = "修改生产天数失败"
		br.ErrMsg = "修改生产天数失败,Err:" + err.Error()
		return
	}

	br.Ret = 200
	br.Msg = "修改成功"
	br.IsAddLog = true
	br.Success = true
}
