package cygx

import (
	"encoding/json"
	"github.com/rdlucklib/rdluck_tools/paging"
	"github.com/tealeg/xlsx"
	"hongze/hz_crm_api/controllers"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/cygx"
	"hongze/hz_crm_api/models/system"
	cygxService "hongze/hz_crm_api/services/cygx"
	"hongze/hz_crm_api/utils"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"time"
)

// 产品内测
type ProductInteriorController struct {
	controllers.BaseAuthController
}

// @Title 新增
// @Description 新增产品内测接口
// @Param	request	body cygx.AddProductInteriorReq true "type json string"
// @Success 200 {object} "保存成功"
// @router /productInterior/preserveAndPublish [post]
func (this *ProductInteriorController) PreserveAndPublish() {
	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 cygx.AddProductInteriorReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	publishTime := utils.StrDateToDate(req.PublishTime) //时间字符串格式转时间格式
	productInteriorId := req.ProductInteriorId
	columnName := req.ColumnName
	title := req.Title
	abstract := req.Abstract
	department := req.Department
	body := req.Body
	industrialManagementIds := req.IndustrialManagementIds
	industrialSubjectIds := req.IndustrialSubjectIds
	matchTypeId := req.MatchTypeId
	chartPermissionId := req.ChartPermissionId
	// 产业ID校验
	if industrialManagementIds != "" {
		industrialManagementIdList := strings.Split(industrialManagementIds, ",")
		for _, v := range industrialManagementIdList {
			_, err := strconv.Atoi(v)
			if err != nil {
				br.Msg = "参数解析异常！"
				br.ErrMsg = "产业ID不规范，Err:" + err.Error() + industrialManagementIds
				return
			}
		}
	}
	if industrialSubjectIds != "" {
		industrialSubjectIdList := strings.Split(industrialSubjectIds, ",")
		for _, v := range industrialSubjectIdList {
			_, err := strconv.Atoi(v)
			if err != nil {
				br.Msg = "参数解析异常！"
				br.ErrMsg = "标的ID不规范，Err:" + err.Error() + industrialSubjectIds
				return
			}
		}
	}
	charInfo, errCategory := cygx.GetCategoryInfoById(chartPermissionId)
	if errCategory != nil {
		br.Msg = "获取品种信息失败"
		br.ErrMsg = "获取品种信息失败,Err:" + errCategory.Error()
		return
	}

	item := new(cygx.CygxProductInterior)
	item.Status = req.DoType
	item.ColumnName = columnName
	item.Title = title
	item.PublishTime = publishTime
	item.CreateTime = time.Now()
	item.ModifyTime = time.Now()
	item.Body = body
	item.Abstract = abstract
	item.Department = department
	item.AdminId = sysUser.AdminId
	item.MatchTypeId = matchTypeId
	item.ChartPermissionId = chartPermissionId
	item.ChartPermissionName = charInfo.PermissionName

	if req.DoType == 1 {
		item.IsCancel = 0
	}
	if productInteriorId == 0 {
		//新增
		err = cygx.AddProductInterior(item, industrialManagementIds, industrialSubjectIds)
	} else {
		//更新
		detail, err := cygx.GetCygxProductInteriorDetail(productInteriorId)
		if err != nil {
			br.Msg = "详情不存在"
			br.ErrMsg = "获取失败，Err:" + err.Error()
			return
		}
		if req.DoType == 1 {
			item.Status = 1
			item.IsCancel = 0
		} else {
			item.IsCancel = detail.IsCancel
			item.Status = detail.Status
		}
		item.ProductInteriorId = productInteriorId
		item.VisibleRange = detail.VisibleRange
		err = cygx.UpdateProductInterior(item, industrialManagementIds, industrialSubjectIds)
	}
	if err != nil {
		br.Msg = "保存失败"
		br.ErrMsg = "保存失败,Err:" + err.Error()
		return
	}
	go cygxService.UpdateProductInteriorResourceData(productInteriorId) //写入首页最新  cygx_resource_data 表
	br.Ret = 200
	br.Success = true
	br.IsAddLog = true
	br.Msg = "操作成功"
}

