package controllers

import (
	"encoding/json"
	"github.com/rdlucklib/rdluck_tools/paging"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/company"
	"hongze/hz_crm_api/models/contract"
	"hongze/hz_crm_api/services"
	"hongze/hz_crm_api/services/company_apply"
	contractService "hongze/hz_crm_api/services/contract"
	"hongze/hz_crm_api/utils"
	"strconv"
	"strings"
	"time"
)

// 审批管理
type CompanyApprovalController struct {
	BaseAuthController
}

// @Title 审批列表
// @Description 审批列表接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   Status   query   string  true       "状态：'全部','待审批','已审批','驳回','已撤回'"
// @Param   KeyWord   query   string  true       "搜索关键词"
// @Success 200 {object} company.CompanyApprovalListResp
// @router /approval/list_old [get]
func (this *CompanyApprovalController) ApprovalListOld() {
	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
	}
	roleTypeCode := sysUser.RoleTypeCode

	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	status := this.GetString("Status")
	keyWord := this.GetString("KeyWord")

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

	var condition string
	var pars []interface{}

	if status != "" {
		if status == "已审批" {
			condition += ` AND c.approve_status IN('已审批','驳回','已撤回') `
		} else {
			condition += ` AND c.approve_status=? `
			pars = append(pars, status)
		}
	}

	if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_ADMIN || roleTypeCode == utils.ROLE_TYPE_CODE_RAI_ADMIN { //审批
		condition += ` AND c.approve_role_type_code=? `
		pars = append(pars, roleTypeCode)
	} else if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_SELLER || roleTypeCode == utils.ROLE_TYPE_CODE_RAI_SELLER { //销售
		condition += ` AND c.apply_user_id=? `
		pars = append(pars, sysUser.AdminId)
	}

	if keyWord != "" {
		condition += ` AND (a.company_name LIKE '%` + keyWord + `%' OR a.credit_code LIKE '%` + keyWord + `%') `
	}

	total, err := company.GetApprovalCount(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据总数失败，Err:" + err.Error()
		return
	}

	list, err := company.GetApprovalList(condition, pars, startSize, pageSize)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}
	listLen := len(list)
	for i := 0; i < listLen; i++ {
		item := list[i]
		if item.FreezeStartDate != "" && item.FreezeEndDate != "" && item.Status == utils.COMPANY_STATUS_FREEZE {
			freezeEndDate, _ := time.Parse(utils.FormatDate, item.FreezeEndDate)
			if time.Now().Before(freezeEndDate) {
				expireDays := freezeEndDate.Sub(time.Now()).Hours() / 24
				list[i].FreezeExpireDays = int(expireDays)
			}
		}
		if item.StartDate != "" && item.EndDate != "" {
			endDate, _ := time.Parse(utils.FormatDate, item.EndDate)
			if time.Now().Before(endDate) {
				expireDays := endDate.Sub(time.Now()).Hours() / 24
				list[i].ExpireDay = int(expireDays)
			}
		}

		switch item.ApplyMethod {
		case 2:
			//客户冻结转试用次数
			approvalCount, err := company.GetFreezeToTryCompanyApprovalCount(item.CompanyId, item.ProductId, item.ApplyUserId)
			if err != nil && err.Error() != utils.ErrNoRow() {
				br.Msg = "获取失败"
				br.ErrMsg = "获取冻结转试用审批次数失败，Err:" + err.Error()
				return
			}
			list[i].ApprovalCount = approvalCount
		case 3:
			delayPermission, err := company.GetApplyDelayPermission(item.CompanyApprovalId)
			if err != nil && err.Error() != utils.ErrNoRow() {
				br.Msg = "获取失败"
				br.ErrMsg = "获取延期审批权限失败，Err:" + err.Error()
				return
			}
			list[i].DelayPermission = delayPermission

			//客户审批试用延期次数
			approvalCount, err := company.GetCompanyTryDelayApprovalCount(item.CompanyId, item.ProductId)
			if err != nil && err.Error() != utils.ErrNoRow() {
				br.Msg = "获取失败"
				br.ErrMsg = "获取延期审批次数失败，Err:" + err.Error()
				return
			}
			list[i].ApprovalCount = approvalCount
		}
	}

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

