package business_trip

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

// @Title 出差审批列表
// @Description 出差申请列表接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   Status   query   string  true       "状态"
// @Success 200 {object} business_trip.BusinessApplyListResp
// @router /approve/list [get]
func (this *BusinessTrip) ApproveList() {
	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 total int
	page := paging.GetPaging(currentIndex, pageSize, total)

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

	reason := this.GetString("Reason")
	status := this.GetString("Status")

	var condition string
	var pars []interface{}

	condition += ` AND approve_id=? `
	pars = append(pars, sysUser.AdminId)

	if reason != "" {
		condition += ` AND reason=? `
		pars = append(pars, reason)
	}

	if status != "" {
		condition += ` AND status=? `
		pars = append(pars, status)
	} else {
		condition += ` AND status IN('待审批','已通过','已驳回','已关闭') `
	}

	resp := new(business_trip.BusinessApplyListResp)
	total, err := business_trip.GetBusinessApplyListCount(condition, pars)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取数据总数失败,GetCalendarListCount,Err:" + err.Error()
		return
	}

	dataList, err := business_trip.GetBusinessApplyList(condition, pars, startSize, pageSize)
	if err != nil {
		br.Msg = "获取指标信息失败"
		br.ErrMsg = "获取数据失败,GetBusinessApplyList,Err:" + err.Error()
		return
	}

	nowDate, _ := time.ParseInLocation(utils.FormatDate, time.Now().Format(utils.FormatDate), time.Local)
	for _, v := range dataList {
		arriveDate, _ := time.ParseInLocation(utils.FormatDate, v.ArriveDate, time.Local)
		if v.Status == "已通过" && arriveDate.After(nowDate) {
			v.IsClose = true
		}
	}
	page = paging.GetPaging(currentIndex, pageSize, total)
	resp.Paging = page
	resp.List = dataList
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 出差申请,审批接口
// @Description 出差申请,审批接口
// @Param	request	body business_trip.BusinessApplyApproveReq true "type json string"
// @Success Ret=200 保存成功
// @router /apply/approve [post]
func (this *BusinessTrip) ApplyApprove() {
	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 business_trip.BusinessApplyApproveReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	if req.BusinessApplyId <= 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "参数错误"
		return
	}

	if req.ApproveStatus != 1 && req.ApproveStatus != 2 {
		br.Msg = "审批状态错误"
		return
	}

	if req.ApproveStatus == 2 && req.RefuseReason == "" {
		br.Msg = "请填写驳回理由"
		return
	}

	businessApplyItem, err := business_trip.GetBusinessApplyById(req.BusinessApplyId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "出差申请已被删除，请刷新页面"
			return
		}
		br.Msg = "获取数据失败！"
		br.ErrMsg = "获取数据失败！GetBusinessApplyById:" + err.Error()
		return
	}
	// 审批权限-仅王沛
	if businessApplyItem.ApproveId != sysUser.AdminId {
		br.Msg = "无权审批"
		return
	}

	whereParams := make(map[string]interface{})
	updateParams := make(map[string]interface{})

	whereParams["business_apply_id"] = req.BusinessApplyId

	var status string
	if req.ApproveStatus == 1 {
		status = "已通过"
	} else {
		status = "已驳回"
	}
	updateParams["status"] = status
	updateParams["refuse_reason"] = req.RefuseReason
	updateParams["modify_time"] = time.Now()
	updateParams["approve_time"] = time.Now()

	err = business_trip.UpdateBusinessApply(whereParams, updateParams)

	if err != nil {
		br.Msg = "审批失败！"
		br.ErrMsg = "审批失败！UpdateBusinessApply:" + err.Error()
		return
	}

	{
		//系统消息
		sourceType := 10
		content := businessApplyItem.Province + businessApplyItem.City + businessApplyItem.Reason + "出差申请" + status
		go services.AddCompanyApprovalMessage(sysUser.AdminId, businessApplyItem.ApplyAdminId, 0, businessApplyItem.BusinessApplyId, 1, sourceType, 2, "", content, content, "")

		go company.IsReadCompanyApprovalMessage(businessApplyItem.BusinessApplyId, sourceType)
	}

	//模板消息
	{
		applyItem, _ := system.GetSysUserById(businessApplyItem.ApplyAdminId)

		openIdObj := &system.OpenIdList{
			OpenId:  applyItem.OpenId,
			AdminId: applyItem.AdminId,
		}
		openIdList := make([]*system.OpenIdList, 0)
		openIdList = append(openIdList, openIdObj)

		var remark string
		if status == "已驳回" {
			remark = req.RefuseReason
		}
		var wxAppPath string
		if utils.RunMode == "debug" {
			wxAppPath = "pages/index/index"
		} else {
			wxAppPath = "pages-approve/businessTrip/detail?id=" + strconv.Itoa(req.BusinessApplyId)
		}
		first := "您的出差申请已被审批"
		keyword1 := businessApplyItem.Reason + "出差申请" + status
		keyword2 := status
		if status == `已驳回` {
			keyword2 = status + `（` + req.RefuseReason + `）`
		}

		go services.SendWxMsgWithRoadshowDeleteNotice(first, keyword1, keyword2, remark, wxAppPath, openIdList)
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "审批成功"
	br.IsAddLog = true
}
