package supply_analysis

import (
	"encoding/json"
	"eta/eta_mobile/models"
	"eta/eta_mobile/models/data_manage/request"
	"eta/eta_mobile/models/data_manage/response"
	"eta/eta_mobile/models/data_manage/supply_analysis"
	supply_analysisServ "eta/eta_mobile/services/data/supply_analysis"
	"eta/eta_mobile/utils"
	"fmt"
	"github.com/shopspring/decimal"
	"time"
)

// PlantList
// @Title 装置列表
// @Description 装置列表
// @Param   VarietyId   query   int  true       "品种id"
// @Success 200 {object} response.VarietyListResp
// @router /variety/plant/list [get]
func (this *VarietyController) PlantList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	varietyId, _ := this.GetInt("VarietyId")
	if varietyId <= 0 {
		br.Msg = "请选择品种"
		br.IsSendEmail = false
		return
	}

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

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

	var list []*supply_analysis.VarietyPlantItem
	list, err = supply_analysis.GetAllVarietyPlantByVarietyId(varietyId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}

	for k, v := range list {
		button := supply_analysis.VarietyPlantButton{}
		if hasPermission {
			button.Edit = true
			button.Delete = true
		}

		v.Button = button

		maintenanceDate, tmpErr := time.ParseInLocation(utils.FormatDate, v.MaintenanceDate, time.Local)
		if tmpErr != nil {
			list[k] = v
			continue
		}
		day := 0
		if v.IsStop == 0 {
			resumptionDate, _ := time.ParseInLocation(utils.FormatDate, v.ResumptionDate, time.Local)
			day = utils.GetTimeSubDay(maintenanceDate, resumptionDate)
		} else {
			// 停产的话，就截止到今天
			day = utils.GetTimeSubDay(maintenanceDate, time.Now())
		}

		v.Day = day + 1
		v.CapacityReduction, _ = decimal.NewFromFloat(v.AverageDailyCapacityReduction * float64(v.Day)).Round(4).Float64()

		list[k] = v
	}

	resp := response.VarietyPlantListResp{
		AddButton: hasPermission,
		List:      list,
	}

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

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

	//if req.FactoryName == "" {
	//	br.Msg = "请输入工厂名称"
	//	br.IsSendEmail = false
	//	return
	//}
	factoryName := utils.TrimLRStr(req.FactoryName)
	//if req.PlantName == "" {
	//	br.Msg = "请输入装置/产线名称"
	//	br.IsSendEmail = false
	//	return
	//}
	// 装置名称
	plantName := utils.TrimLRStr(req.PlantName)

	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
	}

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

	// 检修日期 、 复产日期
	var maintenanceDate, resumptionDate time.Time
	if req.MaintenanceDate != `` {
		maintenanceDate, err = time.ParseInLocation(utils.FormatDate, req.MaintenanceDate, time.Local)
		if err != nil {
			br.Msg = "检修日期异常"
			br.ErrMsg = "检修日期异常,maintenanceDate:" + req.MaintenanceDate + ";ERR:" + err.Error()
			br.IsSendEmail = false
			return
		}
	}
	if req.ResumptionDate != `` {
		resumptionDate, err = time.ParseInLocation(utils.FormatDate, req.ResumptionDate, time.Local)
		if err != nil {
			br.Msg = "复产日期异常"
			br.ErrMsg = "复产日期异常,resumptionDate:" + req.ResumptionDate + ";ERR:" + err.Error()
			br.IsSendEmail = false
			return
		}
	}

	// 如果两个日期都填写了，那么就校验下吧
	if !resumptionDate.IsZero() && !maintenanceDate.IsZero() {
		if resumptionDate.Before(maintenanceDate) {
			br.Msg = "复产日期不得早于检修日期"
			br.IsSendEmail = false
			return
		}
	}

	sort := 0
	// 如果是上一个装置id不为空的情况，也就是向下插入（复制）
	if req.PrevVarietyPlantId > 0 {
		prevItem, err := supply_analysis.GetVarietyPlantById(req.PrevVarietyPlantId)
		if err != nil {
			br.Msg = "保存失败"
			br.ErrMsg = fmt.Sprint("查找上一个装置失败,上一个装置id:", req.PrevVarietyPlantId, ";ERR:"+err.Error())
			br.IsSendEmail = false
			return
		}
		sort = prevItem.Sort + 1

		updateSortStr := `sort + 1`
		err = supply_analysis.UpdateEdbInfoSortByPrevId(req.VarietyId, prevItem.VarietyPlantId, prevItem.Sort, updateSortStr)
		if err != nil {
			br.Msg = "保存失败"
			br.ErrMsg = fmt.Sprint("移动下面的其他装置失败;ERR:" + err.Error())
			br.IsSendEmail = false
			return
		}
	} else if req.NextVarietyPlantId > 0 {
		// 下一个装置id不为空的情况，也就是向上插入
		nextItem, err := supply_analysis.GetVarietyPlantById(req.NextVarietyPlantId)
		if err != nil {
			br.Msg = "保存失败"
			br.ErrMsg = fmt.Sprint("查找下一个装置失败,下一个装置id:", req.NextVarietyPlantId, ";ERR:"+err.Error())
			br.IsSendEmail = false
			return
		}
		sort = nextItem.Sort - 1

		updateSortStr := `sort - 1`
		err = supply_analysis.UpdateEdbInfoSortByNextId(req.VarietyId, nextItem.VarietyPlantId, nextItem.Sort, updateSortStr)
		if err != nil {
			br.Msg = "保存失败"
			br.ErrMsg = fmt.Sprint("移动上面的其他装置失败;ERR:" + err.Error())
			br.IsSendEmail = false
			return
		}
	}
	varietyPlant := &supply_analysis.VarietyPlant{
		//VarietyPlantId:                0,
		VarietyId:                     req.VarietyId,
		Province:                      utils.TrimLRStr(req.Province),
		City:                          utils.TrimLRStr(req.City),
		FactoryName:                   factoryName,
		PlantName:                     plantName,
		MaintenanceDate:               maintenanceDate,
		ResumptionDate:                resumptionDate,
		AnnualCapacity:                req.AnnualCapacity,
		Coefficient:                   req.Coefficient,
		AverageDailyCapacityReduction: req.AverageDailyCapacityReduction,
		IsStop:                        req.IsStop,
		Sort:                          sort,
		SysUserId:                     this.SysUser.AdminId,
		SysUserRealName:               this.SysUser.RealName,
		ModifyTime:                    time.Now(),
		CreateTime:                    time.Now(),
	}
	err = supply_analysis.AddVarietyPlant(varietyPlant)
	if err != nil {
		br.Msg = "添加装置失败"
		br.ErrMsg = "添加装置失败,Err:" + err.Error()
		return
	}

	// 变更品种的更新时间
	{
		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.IsAddLog = true
	br.Success = true
}