// @Title 列表
// @Description 列表接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   Status   query   int  false       "发布状态 ，0未发布，1已发布，传2查询所有"
// @Param   StartDate   query   string  false       "开始时间 ，列如2021-03-06 "
// @Param   EndDate   query   string  false       "结束时间，列如2021-03-06 "
// @Success Ret=200 {object} cygx.GetCygxTacticsTimeLineResp
// @router /productInterior/list [get]
func (this *ProductInteriorController) List() {
	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
	}
	resp := new(cygx.GetCygxProductInteriorResp)
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	status, _ := this.GetInt("Status")
	startDate := this.GetString("StartDate")
	endDate := this.GetString("EndDate")
	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 status == 0 || status == 1 {
		condition += ` AND art.status = ? `
		pars = append(pars, status)
	}
	if startDate != "" && endDate != "" {
		condition += ` 	AND art.publish_time  BETWEEN ?   AND  ? `
		pars = append(pars, startDate, endDate)
	}
	total, err := cygx.GetCygxProductInteriorCount(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	condition += "	ORDER BY art.publish_time DESC , art.product_interior_id DESC "
	list, err := cygx.GetCygxProductInteriorList(condition, pars, startSize, pageSize)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	var productInteriorIds []int
	for _, v := range list {
		v.PublishTime = utils.TimeRemoveHms(v.PublishTime)
		if v.IsCancel == 1 {
			v.Status = 3
		}
		productInteriorIds = append(productInteriorIds, v.ProductInteriorId)
	}

	//获取pv/Uv map
	mapPv, mapUv := cygxService.GetCygxProductInteriorHistoryListMap(productInteriorIds)
	//mapMsg := cygxService.GetCygxProductInteriorMsgListMap(productInteriorIds) // 留言数据
	mapLabel := cygxService.GetCygxProductInteriorLabelListMap(productInteriorIds) // 标签
	mapMatchTypeName := cygxService.GetCygxReportMappingCygxListMap()              //报告匹配类型
	for _, v := range list {
		v.Pv = mapPv[v.ProductInteriorId]
		v.Uv = mapUv[v.ProductInteriorId]
		v.Label = mapLabel[v.ProductInteriorId]
		v.MatchTypeName = mapMatchTypeName[v.MatchTypeId]
	}
	page := paging.GetPaging(currentIndex, pageSize, total)
	resp.List = list
	resp.Paging = page
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title  详情
// @Description 获取详情接口
// @Param   ProductInteriorId   query   int  true       "ID"
// @Success Ret=200 {object} cygx.GetCygxProductInteriorDetailResp
// @router /productInterior/detail [get]
func (this *ProductInteriorController) Detail() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	AdminUser := this.SysUser
	if AdminUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，用户信息为空"
		br.Ret = 408
		return
	}
	resp := new(cygx.GetCygxProductInteriorDetailResp)
	productInteriorId, _ := this.GetInt("ProductInteriorId")
	if productInteriorId < 1 {
		br.Msg = "请输入详情ID"
		return
	}
	detail, err := cygx.GetCygxProductInteriorDetail(productInteriorId)
	if err != nil {
		br.Msg = "详情不存在"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	detail.PublishTime = utils.TimeRemoveHms2(detail.PublishTime)

	industrialList, err := cygx.GetProductInteriorIndustrialGroupManagementList(productInteriorId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取信息失败"
		br.ErrMsg = "GetProductInteriorIndustrialGroupManagementList，Err:" + err.Error() + "productInteriorId：" + strconv.Itoa(productInteriorId)
		return
	}
	subjectList, err := cygx.GetProductInteriorIndustrialGroupSubjecttList(productInteriorId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取信息失败"
		br.ErrMsg = "GetProductInteriorIndustrialGroupSubjecttList，Err:" + err.Error() + "productInteriorId：" + strconv.Itoa(productInteriorId)
		return
	}
	if detail.MatchTypeId > 0 {
		matchDetail, err := cygx.GetCygxReportMappingCygxDetail(detail.MatchTypeId)
		if err != nil {
			br.Msg = "获取信息失败"
			br.ErrMsg = "GetCygxReportMappingCygxDetail，Err:" + err.Error()
			return
		}
		if matchDetail != nil {
			detail.MatchTypeName = matchDetail.MatchTypeName
		}
	}

	detail.ListIndustrial = industrialList
	detail.ListSubject = subjectList
	resp.Detail = detail

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

// @Title  删除
// @Description 获取详情接口
// @Param	request	body cygx.TacticsTimeLineTimeLineIdReq true "type json string"
// @Success 200 {object} "操作成功"
// @router /productInterior/delete [POST]
func (this *ProductInteriorController) Delete() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	AdminUser := this.SysUser
	if AdminUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，用户信息为空"
		br.Ret = 408
		return
	}
	var req cygx.ProductInteriorIdReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	productInteriorId := req.ProductInteriorId
	if productInteriorId == 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "参数错误，id不可为空"
		return
	}
	err = cygx.DeleteProductInterior(productInteriorId)
	if err != nil {
		br.Msg = "详情不存在"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.IsAddLog = true
	br.Msg = "删除成功"
}