// @Title 审批列表
// @Description 审批列表接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   Status   query   string  true       "状态：'全部','待审批','已审批','驳回','已撤回'"
// @Param   KeyWord   query   string  true       "搜索关键词"
// @Success 200 {object} company.CompanyApprovalListResp
// @router /approval/list [get]
func (this *CompanyApprovalController) ApprovalList() {
	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
	}
	roleTypeCode := sysUser.RoleTypeCode

	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	status := this.GetString("Status")
	keyWord := this.GetString("KeyWord")

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

	var condition string
	var pars []interface{}

	if status != "" {
		if status == "已审批" {
			condition += ` AND c.approve_status IN('已审批','驳回','已撤回') `
		} else {
			condition += ` AND c.approve_status=? `
			pars = append(pars, status)
		}
	}

	if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_ADMIN || roleTypeCode == utils.ROLE_TYPE_CODE_RAI_ADMIN { //审批
		condition += ` AND c.approve_role_type_code=? `
		pars = append(pars, roleTypeCode)
	} else if roleTypeCode == utils.ROLE_TYPE_CODE_FICC_SELLER || roleTypeCode == utils.ROLE_TYPE_CODE_RAI_SELLER { //销售
		condition += ` AND c.apply_user_id=? `
		pars = append(pars, sysUser.AdminId)
	}

	if keyWord != "" {
		condition += ` AND (a.company_name LIKE '%` + keyWord + `%' OR a.credit_code LIKE '%` + keyWord + `%') `
	}

	total, err := company.GetApprovalCount(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据总数失败，Err:" + err.Error()
		return
	}

	list, err := company.GetApprovalList(condition, pars, startSize, pageSize)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}
	listLen := len(list)
	if listLen > 0 {
		contractApprovalIdSlice := make([]string, 0)
		for i := 0; i < len(list); i++ {
			contractApprovalIdSlice = append(contractApprovalIdSlice, strconv.Itoa(list[i].CompanyApprovalId))
		}
		contractApprovalIdStr := strings.Join(contractApprovalIdSlice, ",")

		//获取审批流列表数据
		contractApprovalRecordList, err := contract.GetContractApprovalRecordList(contractApprovalIdStr, sysUser.AdminId)
		if err != nil {
			br.Msg = "获取审批流列表失败！"
			br.ErrMsg = "获取审批流列表失败，Err:" + err.Error()
			return
		}
		contractApprovalRecordMap := make(map[int]*contract.ContractApprovalRecord)
		for i := 0; i < len(contractApprovalRecordList); i++ {
			contractApprovalRecordMap[contractApprovalRecordList[i].ContractApprovalId] = contractApprovalRecordList[i]
		}

		for i := 0; i < listLen; i++ {
			item := list[i]
			if item.FreezeStartDate != "" && item.FreezeEndDate != "" && item.Status == utils.COMPANY_STATUS_FREEZE {
				freezeEndDate, _ := time.Parse(utils.FormatDate, item.FreezeEndDate)
				if time.Now().Before(freezeEndDate) {
					expireDays := freezeEndDate.Sub(time.Now()).Hours() / 24
					list[i].FreezeExpireDays = int(expireDays)
				}
			}
			if item.StartDate != "" && item.EndDate != "" {
				endDate, _ := time.Parse(utils.FormatDate, item.EndDate)
				if time.Now().Before(endDate) {
					expireDays := endDate.Sub(time.Now()).Hours() / 24
					list[i].ExpireDay = int(expireDays)
				}
			}

			switch item.ApplyMethod {
			case 2:
				//客户冻结转试用次数
				approvalCount, err := company.GetFreezeToTryCompanyApprovalCount(item.CompanyId, item.ProductId, item.ApplyUserId)
				if err != nil && err.Error() != utils.ErrNoRow() {
					br.Msg = "获取失败"
					br.ErrMsg = "获取冻结转试用审批次数失败，Err:" + err.Error()
					return
				}
				list[i].ApprovalCount = approvalCount
			case 3:
				delayPermission, err := company.GetApplyDelayPermission(item.CompanyApprovalId)
				if err != nil && err.Error() != utils.ErrNoRow() {
					br.Msg = "获取失败"
					br.ErrMsg = "获取延期审批权限失败，Err:" + err.Error()
					return
				}
				list[i].DelayPermission = delayPermission

				//客户审批试用延期次数
				approvalCount, err := company.GetCompanyTryDelayApprovalCount(item.CompanyId, item.ProductId)
				if err != nil && err.Error() != utils.ErrNoRow() {
					br.Msg = "获取失败"
					br.ErrMsg = "获取延期审批次数失败，Err:" + err.Error()
					return
				}
				list[i].ApprovalCount = approvalCount
			}
		}
	}

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