// EditPlant
// @Title 编辑品种装置接口
// @Description 编辑品种装置接口
// @Param	request	body request.EditVarietyPlantReq true "type json string"
// @Success 200 Ret=200 修改成功
// @router /variety/plant/edit [post]
func (this *VarietyController) EditPlant() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req request.EditVarietyPlantReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	//if req.FactoryName == "" {
	//	br.Msg = "请输入工厂名称"
	//	br.IsSendEmail = false
	//	return
	//}
	factoryName := utils.TrimLRStr(req.FactoryName)
	//if req.PlantName == "" {
	//	br.Msg = "请输入装置/产线名称"
	//	br.IsSendEmail = false
	//	return
	//}
	// 装置名称
	plantName := utils.TrimLRStr(req.PlantName)

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

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

	// 获取品种详情
	varietyInfo, err := supply_analysis.GetVarietyById(varietyPlantInfo.VarietyId)
	if err != nil {
		br.Msg = "查询品种失败"
		br.ErrMsg = "查询品种失败;ERR:" + err.Error()
		return
	}
	if varietyInfo == nil {
		br.Msg = "不存在该品种或该品种已被删除"
		br.ErrMsg = "不存在该品种或该品种已被删除"
		br.IsSendEmail = false
		return
	}
	// 检修日期 、 复产日期
	var maintenanceDate, resumptionDate time.Time
	if req.MaintenanceDate != `` {
		maintenanceDate, err = time.ParseInLocation(utils.FormatDate, req.MaintenanceDate, time.Local)
		if err != nil {
			br.Msg = "检修日期异常"
			br.ErrMsg = "检修日期异常,maintenanceDate:" + req.MaintenanceDate + ";ERR:" + err.Error()
			br.IsSendEmail = false
			return
		}
	}
	if req.ResumptionDate != `` {
		resumptionDate, err = time.ParseInLocation(utils.FormatDate, req.ResumptionDate, time.Local)
		if err != nil {
			br.Msg = "复产日期异常"
			br.ErrMsg = "复产日期异常,resumptionDate:" + req.ResumptionDate + ";ERR:" + err.Error()
			br.IsSendEmail = false
			return
		}
	}

	// 如果两个日期都填写了，那么就校验下吧
	if !resumptionDate.IsZero() && !maintenanceDate.IsZero() {
		if resumptionDate.Before(maintenanceDate) {
			br.Msg = "复产日期不得早于检修日期"
			br.IsSendEmail = false
			return
		}
	}

	// 编辑
	varietyPlantInfo.Province = utils.TrimLRStr(req.Province)
	varietyPlantInfo.City = utils.TrimLRStr(req.City)
	varietyPlantInfo.FactoryName = factoryName
	varietyPlantInfo.PlantName = plantName
	varietyPlantInfo.MaintenanceDate = maintenanceDate
	varietyPlantInfo.ResumptionDate = resumptionDate
	varietyPlantInfo.AnnualCapacity = req.AnnualCapacity
	varietyPlantInfo.Coefficient = req.Coefficient
	varietyPlantInfo.AverageDailyCapacityReduction = req.AverageDailyCapacityReduction
	varietyPlantInfo.IsStop = req.IsStop
	varietyPlantInfo.ModifyTime = time.Now()
	err = varietyPlantInfo.Update([]string{"Province", "City", "FactoryName", "PlantName", "MaintenanceDate", "ResumptionDate", "AnnualCapacity", "Coefficient", "AverageDailyCapacityReduction", "IsStop", "ModifyTime"})
	if err != nil {
		br.Msg = "修改失败"
		br.ErrMsg = "修改失败,Err:" + err.Error()
		return
	}

	// 变更品种的更新时间
	{
		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.IsAddLog = true
	br.Success = true
}

