package english_report

import (
	"encoding/json"
	"github.com/rdlucklib/rdluck_tools/paging"
	"hongze/hz_crm_api/controllers"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/system"
	"hongze/hz_crm_api/services"
	"hongze/hz_crm_api/utils"
	"html"
	"time"
)

// EnglishCompanyTodoController 英文客户-TODO任务
type EnglishCompanyTodoController struct {
	controllers.BaseAuthController
}

// List
// @Title 任务列表
// @Description 任务列表
// @Param   CompanyId	query	int  true	"客户ID"
// @Param   SortType	query	int  false	"创建时间排序：1-降序; 2-升序"
// @Success 200 {object} []models.EnglishCompanyTodoListItem
// @router /company_todo/list [get]
func (this *EnglishCompanyTodoController) 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
	}

	companyId, _ := this.GetInt("CompanyId")
	if companyId <= 0 {
		br.Msg = "请选择客户"
		return
	}
	authList := services.GetEnglishCompanyTodoAuthRole()
	if !utils.InArrayByStr(authList, sysUser.RoleTypeCode) {
		br.Msg = "账号角色异常，不允许查看任务"
		return
	}

	var startSize int
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = paging.StartIndex(currentIndex, pageSize)

	var order string
	sortType, _ := this.GetInt("SortType", 0)
	if sortType == 2 {
		order = ` ORDER BY a.create_time ASC `
	}

	// 获取任务列表
	total, todoList, err := models.GetEnglishCompanyTodoList(companyId, startSize, pageSize, order)
	if err != nil {
		br.Msg = "获取任务列表失败"
		br.ErrMsg = "获取英文客户任务列表失败,err:" + err.Error()
		return
	}

	list := make([]*models.EnglishCompanyTodoResp, 0)
	for _, v := range todoList {
		td := &models.EnglishCompanyTodoResp{
			Id:              v.Id,
			CompanyId:       v.CompanyId,
			Content:         v.Content,
			SellerId:        v.SellerId,
			SellerName:      v.SellerName,
			CreateUserId:    v.CreateUserId,
			CreateUserName:  v.CreateUserName,
			ApproveUserId:   v.ApproveUserId,
			ApproveUserName: v.ApproveUserName,
			Status:          v.Status,
			CreateTime:      v.CreateTime.Format(utils.FormatDateTime),
			EndTime:         v.EndTime.Format(utils.FormatDateTime),
			ApproveTime:     v.ApproveTime.Format(utils.FormatDateTime),
			EndTimeStr:      v.EndTime.Format(utils.FormatDate),
			Remark:          v.Remark,
		}
		if td.EndTimeStr == "0001-01-01" {
			td.EndTimeStr = ""
		}
		if td.ApproveTime == "0001-01-01 00:00:00" {
			td.ApproveTime = ""
		}
		list = append(list, td)
	}

	page := paging.GetPaging(currentIndex, pageSize, total)
	resp := &models.GetEnglishCompanyTodoPageListResp{
		Paging: page,
		List:   list,
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// Add
// @Title 新增任务
// @Description 新增任务接口
// @Param	request  body  models.EnglishCompanyTodoAddReq  true  "type json string"
// @Success 200 操作成功
// @router /company_todo/add [post]
func (this *EnglishCompanyTodoController) Add() {
	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 models.EnglishCompanyTodoAddReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.CompanyId <= 0 {
		br.Msg = "请选择客户"
		br.ErrMsg = "客户ID不能为空"
		return
	}
	if req.Description == "" {
		br.Msg = "任务描述不能为空"
		return
	}
	if req.EndTime == "" {
		br.Msg = "请选择截止日期"
		return
	}
	endTime, e := time.ParseInLocation(utils.FormatDate, req.EndTime, time.Local)
	if e != nil {
		br.Msg = "截止日期格式错误"
		return
	}
	description := utils.TrimStr(req.Description)

	// 客户、销售信息
	companyId := req.CompanyId
	companyInfo, e := models.GetEnglishCompanyById(companyId)
	if e != nil {
		br.Msg = "保存失败"
		br.ErrMsg = "获取英文客户失败, Err: " + e.Error()
		return
	}
	sellerInfo, e := system.GetSysUserById(companyInfo.SellerId)
	if e != nil {
		br.Msg = "保存失败"
		br.ErrMsg = "获取英文客户销售信息失败, Err: " + e.Error()
		return
	}

	// 校验操作权限
	ok, msg, e := services.CheckEnglishCompanyTodoAuth(sysUser, sellerInfo)
	if e != nil {
		br.Msg = "保存失败"
		br.ErrMsg = "校验英文客户TODO操作权限失败, Err: " + e.Error()
		return
	}
	if !ok {
		br.Msg = msg
		return
	}

	// 获取处理中的任务数
	ingCount, e := models.GetCountDoingEnglishCompanyTodo(companyId)
	if e != nil {
		br.Msg = "保存失败"
		br.ErrMsg = "获取处理中的任务数失败, Err: " + e.Error()
		return
	}
	if ingCount > 0 {
		br.Msg = "当前存在待处理的任务，不允许添加新的任务待办"
		return
	}

	// 新增任务
	nowTime := time.Now().Local()
	newTodo := &models.EnglishCompanyTodo{
		CompanyId:      companyId,
		Content:        description,
		SellerId:       companyInfo.SellerId,
		SellerName:     companyInfo.SellerName,
		CreateUserId:   sysUser.AdminId,
		CreateUserName: sysUser.RealName,
		Status:         models.EnglishCompanyTodoStatusDoing,
		CreateTime:     nowTime,
		ModifyTime:     nowTime,
		EndTime:        endTime,
	}
	if e = newTodo.Create(); e != nil {
		br.Msg = "保存失败"
		br.ErrMsg = "新增英文客户TODO待办失败, Err: " + e.Error()
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}

// Edit
// @Title 编辑任务
// @Description  编辑任务
// @Param	request  body  models.EnglishCompanyTodoEditReq  true  "type json string"
// @Success 200 操作成功
// @router /company_todo/edit [post]
func (this *EnglishCompanyTodoController) Edit() {
	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 models.EnglishCompanyTodoEditReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.Id <= 0 {
		br.Msg = "请选择待办任务"
		br.ErrMsg = "待办任务ID不能为空"
		return
	}
	if req.Description == "" {
		br.Msg = "任务描述不能为空"
		return
	}
	if req.EndTime == "" {
		br.Msg = "请输入截止日期"
		return
	}
	endTime, err := time.ParseInLocation(utils.FormatDate, req.EndTime, time.Local)
	if err != nil {
		br.Msg = "截止日期格式错误"
		return
	}

	description := utils.TrimStr(req.Description)

	// 客户、销售信息
	companyId := req.CompanyId
	companyInfo, e := models.GetEnglishCompanyById(companyId)
	if e != nil {
		br.Msg = "保存失败"
		br.ErrMsg = "获取英文客户失败, Err: " + e.Error()
		return
	}
	sellerInfo, e := system.GetSysUserById(companyInfo.SellerId)
	if e != nil {
		br.Msg = "保存失败"
		br.ErrMsg = "获取英文客户销售信息失败, Err: " + e.Error()
		return
	}

	// 校验操作权限
	ok, msg, e := services.CheckEnglishCompanyTodoAuth(sysUser, sellerInfo)
	if e != nil {
		br.Msg = "保存失败"
		br.ErrMsg = "校验英文客户TODO操作权限失败, Err: " + e.Error()
		return
	}
	if !ok {
		br.Msg = msg
		return
	}

	// 校验任务状态
	todoInfo, e := models.GetEnglishCompanyTodoById(req.Id)
	if e != nil {
		br.Msg = "保存失败"
		br.ErrMsg = "获取英文客户TODO信息失败, Err: " + e.Error()
		return
	}
	if todoInfo.Status != models.EnglishCompanyTodoStatusDoing {
		br.Msg = `任务状态异常: ` + todoInfo.Status + `, 不允许编辑该任务待办`
		return
	}

	// 编辑任务
	todoInfo.Content = description
	todoInfo.SellerId = sellerInfo.AdminId
	todoInfo.SellerName = sellerInfo.RealName
	todoInfo.ModifyTime = time.Now()
	todoInfo.EndTime = endTime
	updateCols := []string{"Content", "SellerId", "SellerName", "ModifyTime", "EndTime"}
	if e = todoInfo.Update(updateCols); e != nil {
		br.Msg = "保存失败"
		br.ErrMsg = "编辑英文客户TODO待办失败, Err: " + e.Error()
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}

// Approve
// @Title 审批任务
// @Description 审批任务接口
// @Param	request  body  models.EnglishCompanyTodoApproveReq  true  "type json string"
// @Success 200 操作成功
// @router /company_todo/approve [post]
func (this *EnglishCompanyTodoController) Approve() {
	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 models.EnglishCompanyTodoApproveReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.Id <= 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "参数错误,任务编号必传 "
		return
	}

	// 校验任务状态
	todoInfo, e := models.GetEnglishCompanyTodoById(req.Id)
	if e != nil {
		br.Msg = "审核失败"
		br.ErrMsg = "获取英文客户TODO信息失败, Err: " + e.Error()
		return
	}
	if todoInfo.Status != models.EnglishCompanyTodoStatusDoing {
		br.Msg = `任务状态异常: ` + todoInfo.Status + `, 不允许审核该任务待办`
		return
	}

	// 客户、销售信息
	companyInfo, e := models.GetEnglishCompanyById(todoInfo.CompanyId)
	if e != nil {
		br.Msg = "审核失败"
		br.ErrMsg = "获取英文客户失败, Err: " + e.Error()
		return
	}
	sellerInfo, e := system.GetSysUserById(companyInfo.SellerId)
	if e != nil {
		br.Msg = "审核失败"
		br.ErrMsg = "获取英文客户销售信息失败, Err: " + e.Error()
		return
	}

	switch sysUser.RoleTypeCode {
	case utils.ROLE_TYPE_CODE_ADMIN, utils.ROLE_TYPE_CODE_FICC_ADMIN, utils.ROLE_TYPE_CODE_FICC_DEPARTMENT, utils.ROLE_TYPE_CODE_FICC_RESEARCHR:
		break
	case utils.ROLE_TYPE_CODE_FICC_GROUP:
		same, e := services.CheckAdminIsSameBigGroup(sysUser, sellerInfo)
		if e != nil {
			br.Msg = "审核失败"
			br.ErrMsg = "判断主管与客户所属销售是否属于同一大组失败, Err: " + e.Error()
			return
		}
		if !same {
			br.Msg = "该客户销售不是当前账号所属组员，不允许审批任务"
			return
		}
	case utils.ROLE_TYPE_CODE_FICC_TEAM:
		if sellerInfo.GroupId != sysUser.GroupId {
			br.Msg = "该客户销售不是当前账号所属组员，不允许审批任务"
			return
		}
	default:
		br.Msg = `操作人角色异常, 不允许审批任务: ` + sysUser.RoleName
		return
	}

	todoInfo.Status = "已完成"
	todoInfo.ApproveUserId = sysUser.AdminId
	todoInfo.ApproveUserName = sysUser.RealName
	todoInfo.ModifyTime = time.Now()
	todoInfo.ApproveTime = time.Now()
	todoInfo.ApprovedSellerId = sellerInfo.AdminId
	todoInfo.ApprovedSellerName = sellerInfo.RealName
	todoInfo.Remark = req.Remark
	updateCols := []string{"Status", "ApproveUserId", "ApproveUserName", "ModifyTime", "ApproveTime", "ApprovedSellerId", "ApprovedSellerName", "Remark"}
	if e = todoInfo.Update(updateCols); e != nil {
		br.Msg = "审核失败"
		br.ErrMsg = "更新英文客户TODO任务审核信息失败, Err: " + e.Error()
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}

// EditList
// @Title 进行中任务列表
// @Description 进行中任务列表
// @Param   CompanyId  query  int  true  "客户ID"
// @Success 200 {object} []models.EnglishCompanyTodoListItem
// @router /company_todo/edit_list [get]
func (this *EnglishCompanyTodoController) EditList() {
	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
	}

	companyId, _ := this.GetInt("CompanyId")
	if companyId <= 0 {
		br.Msg = "请选择客户"
		return
	}
	authList := services.GetEnglishCompanyTodoAuthRole()
	if !utils.InArrayByStr(authList, sysUser.RoleTypeCode) {
		br.Msg = "账号角色异常，不允许查看任务"
		return
	}

	// 获取进行中的任务信息
	todoList, e := models.GetDoingEnglishCompanyTodoList(companyId)
	if e != nil {
		br.Msg = "获取任务信息失败"
		br.ErrMsg = "获取任务信息失败,err:" + e.Error()
		return
	}

	list := make([]*models.EnglishCompanyTodoResp, 0)
	for _, v := range todoList {
		td := &models.EnglishCompanyTodoResp{
			Id:              v.Id,
			CompanyId:       v.CompanyId,
			Content:         v.Content,
			SellerId:        v.SellerId,
			SellerName:      v.SellerName,
			CreateUserId:    v.CreateUserId,
			CreateUserName:  v.CreateUserName,
			ApproveUserId:   v.ApproveUserId,
			ApproveUserName: v.ApproveUserName,
			Status:          v.Status,
			CreateTime:      v.CreateTime.Format(utils.FormatDateTime),
			EndTime:         v.EndTime.Format(utils.FormatDateTime),
			ApproveTime:     v.ApproveTime.Format(utils.FormatDateTime),
			EndTimeStr:      v.EndTime.Format(utils.FormatDate),
		}
		if td.EndTimeStr == "0001-01-01" {
			td.EndTimeStr = ""
		}
		if td.ApproveTime == "0001-01-01 00:00:00" {
			td.ApproveTime = ""
		}
		list = append(list, td)
	}

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

// LastPublicTodo
// @Title 获取最新的公共TODO
// @Description 获取最新的公共TODO
// @Success 200 {object} models.GetEnglishCompanyTodoDoingPageListResp
// @router /company_todo/last_public_todo [get]
func (this *EnglishCompanyTodoController) LastPublicTodo() {
	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
	}

	item, e := models.GetLastEnglishCompanyTodoPublic()
	if e != nil && e.Error() != utils.ErrNoRow() {
		br.Msg = "获取失败"
		br.ErrMsg = "获取最新的公共TODO失败, Err: " + e.Error()
		return
	}
	if item != nil {
		resp := &models.EnglishCompanyTodoPublicResp{
			Content:        html.UnescapeString(item.Content),
			CreateUserId:   item.CreateUserId,
			CreateUserName: item.CreateUserName,
			ModifyTime:     item.ModifyTime.Format(utils.FormatDateTime),
			CreateTime:     item.CreateTime.Format(utils.FormatDateTime),
		}
		br.Data = resp
	}

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

// AddPublic
// @Title 新增公共任务
// @Description 新增公共任务接口
// @Param	request  body  models.EnglishCompanyTodoPublicAddReq  true  "type json string"
// @Success 200 操作成功
// @router /company_todo/add_public [post]
func (this *EnglishCompanyTodoController) AddPublic() {
	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 models.EnglishCompanyTodoPublicAddReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	// 新增公共任务
	nowTime := time.Now().Local()
	newTodo := &models.EnglishCompanyTodoPublic{
		Content:        html.EscapeString(req.Description),
		CreateUserId:   sysUser.AdminId,
		CreateUserName: sysUser.RealName,
		CreateTime:     nowTime,
		ModifyTime:     nowTime,
	}
	if e := newTodo.Create(); e != nil {
		br.Msg = "保存失败"
		br.ErrMsg = "新增英文客户公共TODO失败, Err: " + e.Error()
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}

// DoingList
// @Title 未完成的任务列表
// @Description 未完成的任务列表
// @Param   PageSize		query	int  true	"每页数据量"
// @Param   CurrentIndex	query	int  true	"当前页码"
// @Param   SortType		query	int  false	"截止日期排序: 0-默认(截止日期正序); 1-正序; 2-倒序"
// @Success 200 {object} models.GetEnglishCompanyTodoDoingPageListResp
// @router /company_todo/doing_list [get]
func (this *EnglishCompanyTodoController) DoingList() {
	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 startSize int
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = paging.StartIndex(currentIndex, pageSize)

	var order string
	sortType, _ := this.GetInt("SortType", 0)
	if sortType == 2 {
		order = ` ORDER BY a.end_time DESC `
	}

	// 获取任务列表
	total, todoList, err := models.GetEnglishCompanyTodoDoingList(startSize, pageSize, order)
	if err != nil {
		br.Msg = "获取任务列表失败"
		br.ErrMsg = "获取英文客户任务列表失败,err:" + err.Error()
		return
	}

	list := make([]*models.EnglishCompanyTodoDoingResp, 0)
	for _, v := range todoList {
		td := &models.EnglishCompanyTodoDoingResp{
			Id:              v.Id,
			CompanyId:       v.CompanyId,
			CompanyName:     v.CompanyName,
			Content:         v.Content,
			SellerId:        v.SellerId,
			SellerName:      v.SellerName,
			CreateUserId:    v.CreateUserId,
			CreateUserName:  v.CreateUserName,
			ApproveUserId:   v.ApproveUserId,
			ApproveUserName: v.ApproveUserName,
			Status:          v.Status,
			CreateTime:      v.CreateTime.Format(utils.FormatDateTime),
			EndTime:         v.EndTime.Format(utils.FormatDate),
			ApproveTime:     v.ApproveTime.Format(utils.FormatDateTime),
			Remark:          v.Remark,
		}
		if td.EndTime == "0001-01-01" {
			td.EndTime = ""
		}
		if td.ApproveTime == "0001-01-01 00:00:00" {
			td.ApproveTime = ""
		}
		list = append(list, td)
	}

	page := paging.GetPaging(currentIndex, pageSize, total)
	resp := &models.GetEnglishCompanyTodoDoingPageListResp{
		Paging: page,
		List:   list,
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}