// List
// @Title 审批列表
// @Description 审批列表接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   Status   query   string  true       "状态：'全部','待审批','已审批','驳回','已撤回'"
// @Param   KeyWord   query   string  true       "搜索关键词"
// @Success 200 {object} company.CompanyApprovalListResp
// @router /approval/listV2 [get]
func (this *CompanyApprovalController) 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
	}

	//合同类型、产品类型、合同状态、更新时间、所选销售
	//关键字：合同编号、客户名称，社会信用码
	contractType := this.GetString("ContractType")
	status := this.GetString("Status")
	productId, _ := this.GetInt("ProductId")
	sellerIds := this.GetString("SellerId")
	keyword := this.GetString("KeyWord")
	modifyStartTime := this.GetString("ModifyStartTime")
	modifyEndTime := this.GetString("ModifyEndTime")

	childCondition := ""
	condition := ""
	childPars := make([]interface{}, 0)
	pars := make([]interface{}, 0)
	//如果不是超管或者合规，那么只能查看自己的合同
	if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_RAI_ADMIN { //权益管理员
		condition += ` AND c.product_id = ? `
		pars = append(pars, 2)
	} else if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_FICC_ADMIN { //ficc管理员
		condition += ` AND c.product_id = ? `
		pars = append(pars, 1)
	} else {
		if sysUser.RoleTypeCode != utils.ROLE_TYPE_CODE_COMPLIANCE && sysUser.RoleTypeCode != utils.ROLE_TYPE_CODE_ADMIN {
			condition += ` AND c.apply_user_id = ? `
			pars = append(pars, sysUser.AdminId)
		}
	}

	//合同类型、、更新时间、所选销售
	//关键字：合同编号、客户名称，社会信用码
	if contractType != "" {
		condition += ` AND c.contract_type = ? `
		pars = append(pars, contractType)
	}
	//审批状态
	if status != "" {
		//childCondition += ` AND status = ? `
		//childPars = append(childPars, status)

		if status == "已审批" {
			if services.CheckAdminIsSeller(sysUser.RoleTypeCode) {
				condition += ` AND c.approve_status in ("已审批","驳回","已撤回")  `
			} else {
				condition += ` AND c.approve_status in ("已审批","驳回")  `
			}
		} else {
			condition += ` AND c.approve_status = ? `
			pars = append(pars, status)
		}
	} else {
		//如果不是销售，那么不展示 已撤回 的客户单
		if !services.CheckAdminIsSeller(sysUser.RoleTypeCode) {
			condition += ` AND c.approve_status !="已撤回" `
		}
	}

	//产品类型
	if productId > 0 {
		condition += ` AND c.product_id = ? `
		pars = append(pars, productId)
	}
	//所选销售
	if sellerIds != "" {
		condition += ` AND c.apply_user_id IN (` + sellerIds + `) `
	}
	//更新开始时间

	//更新开始时间
	if modifyStartTime != "" {
		condition += ` AND a.modify_time >= ? `
		pars = append(pars, modifyStartTime)
	}
	//更新结束时间
	if modifyEndTime != "" {
		condition += ` AND a.modify_time <= ? `
		pars = append(pars, modifyEndTime)
	}
	//关键字
	if keyword != "" {
		condition += ` AND ( e.company_name LIKE '%` + keyword + `%' OR e.credit_code LIKE '%` + keyword + `%' ) `
	}

	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")

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

	total, err := contract.GetCompanyApprovalListCount(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据总数失败，Err:" + err.Error()
		return
	}

	list, err := contract.GetCompanyApprovalList(childCondition, condition, childPars, pars, startSize, pageSize)
	if err != nil {
		br.Msg = "获取审批列表失败！"
		br.ErrMsg = "获取审批列表失败，Err:" + err.Error()
		return
	}

	respList := make([]*company.CompanyApprovalList, 0)

	if len(list) > 0 {
		contractApprovalIdSlice := make([]string, 0)
		for i := 0; i < len(list); i++ {
			contractApprovalIdSlice = append(contractApprovalIdSlice, strconv.Itoa(list[i].ContractApprovalId))
		}
		contractApprovalIdStr := strings.Join(contractApprovalIdSlice, ",")

		//获取审批流列表数据
		contractApprovalRecordList, err := contract.GetContractApprovalRecordList(contractApprovalIdStr, sysUser.AdminId)
		if err != nil {
			br.Msg = "获取审批流列表失败！"
			br.ErrMsg = "获取审批流列表失败，Err:" + err.Error()
			return
		}
		contractApprovalRecordMap := make(map[int]*contract.ContractApprovalRecord)
		for i := 0; i < len(contractApprovalRecordList); i++ {
			contractApprovalRecordMap[contractApprovalRecordList[i].ContractApprovalId] = contractApprovalRecordList[i]
		}

		for i := 0; i < len(list); i++ {
			item := list[i]
			list[i].StartDateStr = item.StartDate.Format(utils.FormatDate)
			list[i].EndDateStr = item.EndDate.Format(utils.FormatDate)
			list[i].CreateTimeStr = item.CreateTime.Format(utils.FormatDateTime)
			list[i].ModifyTimeStr = item.ModifyTime.Format(utils.FormatDateTime)
			list[i].ApproveTimeStr = item.ApproveTime.Format(utils.FormatDateTime)

			//合同操作权限
			var opButton company.ApprovalButton

			var contractDetail contract.ContractDetail
			jsonErr := json.Unmarshal([]byte(list[i].ContractDetail), &contractDetail)
			if jsonErr != nil {
				br.Msg = "审批合同数据转换失败！"
				br.ErrMsg = "审批合同数据转换失败，Err:" + jsonErr.Error()
				return
			}
			list[i].ContractInfo = contractDetail
			//校验最新审批流数据
			if contractApprovalRecord, has := contractApprovalRecordMap[item.ContractApprovalId]; has {
				//审批流id
				list[i].ContractApprovalRecordId = contractApprovalRecord.ContractApprovalRecordId
				//审批时间
				list[i].ApproveTime = contractApprovalRecord.ApproveTime
				list[i].ApproveTimeStr = contractApprovalRecord.ApproveTime.Format(utils.FormatDateTime)
				//判断是否有操作权限
				list[i].Status = contractApprovalRecord.Status

				//判断是否处于待审批状态
				if contractApprovalRecord.Status == "待审批" {
					//如果不是审批者，那么不能审批操作
					if contractApprovalRecord.NodeType != "check" {
						continue
					}
					//如果没有指定审批人的话
					if contractApprovalRecord.ApproveUserId <= 0 {
						//判断是否与审批角色一致，如果一致，那么允许操作审批
						if contractApprovalRecord.ApproveRoleTypeCode == sysUser.RoleTypeCode {
							opButton.Approval = true
						}
					} else if contractApprovalRecord.ApproveUserId == sysUser.AdminId {
						//如果指定审批人就是自己的话，那么操作审批
						opButton.Approval = true
					}
				}
			}

			//撤销权限（本人才有，然后没有审核操作过的才允许撤销）
			if item.Status == "待审批" && item.StartNodeId == item.CurrNodeId && item.ApplyUserId == sysUser.AdminId {
				opButton.Cancel = true
			}

			if item.CompanyProductStatus == utils.COMPANY_STATUS_FOREVER {
				item.CompanyProductStatus = utils.COMPANY_STATUS_X_CLASS_TRY_OUT
			}

			respTmp := &company.CompanyApprovalList{
				CompanyId:         item.CompanyId,
				ProductId:         item.ProductId,
				CompanyName:       item.CompanyName,
				CreditCode:        item.CreditCode,
				CompanyType:       item.CompanyType,
				IndustryName:      item.IndustryName,
				SellerName:        item.SellerName,
				CreateTime:        item.CreateTimeStr,
				ApprovalTime:      item.CreateTime.Format(utils.FormatDateTime),
				ApproveTime:       item.ApproveTimeStr,
				Status:            item.CompanyProductStatus,
				ApproveContent:    item.ApplyContent,
				ApproveStatus:     item.ApproveStatus,
				ApplyMethod:       item.ApplyMethod,
				ApplyReasons:      item.ApplyReasons,
				FreezeStartDate:   item.FreezeStartDate,
				FreezeEndDate:     item.FreezeEndDate,
				FreezeExpireDays:  item.FreezeExpireDays,
				Address:           item.Address,
				Source:            item.Source,
				ApproveRemark:     item.ApproveRemark,
				StartDate:         item.StartDate.Format(utils.FormatDate),
				EndDate:           item.EndDate.Format(utils.FormatDate),
				ExpireDay:         item.ExpireDay,
				CompanyApprovalId: item.CompanyApprovalId,
				//ApprovalCount     int            `description:"已延期审批次数"`
				CompanyContractId: item.CompanyContractId,
				//DelayPermission   :
				ApplyRealName: item.ApplyRealName,
				ApplyUserId:   item.ApplyUserId,
				OpButton:      opButton,
			}

			if respTmp.FreezeStartDate != "" && respTmp.FreezeEndDate != "" && respTmp.Status == utils.COMPANY_STATUS_FREEZE {
				freezeEndDate, _ := time.Parse(utils.FormatDate, item.FreezeEndDate)
				if time.Now().Before(freezeEndDate) {
					expireDays := freezeEndDate.Sub(time.Now()).Hours() / 24
					respTmp.FreezeExpireDays = int(expireDays)
				}
			}
			if respTmp.StartDate != "" && respTmp.EndDate != "" {
				endDate, _ := time.Parse(utils.FormatDate, respTmp.EndDate)
				if time.Now().Before(endDate) {
					expireDays := endDate.Sub(time.Now()).Hours() / 24
					list[i].ExpireDay = int(expireDays)
				}
			}

			switch respTmp.ApplyMethod {
			case 2:
				//客户冻结转试用次数
				approvalCount, err := company.GetFreezeToTryCompanyApprovalCount(item.CompanyId, item.ProductId, respTmp.ApplyUserId)
				if err != nil && err.Error() != utils.ErrNoRow() {
					br.Msg = "获取失败"
					br.ErrMsg = "获取客户冻结转试用次数失败，Err:" + err.Error()
					return
				}
				//respTmp.S
				respTmp.ApprovalCount = approvalCount
			case 3:
				delayPermission, err := company.GetApplyDelayPermission(item.CompanyApprovalId)
				if err != nil && err.Error() != utils.ErrNoRow() {
					br.Msg = "获取失败"
					br.ErrMsg = "获取延期审批权限失败，Err:" + err.Error()
					return
				}
				respTmp.DelayPermission = delayPermission

				//客户审批试用延期次数
				approvalCount, err := company.GetCompanyTryDelayApprovalCount(item.CompanyId, item.ProductId)
				if err != nil && err.Error() != utils.ErrNoRow() {
					br.Msg = "获取失败"
					br.ErrMsg = "获取延期审批次数失败，Err:" + err.Error()
					return
				}
				respTmp.ApprovalCount = approvalCount
			}

			//判断是否系统合同
			if respTmp.CompanyContractId > 0 {
				companyContract, err := company.GetCompanyContractById(respTmp.CompanyContractId)
				if err != nil {
					br.Msg = "获取合同失败"
					br.ErrMsg = "获取合同失败，Err:" + err.Error()
					return
				}
				systemContract, err := contract.GetContractByCode(companyContract.ContractCode)
				//如果通过合同编号可以找到系统合同，那么就是标准合同
				if systemContract != nil {
					respTmp.ApplyContractType = 1
				}
			}

			respList = append(respList, respTmp)
		}
	}

	page := paging.GetPaging(currentIndex, pageSize, total)

	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = company.CompanyApprovalListResp{
		List:   respList,
		Paging: page,
	}
}