// DeletePlant
// @Title 删除装置
// @Description 删除装置接口
// @Param	request	body request.DeleteVarietyPlantReq true "type json string"
// @Success 200 Ret=200 删除成功
// @router /variety/plant/delete [post]
func (this *VarietyController) DeletePlant() {
	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 request.DeleteVarietyPlantReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	if req.VarietyPlantId <= 0 {
		br.Msg = "请选择装置"
		br.IsSendEmail = false
		return
	}

	varietyPlantInfo, err := supply_analysis.GetVarietyPlantById(req.VarietyPlantId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "删除失败"
		br.ErrMsg = "查找品种装置失败，Err:" + err.Error()
		return
	}
	if varietyPlantInfo == nil {
		br.Msg = "该装置不存在或已删除"
		br.IsSendEmail = false
		return
	}

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

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

	// 保留一条装置校验
	{
		total, err := supply_analysis.GetCountVarietyPlantByVarietyId(varietyInfo.VarietyId)
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "删除失败"
			br.ErrMsg = "查找品种装置总数量失败，Err:" + err.Error()
			return
		}
		if total <= 1 {
			br.Msg = "请保留至少一条装置"
			br.IsSendEmail = false
			return
		}
	}

	// 删除
	err = supply_analysis.DeleteVarietyPlantById(req.VarietyPlantId)
	if err != nil {
		br.Msg = "删除失败"
		br.ErrMsg = "删除装置失败，Err:" + err.Error()
		return
	}

	// 变更品种的更新时间
	{
		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
	br.IsAddLog = true
}