// @Title 发布/取消发布报告
// @Description 发布/取消发布报告接口
// @Param	request	body cygx.ProductInteriorIdReq true "type json string"
// @Success 200 Ret=200 发布成功
// @router /productInterior/publishAndcancel [post]
func (this *ProductInteriorController) PublishReport() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req cygx.ProductInteriorIdReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	productInteriorId := req.ProductInteriorId
	if productInteriorId == 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "参数错误，id不可为空"
		return
	}
	detail, err := cygx.GetCygxProductInteriorDetail(productInteriorId)
	if err != nil {
		br.Msg = "详情不存在"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	var status int
	var isCancel int
	if detail.Status == 0 {
		status = 1
		isCancel = 0
	} else {
		status = 0
		isCancel = 1
		//go cygxService.UpdateResourceData(productInteriorId, "productinterior", "delete", time.Now().Format(utils.FormatDateTime))
		go cygxService.UpdateProductInteriorResourceData(productInteriorId) //写入首页最新  cygx_resource_data 表
	}
	err = cygx.EditProductInteriorStatus(status, isCancel, productInteriorId)
	if err != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}

// @Title 可见范围修改
// @Description   可见范围修改接口
// @Param	request	body cygx.ProductInteriorIdReq true "type json string"
// @Success 200 操作成功
// @router /productInterior/visibleRange [post]
func (this *ProductInteriorController) VisibleRange() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	AdminUser := this.SysUser
	if AdminUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，用户信息为空"
		br.Ret = 408
		return
	}
	var req cygx.ProductInteriorIdReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	productInteriorId := req.ProductInteriorId
	detail, err := cygx.GetCygxProductInteriorDetail(productInteriorId)
	if err != nil {
		br.Msg = "详情不存在"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	var visibleRange int
	if detail.VisibleRange == 0 {
		visibleRange = 1
		//go cygxService.UpdateResourceData(productInteriorId, "productinterior", "add", time.Now().Format(utils.FormatDateTime))
		go cygxService.SendWxMsgWithCygxProductInterior(productInteriorId)
	} else {
		visibleRange = 0
		//go cygxService.UpdateResourceData(productInteriorId, "productinterior", "delete", time.Now().Format(utils.FormatDateTime))
	}

	err = cygx.ProductInteriorVisibleRange(visibleRange, productInteriorId)
	if err != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "操作失败,Err:" + err.Error()
		return
	}
	go cygxService.UpdateProductInteriorResourceData(productInteriorId) //写入首页最新  cygx_resource_data 表
	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
	br.IsAddLog = true
}