// @Title 获取审批单中的权限列表
// @Description 获取审批单中的权限列表接口
// @Param   ApprovalId   query   int  true       "审批单id"
// @Success 200 {object} company.CompanyPermissionResp
// @router /approval/getApprovalPermissionList [get]
func (this *CompanyApprovalController) GetApprovalPermissionList() {
	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(company.CompanyPermissionResp)

	//获取审批单信息
	approvalId, _ := this.GetInt("ApprovalId")
	if approvalId <= 0 {
		br.Msg = "审批单参数异常"
		br.ErrMsg = "提交审批单参数异常"
		return
	}
	approvalInfo, err := company.GetCompanyApprovalByApprovalId(approvalId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取审批单数据失败，Err:" + err.Error()
		return
	}

	//子权限切片集合
	var permissionProductId int

	if approvalInfo.ProductId == 1 {
		permissionProductId = 1
	} else {
		permissionProductId = 2
	}
	permissionClassifyArr, err := services.GetPermissionFirstArr(permissionProductId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取权限分类失败，Err:" + err.Error()
		return
	}
	//获取需要审批的权限
	delayPermissionList, err := company.GetDelayPermissionItems(approvalInfo.CompanyId, approvalInfo.CompanyApprovalId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取失败"
		br.ErrMsg = "获取审批权限失败，Err:" + err.Error()
		return
	}

	delayPermissionIdMap := make(map[int]int)
	//sandoPermissionIdMap := make(map[string]int)
	for _, delayPermission := range delayPermissionList {
		delayPermissionIdMap[delayPermission.ChartPermissionId] = 0
	}

	//遍历获取
	for _, v := range permissionClassifyArr {
		checkList := make([]int, 0)
		plist := new(company.PermissionLookList)
		plist.Items = make([]*company.PermissionLookItem, 0)
		items, err := company.GetPermissionLookItemsByParentId(approvalInfo.ProductId, v.ChartPermissionId)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取权限信息失败，Err:" + err.Error()
			return
		}
		if len(items) > 0 {
			//权益客户下，主观客观同时选择，进行合并
			for _, n := range items {
				if _, ok := delayPermissionIdMap[n.ChartPermissionId]; ok {
					//if approvalInfo.ProductId == 2 {
					//	if sandoPermissionIdMap[n.PermissionName] == 0 {
					//		checkList = append(checkList, n.ChartPermissionId)
					//	}
					//	sandoPermissionIdMap[n.PermissionName] += 1
					//} else {
					//	checkList = append(checkList, n.ChartPermissionId)
					//}
					checkList = append(checkList, n.ChartPermissionId)
				}
			}
			plist.Items = items
		}

		//if approvalInfo.ProductId == 2 {
		//	for i, n := range items {
		//		if sandoPermissionIdMap[n.PermissionName] == 1 {
		//			items[i].PermissionName = n.Remark
		//		}
		//	}
		//}
		plist.ClassifyName = v.PermissionName
		plist.CheckList = checkList
		if approvalInfo.ProductId == 1 {
			resp.FiccPermissionList = append(resp.FiccPermissionList, plist)
		} else {
			rp := make([]*company.PermissionLookList, 0)
			rp = append(rp, plist)
			// CRM8.8-权限主客观合并
			newPermissionLookList := contractService.HandleEquityPermissionLookList(rp)
			resp.PermissionList = newPermissionLookList
		}

	}

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