// CopyPlant
// @Title 从其他品种下复制装置
// @Description 从其他品种下复制装置接口
// @Param	request	body request.AddVarietyPlantReq true "type json string"
// @Success 200 Ret=200 添加成功
// @router /variety/plant/copy [post]
func (this *VarietyController) CopyPlant() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req request.CopyVarietyPlantReq
	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
	}

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

	if len(req.VarietyPlantIdList) <= 0 {
		br.Msg = "存量装置不允许必选"
		br.ErrMsg = "存量装置不允许必选"
		br.IsSendEmail = false
		return
	}

	list, err := supply_analysis.GetVarietyPlantByIdList(req.VarietyPlantIdList)
	if err != nil {
		br.Msg = "保存失败"
		br.ErrMsg = fmt.Sprint("查找需要复制的产品装置;ERR:" + err.Error())
		br.IsSendEmail = false
		return
	}

	num := len(list)
	varietyPlantMap := make(map[int]*supply_analysis.VarietyPlant)
	for _, v := range list {
		varietyPlantMap[v.VarietyPlantId] = v
	}

	prevSort := 0
	// 获取上级的品种
	if req.PrevVarietyPlantId > 0 {
		prevItem, err := supply_analysis.GetVarietyPlantById(req.PrevVarietyPlantId)
		if err != nil {
			br.Msg = "保存失败"
			br.ErrMsg = fmt.Sprint("查找上一个装置失败,上一个装置id:", req.PrevVarietyPlantId, ";ERR:"+err.Error())
			br.IsSendEmail = false
			return
		}

		updateSortStr := fmt.Sprintf(`sort + %d `, num)
		err = supply_analysis.UpdateEdbInfoSortByPrevId(req.VarietyId, prevItem.VarietyPlantId, prevItem.Sort, updateSortStr)
		if err != nil {
			br.Msg = "保存失败"
			br.ErrMsg = fmt.Sprint("移动下面的其他装置失败;ERR:" + err.Error())
			br.IsSendEmail = false
			return
		}
		prevSort = prevItem.Sort
	}

	i := 1
	addVarietyPlantList := make([]*supply_analysis.VarietyPlant, 0)
	for _, v := range req.VarietyPlantIdList {
		tmpVarietyPlant, ok := varietyPlantMap[v]
		if !ok {
			continue
		}
		addVarietyPlantList = append(addVarietyPlantList, &supply_analysis.VarietyPlant{
			VarietyId:                     req.VarietyId,
			Province:                      tmpVarietyPlant.Province,
			City:                          tmpVarietyPlant.City,
			FactoryName:                   tmpVarietyPlant.FactoryName,
			PlantName:                     tmpVarietyPlant.PlantName,
			MaintenanceDate:               tmpVarietyPlant.MaintenanceDate,
			ResumptionDate:                tmpVarietyPlant.ResumptionDate,
			AnnualCapacity:                tmpVarietyPlant.AnnualCapacity,
			Coefficient:                   tmpVarietyPlant.Coefficient,
			AverageDailyCapacityReduction: tmpVarietyPlant.AverageDailyCapacityReduction,
			IsStop:                        tmpVarietyPlant.IsStop,
			Sort:                          prevSort + i,
			SysUserId:                     this.SysUser.AdminId,
			SysUserRealName:               this.SysUser.RealName,
			ModifyTime:                    time.Now(),
			CreateTime:                    time.Now(),
		})
		i++
	}
	if len(addVarietyPlantList) > 0 {
		err = supply_analysis.MultiAddVarietyPlant(addVarietyPlantList)
		if err != nil {
			br.Msg = "添加装置失败"
			br.ErrMsg = "添加装置失败,Err:" + err.Error()
			return
		}
	}

	// 变更品种的更新时间
	{
		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.IsAddLog = true
	br.Success = true
}