// @Title  下载PV
// @Description 下载PV接口
// @Param   ProductInteriorId   query   int  true       "ID"
// @router /productInterior/PvExport [get]
func (this *ProductInteriorController) PvExport() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	AdminUser := this.SysUser
	if AdminUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，用户信息为空"
		br.Ret = 408
		return
	}
	productInteriorId, _ := this.GetInt("ProductInteriorId")
	if productInteriorId < 1 {
		br.Msg = "请输入详情ID"
		return
	}
	var condition string
	var pars []interface{}
	condition = ` AND product_interior_id = ? `
	pars = append(pars, productInteriorId)
	var respList []*cygx.CygxProductInteriorHistory

	list, err := cygx.GetCygxProductInteriorHistoryList(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}
	//超级管理员和权益管理员、权益研究员可以下载所有客户，销售组长能下载本组客户，销售只能下载本人名下客户
	resp := new(cygx.CanDownload)
	adminInfo, errAdmin := system.GetSysUserById(AdminUser.AdminId)
	if errAdmin != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + errAdmin.Error()
		return
	}
	if adminInfo.Role == "admin" || adminInfo.Role == "researcher" {
		resp.IsCanDownload = true
	}
	//销售查看自己客户，销售组长查看组员
	if resp.IsCanDownload == false {
		mapMobile, err := cygxService.GetAdminLookUserMobile(adminInfo)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败,销售对应权限，Err:" + err.Error()
			return
		}
		for _, v := range list {
			if _, ok := mapMobile[v.Mobile]; ok {
				respList = append(respList, v)
			}
		}
	} else {
		respList = list
	}

	//创建excel
	dir, err := os.Executable()
	exPath := filepath.Dir(dir)
	downLoadnFilePath := exPath + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
	xlsxFile := xlsx.NewFile()
	if err != nil {
		br.Msg = "生成文件失败"
		br.ErrMsg = "生成文件失败"
		return
	}
	style := xlsx.NewStyle()
	alignment := xlsx.Alignment{
		Horizontal: "center",
		Vertical:   "center",
		WrapText:   true,
	}
	style.Alignment = alignment
	style.ApplyAlignment = true
	sheet, err := xlsxFile.AddSheet("阅读明细")
	if err != nil {
		br.Msg = "新增Sheet失败"
		br.ErrMsg = "新增Sheet失败,Err:" + err.Error()
		return
	}
	rowTitle := sheet.AddRow()
	cellA := rowTitle.AddCell()
	cellA.Value = "姓名"
	cellB := rowTitle.AddCell()
	cellB.Value = "手机号"
	cellC := rowTitle.AddCell()
	cellC.Value = "公司名称"
	cellD := rowTitle.AddCell()
	cellD.Value = "所属权益销售"
	cellE := rowTitle.AddCell()
	cellE.Value = "阅读时间"

	for _, item := range respList {
		row := sheet.AddRow()
		cellA := row.AddCell()
		cellA.Value = item.RealName
		cellB := row.AddCell()
		cellB.Value = item.Mobile
		cellC := row.AddCell()
		cellC.Value = item.CompanyName
		cellD := row.AddCell()
		cellD.Value = item.SellerName
		cellE := row.AddCell()
		cellE.Value = item.CreateTime.Format(utils.FormatDateTime)
	}
	err = xlsxFile.Save(downLoadnFilePath)
	if err != nil {
		br.Msg = "保存文件失败"
		br.ErrMsg = "保存文件失败"
		return
	}
	downloadFileName := time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
	this.Ctx.Output.Download(downLoadnFilePath, downloadFileName)
	defer func() {
		os.Remove(downLoadnFilePath)
	}()
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
}