// @Title 审批
// @Description 审批接口
// @Param	request	body company.CompanyApplyApproveReq true "type json string"
// @Success Ret=200 审批成功
// @router /approval/approve [post]
func (this *CompanyApprovalController) 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 company.CompanyApplyApproveReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	roleTypeCode := sysUser.RoleTypeCode
	//productId := services.GetProductId(roleTypeCode)
	productId := req.ProductId
	if productId == 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "客户类型为：" + roleTypeCode
		return
	}
	if req.CompanyId <= 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "客户Id小于等于0："
		return
	}
	if req.Status != 1 && req.Status != 2 {
		br.Msg = "参数错误"
		br.ErrMsg = "审批状态Id小于等于0："
		return
	}
	companyProduct, err := company.GetCompanyProductByCompanyIdAndProductId(req.CompanyId, productId)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取信息失败,Err:" + err.Error()
		return
	}
	if companyProduct == nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取审批信息失败,Err:companyProduct为空"
		return
	}
	//数据校验（校验是否具有审批权限）
	_, _, approvalRecord, err := company_apply.CheckApproveAuth(req.CompanyId, productId, sysUser)
	if err != nil {
		br.Msg = "审批失败"
		br.ErrMsg = "审批失败,Err:" + err.Error()
		return
	}
	//真实审核操作
	if req.Status == 1 {
		err = company_apply.Approved(approvalRecord, sysUser, req.Remark)
		if err != nil {
			br.Msg = "审核失败！"
			br.ErrMsg = "审核失败，Err:" + err.Error()
			return
		}
	} else {
		err = company_apply.Reject(approvalRecord, sysUser, req.Remark)
		if err != nil {
			br.Msg = "审核失败！"
			br.ErrMsg = "审核失败，Err:" + err.Error()
			return
		}
	}

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

