package business_trip

import (
	"encoding/json"
	"fmt"
	"github.com/rdlucklib/rdluck_tools/paging"
	"hongze/hz_crm_api/controllers"
	"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"
	"strings"
	"time"
)

// 出差
type BusinessTrip struct {
	controllers.BaseAuthController
}

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

	if req.ArriveDate == "" {
		br.Msg = "请填写到达日期"
		return
	}

	if req.ReturnDate == "" {
		br.Msg = "请填写返程日期"
		return
	}

	if req.Province == "" {
		br.Msg = "请填写目的地省"
		return
	}

	if req.City == "" {
		br.Msg = "请填写目的地市"
		return
	}

	if req.Reason == "" {
		br.Msg = "请填写出差事由"
		return
	}

	if req.Transportation == "" {
		br.Msg = "请填写交通工具"
		return
	}

	startP, _ := time.ParseInLocation(utils.FormatDate, req.ArriveDate, time.Local)
	endP, _ := time.ParseInLocation(utils.FormatDate, req.ReturnDate, time.Local)
	nowDate, _ := time.ParseInLocation(utils.FormatDate, time.Now().Format(utils.FormatDate), time.Local)

	if startP.Before(nowDate) {
		br.Msg = "出差开始日期不能小于当前日期!"
		return
	}

	if !endP.Equal(nowDate) && endP.Before(nowDate) {
		br.Msg = "出差结束时间不能小于当前时间!"
		return
	}

	if !startP.Equal(endP) && (startP.After(endP) || startP.Equal(endP)) {
		br.Msg = "出差开始日期应小于结束日期!"
		return
	}

	//校验出差日期冲突
	{
		businessApplyCount, err := business_trip.CheckBusinessApplyDate(req.ArriveDate, req.ReturnDate, "'待审批','已通过'", sysUser.AdminId, 0)
		if err != nil {
			br.Msg = "时间冲突检测失败！"
			br.ErrMsg = "时间冲突检测失败-CheckBusinessApplyDate！Err:" + err.Error()
			return
		}
		if businessApplyCount > 0 {
			br.Msg = "日期已被占用！"
			br.ErrMsg = "日期已被占用-CheckBusinessApplyDate！"
			br.IsSendEmail = false
			return
		}
	}
	//校验申请人，是否被邀请为同行人，并且出差日期冲突
	{
		peerCount, err := business_trip.CheckBusinessApplyPeerDate(req.ArriveDate, req.ReturnDate, "'待审批','已通过'", sysUser.AdminId, 0)
		if err != nil {
			br.Msg = "时间冲突检测失败！"
			br.ErrMsg = "时间冲突检测失败-CheckBusinessApplyPeerDate！Err:" + err.Error()
			br.IsSendEmail = false
			return
		}
		if peerCount > 0 {
			br.Msg = "所选日期您被设置为同行人，请重新选择！"
			br.ErrMsg = "所选日期您被设置为同行人，请重新选择！"
			br.IsSendEmail = false
			return
		}
	}
	//校验同行人，出差日期冲突
	{
		if req.PeerPeopleId != "" {
			var existPeerNameArr []string

			peerIdArr := strings.Split(req.PeerPeopleId, ",")
			peerNameArr := strings.Split(req.PeerPeopleName, ",")

			for k, v := range peerIdArr {
				peerId, err := strconv.Atoi(v)
				if err != nil {
					br.Msg = "申请失败！"
					br.ErrMsg = "申请失败-同行人id失败！"
					br.IsSendEmail = false
					return
				}

				peerCount, err := business_trip.CheckBusinessApplyPeerDate(req.ArriveDate, req.ReturnDate, "'待审批','已通过'", peerId, 0)
				if err != nil {
					br.Msg = "时间冲突检测失败！"
					br.ErrMsg = "时间冲突检测失败-CheckBusinessApplyPeerDate！Err:" + err.Error()
					br.IsSendEmail = false
					return
				}
				if peerCount > 0 {
					existPeerNameArr = append(existPeerNameArr, peerNameArr[k])
				}
			}

			if len(existPeerNameArr) > 0 {
				br.Msg = strings.Join(existPeerNameArr, ",") + "日期已被占用"
				br.ErrMsg = "日期已被占用-CheckBusinessApplyDate！"
				br.IsSendEmail = false
				return
			}
		}
	}

	approveItem, err := system.GetSysUserById(utils.ApproveUserId)
	if err != nil {
		br.Msg = "获取审批人信息失败！"
		br.ErrMsg = "获取审批人信息失败，Err:" + err.Error()
		return
	}
	item := new(business_trip.BusinessApply)
	item.ApplyAdminId = sysUser.AdminId
	item.ApplyRealName = sysUser.RealName
	item.ArriveDate = req.ArriveDate
	item.ReturnDate = req.ReturnDate
	item.Province = req.Province
	item.City = req.City
	item.Reason = req.Reason
	item.Transportation = req.Transportation
	item.PeerPeopleId = req.PeerPeopleId
	item.PeerPeopleName = req.PeerPeopleName
	item.Status = "待审批"
	item.ApproveId = approveItem.AdminId
	item.ApproveName = approveItem.RealName
	item.CreateTime = time.Now()
	item.ModifyTime = time.Now()
	applyId, err := business_trip.AddBusinessApply(item)
	if err != nil {
		br.Msg = "申请失败"
		br.ErrMsg = "申请失败，Err:" + err.Error()
		return
	}

	//新增随行人
	{
		if req.PeerPeopleId != "" {
			peerList := make([]*business_trip.BusinessApplyPeer, 0)
			peerIdArr := strings.Split(req.PeerPeopleId, ",")
			peerNameArr := strings.Split(req.PeerPeopleName, ",")
			for k, v := range peerIdArr {
				peerId, err := strconv.Atoi(v)
				if err != nil {
					br.Msg = "申请失败"
					br.ErrMsg = "同行人id失败，Err:" + err.Error()
					return
				}
				peerItem := new(business_trip.BusinessApplyPeer)
				peerItem.BusinessApplyId = int(applyId)
				peerItem.ArriveDate = req.ArriveDate
				peerItem.ReturnDate = req.ReturnDate
				peerItem.Province = req.Province
				peerItem.City = req.City
				peerItem.Status = "待审批"
				peerItem.PeerPeopleId = peerId
				peerItem.PeerPeopleName = peerNameArr[k]
				peerItem.CreateTime = time.Now()
				peerItem.ModifyTime = time.Now()
				peerList = append(peerList, peerItem)
			}
			err = business_trip.AddBusinessApplyPeer(peerList)
			if err != nil {
				br.Msg = "申请失败"
				br.ErrMsg = "新增同行人信息失败，Err:" + err.Error()
				return
			}
		}
	}

	{
		//系统消息
		sourceType := 10
		content := sysUser.RealName + " " + req.Province + req.City + req.Reason + "出差申请"
		go services.AddCompanyApprovalMessage(sysUser.AdminId, approveItem.AdminId, 0, int(applyId), 1, sourceType, 1, "", content, content, "")
	}

	//模板消息
	{
		openIdObj := &system.OpenIdList{
			OpenId:  approveItem.OpenId,
			AdminId: approveItem.AdminId,
		}
		openIdList := make([]*system.OpenIdList, 0)
		openIdList = append(openIdList, openIdObj)

		var wxAppPath string
		if utils.RunMode == "debug" {
			wxAppPath = "pages/index/index"
		} else {
			wxAppPath = "pages-approve/businessTrip/detail?id=" + strconv.Itoa(int(applyId))
		}

		first := "您好，有新的申请待处理"
		keyword1 := sysUser.RealName
		keyword2 := "--" //sysUser.Mobile
		//keyword3 := time.Now().Format(utils.FormatDateTime)
		keyword3 := req.ArriveDate + "至" + req.ReturnDate
		var keyword4 string
		if req.PeerPeopleId != "" {
			keyword4 = req.Transportation + "前往" + req.Province + req.City + "," + "同行人：" + req.PeerPeopleName
		} else {
			keyword4 = req.Transportation + "前往" + req.Province + req.City
		}
		remark := "请尽快完成审批"
		go services.SendWxMsgWithRoadshowPending(first, keyword1, keyword2, keyword3, keyword4, remark, wxAppPath, openIdList)
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "保存成功"
	br.IsAddLog = true
}

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

	if req.ArriveDate == "" {
		br.Msg = "请填写到达日期"
		return
	}

	if req.ReturnDate == "" {
		br.Msg = "请填写返程日期"
		return
	}

	if req.Province == "" {
		br.Msg = "请填写目的地省"
		return
	}

	if req.City == "" {
		br.Msg = "请填写目的地市"
		return
	}

	if req.Reason == "" {
		br.Msg = "请填写出差事由"
		return
	}

	if req.Transportation == "" {
		br.Msg = "请填写交通工具"
		return
	}

	startP, _ := time.ParseInLocation(utils.FormatDate, req.ArriveDate, time.Local)
	endP, _ := time.ParseInLocation(utils.FormatDate, req.ReturnDate, time.Local)
	nowDate, _ := time.ParseInLocation(utils.FormatDate, time.Now().Format(utils.FormatDate), time.Local)

	if startP.Before(nowDate) {
		br.Msg = "出差开始日期不能小于当前日期"
		return
	}

	if !endP.Equal(nowDate) && endP.Before(nowDate) {
		br.Msg = "出差结束时间不能小于当前时间！"
		return
	}

	if !startP.Equal(endP) && (startP.After(endP) || startP.Equal(endP)) {
		br.Msg = "出差开始日期应小于结束日期！"
		return
	}

	//校验出差日期冲突
	{
		businessApplyCount, err := business_trip.CheckBusinessApplyDate(req.ArriveDate, req.ReturnDate, "'待审批','已通过'", sysUser.AdminId, req.BusinessApplyId)
		if err != nil {
			br.Msg = "时间冲突检测失败！"
			br.ErrMsg = "时间冲突检测失败-CheckBusinessApplyDate！Err:" + err.Error()
			return
		}
		if businessApplyCount > 0 {
			br.Msg = "日期已被占用！"
			br.ErrMsg = "日期已被占用-CheckBusinessApplyDate！"
			return
		}
	}

	//校验申请人，是否被邀请为同行人，并且出差日期冲突
	{
		peerCount, err := business_trip.CheckBusinessApplyPeerDate(req.ArriveDate, req.ReturnDate, "'待审批','已通过'", sysUser.AdminId, 0)
		if err != nil {
			br.Msg = "时间冲突检测失败！"
			br.ErrMsg = "时间冲突检测失败-CheckBusinessApplyPeerDate！Err:" + err.Error()
			br.IsSendEmail = false
			return
		}
		if peerCount > 0 {
			br.Msg = "所选日期您被设置为同行人，请重新选择！"
			br.ErrMsg = "所选日期您被设置为同行人，请重新选择！"
			br.IsSendEmail = false
			return
		}
	}

	//校验同行人，出差日期冲突
	{
		if req.PeerPeopleId != "" {
			var existPeerNameArr []string

			peerIdArr := strings.Split(req.PeerPeopleId, ",")
			peerNameArr := strings.Split(req.PeerPeopleName, ",")

			for k, v := range peerIdArr {
				peerId, err := strconv.Atoi(v)
				if err != nil {
					br.Msg = "申请失败！"
					br.ErrMsg = "同行人id失败，Err:" + err.Error()
					return
				}

				peerCount, err := business_trip.CheckBusinessApplyPeerDate(req.ArriveDate, req.ReturnDate, "'待审批','已通过'", peerId, req.BusinessApplyId)
				if err != nil {
					br.Msg = "时间冲突校验失败！"
					br.ErrMsg = "时间冲突检测失败-CheckBusinessApplyPeerDate！Err:" + err.Error()
					return
				}
				if peerCount > 0 {
					existPeerNameArr = append(existPeerNameArr, peerNameArr[k])
				}
			}

			if len(existPeerNameArr) > 0 {
				br.Msg = strings.Join(existPeerNameArr, ",") + "日期已被占用"
				br.ErrMsg = "日期已被占用-CheckBusinessApplyDate！"
				return
			}
		}
	}

	if req.BusinessApplyId <= 0 {
		br.Msg = "参数错误！"
		br.ErrMsg = "参数错误！BusinessApplyId:" + strconv.Itoa(req.BusinessApplyId)
		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.Status == "已通过" {
		br.Msg = "已通过，不可进行重新申请操作！"
		return
	} else if businessApplyItem.Status == "已过期" {
		br.Msg = "已过期，不可进行重新申请操作！"
		return
	}

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

	whereParams["business_apply_id"] = req.BusinessApplyId

	updateParams["arrive_date"] = req.ArriveDate
	updateParams["return_date"] = req.ReturnDate
	updateParams["province"] = req.Province
	updateParams["city"] = req.City
	updateParams["reason"] = req.Reason
	updateParams["transportation"] = req.Transportation
	updateParams["peer_people_id"] = req.PeerPeopleId
	updateParams["peer_people_name"] = req.PeerPeopleName
	updateParams["status"] = "待审批"
	updateParams["refuse_reason"] = ""
	updateParams["create_time"] = time.Now()
	updateParams["modify_time"] = time.Now()

	err = business_trip.UpdateBusinessApply(whereParams, updateParams)
	if err != nil {
		br.Msg = "重新申请失败"
		br.ErrMsg = "重新申请失败,Err:" + err.Error()
		return
	}

	//新增随行人
	{
		if req.PeerPeopleId != "" {
			err = business_trip.DeleteBusinessApplyPeer(req.BusinessApplyId)
			if err != nil {
				br.Msg = "重新申请失败"
				br.ErrMsg = "删除同行人失败,Err:" + err.Error()
				return
			}
			peerList := make([]*business_trip.BusinessApplyPeer, 0)
			peerIdArr := strings.Split(req.PeerPeopleId, ",")
			peerNameArr := strings.Split(req.PeerPeopleName, ",")
			for k, v := range peerIdArr {
				peerId, err := strconv.Atoi(v)
				if err != nil {
					br.Msg = "重新申请失败"
					br.ErrMsg = "同行人id失败,Err:" + err.Error()
					return
				}
				peerItem := new(business_trip.BusinessApplyPeer)
				peerItem.BusinessApplyId = req.BusinessApplyId
				peerItem.ArriveDate = req.ArriveDate
				peerItem.ReturnDate = req.ReturnDate
				peerItem.Province = req.Province
				peerItem.City = req.City
				peerItem.Status = "待审批"
				peerItem.PeerPeopleId = peerId
				peerItem.PeerPeopleName = peerNameArr[k]
				peerItem.CreateTime = time.Now()
				peerItem.ModifyTime = time.Now()
				peerList = append(peerList, peerItem)
			}
			err = business_trip.AddBusinessApplyPeer(peerList)
			if err != nil {
				br.Msg = "申请失败"
				br.ErrMsg = "新增同行人信息失败,Err:" + err.Error()
				return
			}
		}
	}

	approveItem, err := system.GetSysUserById(utils.ApproveUserId)
	if err != nil {
		br.Msg = "获取审批人信息失败！"
		br.ErrMsg = "获取审批人信息失败，Err:" + err.Error()
		return
	}
	{
		//系统消息
		sourceType := 10
		content := sysUser.RealName + " " + req.Province + req.City + req.Reason + "出差申请"
		go services.AddCompanyApprovalMessage(sysUser.AdminId, approveItem.AdminId, 0, req.BusinessApplyId, 1, sourceType, 1, "", content, content, "")
	}

	//模板消息
	{
		openIdObj := &system.OpenIdList{
			OpenId:  approveItem.OpenId,
			AdminId: approveItem.AdminId,
		}
		openIdList := make([]*system.OpenIdList, 0)
		openIdList = append(openIdList, openIdObj)

		var wxAppPath string
		if utils.RunMode == "debug" {
			wxAppPath = "pages/index/index"
		} else {
			wxAppPath = "pages-approve/businessTrip/detail?id=" + strconv.Itoa(req.BusinessApplyId)
		}
		first := "您好，有新的申请待处理"
		keyword1 := sysUser.RealName
		keyword2 := "--" //sysUser.Mobile
		//keyword3 := time.Now().Format(utils.FormatDateTime)
		keyword3 := req.ArriveDate + "至" + req.ReturnDate
		var keyword4 string
		if req.PeerPeopleId != "" {
			keyword4 = req.Transportation + "前往" + req.Province + req.City + "," + "同行人：" + req.PeerPeopleName
		} else {
			keyword4 = req.Transportation + "前往" + req.Province + req.City
		}
		remark := "请尽快完成审批"
		services.SendWxMsgWithRoadshowPending(first, keyword1, keyword2, keyword3, keyword4, remark, wxAppPath, openIdList)
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "申请成功"
	br.IsAddLog = true
}

// @Title 出差申请列表
// @Description 出差申请列表接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   Reason   query   string  true       "出差事由"
// @Param   Status   query   string  true       "状态"
// @Success 200 {object} business_trip.BusinessApplyListResp
// @router /apply/list [get]
func (this *BusinessTrip) ApplyList() {
	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 apply_admin_id=? `
	pars = append(pars, sysUser.AdminId)

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

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

	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 {
		if v.ApplyAdminId != sysUser.AdminId {
			continue
		}
		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.BusinessApplyDeleteReq true "type json string"
// @Success Ret=200 删除成功
// @router /apply/delete [post]
func (this *BusinessTrip) Delete() {
	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.BusinessApplyDeleteReq
	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 = "参数错误！BusinessApplyId:" + strconv.Itoa(req.BusinessApplyId)
		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
	}
	err = business_trip.DeleteBusinessApply(businessApplyItem.BusinessApplyId)
	if err != nil {
		br.Msg = "删除失败！"
		br.ErrMsg = "删除失败！DeleteBusinessApply:" + err.Error()
		return
	}
	if businessApplyItem.PeerPeopleId != "" {
		err = business_trip.DeleteBusinessApplyPeer(businessApplyItem.BusinessApplyId)
		if err != nil {
			br.Msg = "删除失败！"
			br.ErrMsg = "删除失败！DeleteBusinessApplyPeer:" + err.Error()
			return
		}
	}
	//删除系统消息
	go company.DeleteCompanyApprovalMessage(req.BusinessApplyId, 10)

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

// @Title 撤回出差申请接口
// @Description 撤回出差申请接口
// @Param	request	body business_trip.BusinessApplyBackReq true "type json string"
// @Success Ret=200 保存成功
// @router /apply/back [post]
func (this *BusinessTrip) Back() {
	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.BusinessApplyBackReq
	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 = "参数错误！BusinessApplyId:" + strconv.Itoa(req.BusinessApplyId)
		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.Status == "已通过" {
		br.Msg = "已通过，不可进行撤回操作！"
		return
	} else if businessApplyItem.Status == "已驳回" {
		br.Msg = "已驳回，不可进行撤回操作！"
		return
	} else if businessApplyItem.Status == "已撤回" {
		br.Msg = "已撤回，不可重复操作！"
		return
	} else if businessApplyItem.Status == "已过期" {
		br.Msg = "已过期，不可进行重复操作！"
		return
	}

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

	whereParams["business_apply_id"] = req.BusinessApplyId

	updateParams["status"] = "已撤回"
	updateParams["modify_time"] = time.Now()

	err = business_trip.UpdateBusinessApply(whereParams, updateParams)

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

	if businessApplyItem.PeerPeopleId != "" {
		peerWhereParams := make(map[string]interface{})
		peerUpdateParams := make(map[string]interface{})

		whereParams["business_apply_id"] = req.BusinessApplyId

		peerUpdateParams["status"] = "已撤回"
		peerUpdateParams["modify_time"] = time.Now()

		err = business_trip.UpdateBusinessApplyPeer(peerWhereParams, peerUpdateParams)

		if err != nil {
			br.Msg = "撤回失败！"
			br.ErrMsg = "撤回失败！UpdateBusinessApplyPeer:" + err.Error()
			return
		}
	}

	//删除系统消息
	go company.DeleteCompanyApprovalMessage(req.BusinessApplyId, 10)

	br.Ret = 200
	br.Success = true
	br.Msg = "撤回成功"
	br.IsAddLog = true
}

// @Title 出差申请详情
// @Description 出差申请详情接口
// @Param   BusinessApplyId   query   int  true       "出差申请id"
// @Success 200 {object} business_trip.BusinessApplyView
// @router /apply/detail [get]
func (this *BusinessTrip) ApplyDetail() {
	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
	}

	businessApplyId, _ := this.GetInt("BusinessApplyId")
	if businessApplyId <= 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "出差申请id错误:" + strconv.Itoa(businessApplyId)
		return
	}

	item, err := business_trip.GetBusinessApplyById(businessApplyId)
	if err != nil {
		br.Msg = "参数错误"
		br.ErrMsg = "出差申请id错误:" + strconv.Itoa(businessApplyId)
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = item
}

// @Title 关闭接口
// @Description 关闭接口
// @Param	request	body business_trip.BusinessApplyCloseReq true "type json string"
// @Success Ret=200 保存成功
// @router /apply/close [post]
func (this *BusinessTrip) Close() {
	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.BusinessApplyCloseReq
	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 = "参数错误！BusinessApplyId:" + strconv.Itoa(req.BusinessApplyId)
		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 sysUser.AdminId != businessApplyItem.ApplyAdminId && sysUser.AdminId != businessApplyItem.ApproveId {
		br.Msg = "无权操作"
		return
	}
	// 判断是申请人还是审批人操作的关闭
	isApply := false
	if sysUser.AdminId == businessApplyItem.ApplyAdminId {
		isApply = true
	}

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

	whereParams["business_apply_id"] = req.BusinessApplyId
	updateParams["status"] = "已关闭"
	updateParams["close_reason"] = req.CloseReason
	updateParams["modify_time"] = time.Now()
	updateParams["close_time"] = time.Now()

	err = business_trip.UpdateBusinessApply(whereParams, updateParams)
	if err != nil {
		br.Msg = "关闭失败！"
		br.ErrMsg = "关闭失败！UpdateBusinessApply:" + err.Error()
		return
	}

	peerWhereParams := make(map[string]interface{})
	peerUpdateParams := make(map[string]interface{})

	peerWhereParams["business_apply_id"] = req.BusinessApplyId

	peerUpdateParams["status"] = "已关闭"
	peerUpdateParams["modify_time"] = time.Now()

	err = business_trip.UpdateBusinessApplyPeer(peerWhereParams, peerUpdateParams)
	if err != nil {
		br.Msg = "关闭失败！"
		br.ErrMsg = "关闭失败！UpdateBusinessApplyPeer:" + err.Error()
		return
	}

	// 审批人关闭时, 发送消息给申请人
	// 若为申请人自己关闭, 则消息发送给审批人
	receiveUserId := businessApplyItem.ApplyAdminId
	if isApply {
		receiveUserId = businessApplyItem.ApproveId
	}
	{
		//系统消息
		sourceType := 10
		content := sysUser.RealName + " " + businessApplyItem.Province + businessApplyItem.City + businessApplyItem.Reason + "出差申请已关闭"
		go services.AddCompanyApprovalMessage(sysUser.AdminId, receiveUserId, 0, businessApplyItem.BusinessApplyId, 1, sourceType, 1, "", content, content, "")
	}

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

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

		var remark string

		var wxAppPath string
		if utils.RunMode == "debug" {
			wxAppPath = "pages/index/index"
		} else {
			wxAppPath = "pages-approve/businessTrip/detail?id=" + strconv.Itoa(req.BusinessApplyId)
		}
		status := "已关闭"
		first := "您的出差申请已被关闭"
		if isApply {
			first = fmt.Sprintf("%s的出差申请已关闭", businessApplyItem.ApplyRealName)
		}
		keyword1 := businessApplyItem.Reason + "出差申请" + status
		keyword2 := status

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

	br.Ret = 200
	br.Success = true
	br.Msg = "关闭成功"
	br.IsAddLog = true
}