//func (this *CompanyApprovalController) ApplyApproveOld() {
//	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 company.CompanyApplyApproveReq
//	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
//	if err != nil {
//		br.Msg = "参数解析异常！"
//		br.ErrMsg = "参数解析失败，Err:" + err.Error()
//		return
//	}
//	roleTypeCode := sysUser.RoleTypeCode
//	productId := services.GetProductId(roleTypeCode)
//	if productId == 0 {
//		br.Msg = "参数错误"
//		br.ErrMsg = "客户类型为：" + roleTypeCode
//		return
//	}
//	if req.CompanyId <= 0 {
//		br.Msg = "参数错误"
//		br.ErrMsg = "客户Id小于等于0："
//		return
//	}
//	if req.Status != 1 && req.Status != 2 {
//		br.Msg = "参数错误"
//		br.ErrMsg = "审批状态Id小于等于0："
//		return
//	}
//	companyProduct, err := company.GetCompanyProductByCompanyIdAndProductId(req.CompanyId, productId)
//	if err != nil {
//		br.Msg = "获取信息失败"
//		br.ErrMsg = "获取信息失败,Err:" + err.Error()
//		return
//	}
//	if companyProduct == nil {
//		br.Msg = "获取信息失败"
//		br.ErrMsg = "获取审批信息失败,Err:companyProduct 为空"
//		return
//	}
//
//	approvalItem, err := company.GetCompanyApprovalById(req.CompanyId, productId)
//	if err != nil {
//		if err.Error() == utils.ErrNoRow() {
//			br.Msg = "订单已审批，请刷新页面查看最新状态"
//			br.ErrMsg = "待审批信息不存在,CompanyId:" + strconv.Itoa(req.CompanyId) + ";productId:" + strconv.Itoa(productId)
//			return
//		}
//		br.Msg = "获取信息失败"
//		br.ErrMsg = "获取信息失败,Err:" + err.Error()
//		return
//	}
//	if approvalItem == nil {
//		br.Msg = "订单已审批，请刷新页面查看最新状态"
//		br.ErrMsg = "待审批信息不存在,CompanyId:" + strconv.Itoa(req.CompanyId) + ";productId:" + strconv.Itoa(productId)
//		return
//	}
//
//	if approvalItem.ApproveRoleTypeCode != roleTypeCode {
//		br.Msg = "您无权审批"
//		br.ErrMsg = "ApproveRoleTypeCode:" + approvalItem.ApproveRoleTypeCode + ";roleTypeCode:" + roleTypeCode
//		return
//	}
//
//	var approveStatus, approveContent string
//
//	if req.Status == 1 { //通过
//		//申请类型：1:试用->正式,2:冻结—>试用,3:试用延期,4:原销售申请领取流失客户，5:正式客户申请服务更新
//		if approvalItem.ApplyMethod == 1 { //试用转正式
//			//获取合同信息
//			contract, err := company.GetCompanyContractDetail(req.CompanyId, productId, req.CompanyContractId)
//			if err != nil {
//				br.Msg = "待审批信息不存在"
//				br.ErrMsg = "待审批信息不存在,CompanyId:" + strconv.Itoa(req.CompanyId) + ";productId:" + strconv.Itoa(productId) + ";Err:" + err.Error()
//				return
//			}
//			if contract == nil {
//				br.Msg = "待审批信息不存在"
//				br.ErrMsg = "待审批信息不存在,CompanyId:" + strconv.Itoa(req.CompanyId) + ";productId:" + strconv.Itoa(productId)
//				return
//			}
//
//			//格式化合同开始时间
//			contractStartDate, err := time.Parse(utils.FormatDate, contract.StartDate)
//			if err != nil {
//				br.Msg = "审批失败"
//				br.ErrMsg = "合同开始时间转换失败,Err:" + err.Error()
//				return
//			}
//			//格式化合同结束日期
//			contractEndDate, err := time.Parse(utils.FormatDate, contract.EndDate)
//			if err != nil {
//				br.Msg = "审批失败"
//				br.ErrMsg = "合同结束时间转换失败,Err:" + err.Error()
//				return
//			}
//			//格式化 产品中 合同结束日期
//			//productContractEndDate, err := time.Parse(utils.FormatDate, companyProduct.ContractEndDate)
//			//if err != nil {
//			//	br.Msg = "审批失败"
//			//	br.ErrMsg = "产品中合同结束时间转换失败,Err:" + err.Error()
//			//	return
//			//}
//			//如果合同时间小于等于今天，那么立马执行合同内容
//			if time.Now().After(contractStartDate) {
//				_, err = company.TryOutToFormal(req.CompanyId, productId, sysUser.AdminId, approvalItem.CompanyApprovalId, contract.CompanyContractId, contract.StartDate, contract.EndDate, sysUser.RealName, companyProduct.ProductName, contract.PackageType)
//				if err != nil {
//					br.Msg = "审批失败"
//					br.ErrMsg = "审批失败,Err:" + err.Error()
//					return
//				}
//			} else {
//				err = company.ApplyApproveContract(req.CompanyId, productId, approvalItem.CompanyApprovalId, contract.CompanyContractId)
//				if err != nil {
//					br.Msg = "审批失败"
//					br.ErrMsg = "审批失败,Err:" + err.Error()
//					return
//				}
//			}
//			//如果合同中的结束日期大于产品中的合同结束日期，那么就去修改产品中的合同结束日期
//			if contractEndDate.After(companyProduct.ContractEndDate) {
//				companyProduct.ContractEndDate = contractEndDate
//				cols := make([]string, 0)
//				cols = append(cols, "ContractEndDate")
//				_ = companyProduct.Update(cols)
//			}
//		} else if approvalItem.ApplyMethod == 2 { //冻结->试用
//			_, _, _, err = company.FreezeToTryOut(req.CompanyId, productId, sysUser.AdminId, approvalItem.CompanyApprovalId, approvalItem.ApplyUserId, sysUser.RealName, companyProduct.ProductName)
//			if err != nil {
//				br.Msg = "审批失败"
//				br.ErrMsg = "审批失败,Err:" + err.Error()
//				return
//			}
//		} else if approvalItem.ApplyMethod == 3 { //试用延期
//			_, _, err = company.TryOutDelay(req.CompanyId, productId, sysUser.AdminId, approvalItem.CompanyApprovalId, sysUser.RealName, companyProduct.EndDate, companyProduct.ProductName)
//			if err != nil {
//				br.Msg = "审批失败"
//				br.ErrMsg = "审批失败,Err:" + err.Error()
//				return
//			}
//		} else if approvalItem.ApplyMethod == 4 { //原销售申请领取流失客户
//			sellerItem, err := system.GetSysAdminById(approvalItem.ApplyUserId)
//			if err != nil {
//				br.Msg = "审批失败"
//				br.ErrMsg = "找不到申请的销售,Err:" + err.Error()
//				return
//			}
//			_, _, _, err = company.ApplyReceive(req.CompanyId, productId, sysUser.AdminId, approvalItem.CompanyApprovalId, sellerItem, sysUser.RealName, companyProduct.ProductName, sellerItem.RealName, sellerItem.AdminId)
//			if err != nil {
//				br.Msg = "审批失败"
//				br.ErrMsg = "审批失败,Err:" + err.Error()
//				return
//			}
//		} else if approvalItem.ApplyMethod == 5 || approvalItem.ApplyMethod == 6 { //正式客户申请服务更新
//			//获取合同信息
//			contract, err := company.GetCompanyContractDetail(req.CompanyId, productId, req.CompanyContractId)
//			if err != nil {
//				br.Msg = "待审批信息不存在"
//				br.ErrMsg = "待审批信息不存在,CompanyId:" + strconv.Itoa(req.CompanyId) + ";productId:" + strconv.Itoa(productId) + ";Err:" + err.Error()
//				return
//			}
//			if contract == nil {
//				br.Msg = "待审批信息不存在"
//				br.ErrMsg = "待审批信息不存在,CompanyId:" + strconv.Itoa(req.CompanyId) + ";productId:" + strconv.Itoa(productId)
//				return
//			}
//			//格式化合同开始时间
//			contractStartDate, err := time.Parse(utils.FormatDate, contract.StartDate)
//			if err != nil {
//				br.Msg = "审批失败"
//				br.ErrMsg = "合同开始时间转换失败,Err:" + err.Error()
//				return
//			}
//
//			//格式化合同结束日期
//			contractEndDate, err := time.Parse(utils.FormatDate, contract.EndDate)
//			if err != nil {
//				br.Msg = "审批失败"
//				br.ErrMsg = "合同结束时间转换失败,Err:" + err.Error()
//				return
//			}
//			//格式化 产品中 合同结束日期
//			//productContractEndDate, err := time.Parse(utils.FormatDate, companyProduct.ContractEndDate)
//			//if err != nil {
//			//	br.Msg = "审批失败"
//			//	br.ErrMsg = "产品中合同结束时间转换失败,Err:" + err.Error()
//			//	return
//			//}
//
//			//如果合同时间小于等于今天，那么立马执行合同内容
//			if time.Now().After(contractStartDate) {
//				_, err = company.ApplyServiceUpdate(req.CompanyId, productId, sysUser.AdminId, approvalItem.CompanyApprovalId, contract.CompanyContractId, companyProduct.StartDate, contract.EndDate, sysUser.RealName, companyProduct.ProductName, contract.PackageType)
//				if err != nil {
//					br.Msg = "审批失败"
//					br.ErrMsg = "审批失败,Err:" + err.Error()
//					return
//				}
//			} else {
//				err = company.ApplyApproveContract(req.CompanyId, productId, approvalItem.CompanyApprovalId, contract.CompanyContractId)
//				if err != nil {
//					br.Msg = "审批失败"
//					br.ErrMsg = "审批失败,Err:" + err.Error()
//					return
//				}
//			}
//
//			//如果合同中的结束日期大于产品中的合同结束日期，那么就去修改产品中的合同结束日期
//			if contractEndDate.After(companyProduct.ContractEndDate) {
//				companyProduct.ContractEndDate = contractEndDate
//				cols := make([]string, 0)
//				cols = append(cols, "ContractEndDate")
//				_ = companyProduct.Update(cols)
//			}
//		} else {
//			br.Msg = "审批失败"
//			br.ErrMsg = "无效的审批状态,CompanyId:" + strconv.Itoa(req.CompanyId) + ";productId:" +
//				strconv.Itoa(productId) + ";ApplyMethod:" + strconv.Itoa(approvalItem.ApplyMethod) + " ApproveStatus;" + approvalItem.ApproveStatus
//			return
//		}
//		approveContent = "审批通过"
//	} else { //拒绝
//		approveStatus = "驳回"
//		err = company.ApproveRefuse(req.CompanyId, productId, approveStatus, req.Remark)
//		approveContent = "审批驳回"
//		if err != nil {
//			br.Msg = "审批失败"
//			br.ErrMsg = "审批失败,Err:" + err.Error()
//			return
//		}
//	}
//
//	//新增客户产品日志
//	{
//		productLog := new(company.CompanyProductLog)
//		productLog.CompanyProductId = companyProduct.CompanyProductId
//		productLog.CompanyId = companyProduct.CompanyId
//		productLog.ProductId = companyProduct.ProductId
//		productLog.ProductName = companyProduct.ProductName
//		productLog.CompanyName = companyProduct.CompanyName
//		productLog.CompanyName = companyProduct.CompanyName
//		productLog.Source = companyProduct.Source
//		productLog.Reasons = companyProduct.Reasons
//		productLog.Status = companyProduct.Status
//		productLog.IndustryId = companyProduct.IndustryId
//		productLog.IndustryName = companyProduct.IndustryName
//		productLog.SellerId = companyProduct.SellerId
//		productLog.SellerName = companyProduct.SellerName
//		productLog.GroupId = companyProduct.GroupId
//		productLog.DepartmentId = companyProduct.DepartmentId
//		productLog.IsSuspend = companyProduct.IsSuspend
//		productLog.SuspendTime = companyProduct.SuspendTime
//		productLog.ApproveStatus = companyProduct.ApproveStatus
//		productLog.FreezeTime = companyProduct.FreezeTime
//		productLog.Remark = companyProduct.Remark
//		productLog.StartDate = companyProduct.StartDate
//		productLog.EndDate = companyProduct.EndDate
//		productLog.CreateTime = companyProduct.CreateTime
//		productLog.ModifyTime = companyProduct.ModifyTime
//		productLog.LoseReason = companyProduct.LoseReason
//		productLog.LossTime = companyProduct.LossTime
//		productLog.LogType = "modify"
//		productLog.LogCreateTime = time.Now()
//		productLog.AdminId = this.SysUser.AdminId
//		go company.AddCompanyProductLog(productLog)
//	}
//	//新增操作记录
//	{
//		remark := "审批"
//		operation := "approve"
//		services.AddCompanyOperationRecord(req.CompanyId, companyProduct.SellerId, sysUser.AdminId, productId, sysUser.AdminId, companyProduct.CompanyName,
//			companyProduct.ProductName, sysUser.RealName, remark, operation, approveContent, sysUser.RealName, req.Remark, companyProduct.Status)
//	}
//	//待办通知
//	{
//		content := companyProduct.CompanyName + " " + approvalItem.ApproveContent + approveContent
//		approvalSysUser, _ := system.GetSysAdminById(approvalItem.ApplyUserId)
//		if sysUser != nil {
//			//审批通过
//			approvalStatus := 2
//			if req.Status != 1 {
//				//审批驳回
//				approvalStatus = 3
//			}
//			go services.AddCompanyApprovalMessage(sysUser.AdminId, approvalItem.ApplyUserId, req.CompanyId, approvalItem.CompanyApprovalId, 2, 1, approvalStatus, companyProduct.CompanyName, content, content, approvalSysUser.Mobile)
//		}
//	}
//	br.Ret = 200
//	br.Success = true
//	br.Msg = "审批成功"
//}

// ApplyDelete
// @Title 审批列表删除
// @Description 审批列表删除接口
// @Param	request	body company.CompanyApplyDeleteReq true "type json string"
// @Success Ret=200 删除成功
// @router /approval/delete [post]
func (this *CompanyApprovalController) ApplyDelete() {
	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 company.CompanyApplyDeleteReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	roleTypeCode := sysUser.RoleTypeCode
	productId := services.GetProductId(roleTypeCode)
	if productId == 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "客户类型为：" + roleTypeCode
		return
	}
	if req.CompanyId <= 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "客户Id小于等于0："
		return
	}
	companyProduct, err := company.GetCompanyProductByCompanyIdAndProductId(req.CompanyId, productId)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取信息失败,Err:" + err.Error()
		return
	}
	if companyProduct == nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取审批信息失败,Err:" + err.Error()
		return
	}
	approvalItem, err := company.GetCompanyApprovalByApprovalId(req.CompanyApprovalId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "待审批信息不存在"
			br.ErrMsg = "待审批信息不存在,CompanyId:" + strconv.Itoa(req.CompanyId) + ";productId:" + strconv.Itoa(productId)
			return
		}
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取信息失败,Err:" + err.Error()
		return
	}
	if approvalItem == nil {
		br.Msg = "待审批信息不存在"
		br.ErrMsg = "待审批信息不存在,CompanyId:" + strconv.Itoa(req.CompanyId) + ";productId:" + strconv.Itoa(productId)
		return
	}
	if approvalItem.ApproveStatus != "已撤回" {
		br.Msg = "审批状态为：" + approvalItem.ApproveStatus + ";不可删除"
		br.ErrMsg = "审批状态为：" + approvalItem.ApproveStatus + ";不可删除" + ";CompanyId:" + strconv.Itoa(req.CompanyId) + ";productId:" + strconv.Itoa(productId)
		return
	}
	//删除
	err = company.ApplyDelete(req.CompanyId, req.CompanyApprovalId, approvalItem.ProductId, approvalItem.CompanyContractId)
	if err != nil {
		br.Msg = "删除失败"
		br.ErrMsg = "删除失败,Err:" + err.Error()
		return
	}
	//新增操作记录
	{
		remark := "删除审批申请"
		operation := "approve_delete"
		services.AddCompanyOperationRecord(req.CompanyId, companyProduct.SellerId, sysUser.AdminId, productId, sysUser.AdminId, companyProduct.CompanyName,
			companyProduct.ProductName, sysUser.RealName, remark, operation, remark, sysUser.RealName, "", companyProduct.Status)
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "删除成功"
}
