package seal

import (
	"encoding/json"
	"errors"
	"fmt"
	"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/company"
	"hongze/hz_crm_api/models/contract"
	sealModels "hongze/hz_crm_api/models/seal"
	"hongze/hz_crm_api/models/seal/request"
	"hongze/hz_crm_api/models/seal/response"
	"hongze/hz_crm_api/services/seal"
	"hongze/hz_crm_api/utils"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"time"
)

// 用印审批管理
type SealApprovalController struct {
	controllers.BaseAuthController
}

// 用印审批列表-分页
// @Title 用印审批列表
// @Description 用印审批列表
// @Param   PageSize		query   int  	true	"每页数据条数"
// @Param   CurrentIndex	query   int  	true	"当前页页码,从1开始"
// @Param   ContractType	query   string  false	"合同类型 新签合同/续签合同/代付合同"
// @Param   Status			query   string  false	"用印状态 待审批/处理中/已审批/已驳回/已签回/已作废"
// @Param   SellerId   		query   string	false	"所属销售ID,多个逗号拼接"
// @Param   StartTime   	query   string  false	"提交开始时间"
// @Param   EndTime   		query   string  false	"提交结束时间"
// @Param   Keyword   		query   string  false	"搜索关键词(客户名称/社会信用码)"
// @Param   IsExport   		query   bool  	false   "是否导出excel,默认是false"
// @Param   AffiliatedCompany   query   string  	false   "归属公司"
// @Success 200 {object} response.SealApprovalListResp
// @router /getApprovalPageList [get]
func (this *SealApprovalController) 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
	}

	// 分页
	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)
	isExport, _ := this.GetBool("IsExport", false)
	// 筛选条件
	condition := ""
	joinCondition := " AND a.curr_node_id = d.node_id" // contract_approval和contract_approval_record的join条件
	pars := make([]interface{}, 0)

	// 数据权限
	reqStatus := this.GetString("Status")
	if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_ADMIN {
		// 超管
		condition += ` AND c.status != "已撤回" `
		if reqStatus != "" {
			if reqStatus == "待审批" {
				// 当前审批节点小于等于审批节点且状态为-待审批
				condition += ` AND (a.curr_node_id <= a.start_node_id AND c.status = "待审批") `
				joinCondition = ``
			} else if reqStatus == "处理中" {
				// 当前审批节点大于开始审批节点且状态为-待审批
				condition += ` AND (a.curr_node_id > a.start_node_id AND c.status = "待审批")`
			} else {
				condition += ` AND c.status = ?`
				pars = append(pars, reqStatus)
			}
		}
	} else if sysUser.RoleTypeCode == utils.ROLE_TYPE_CODE_COMPLIANCE {
		// 合规
		if reqStatus != "" {
			if reqStatus == "待审批" {
				condition += ` AND (d.approve_user_id = ? AND a.curr_node_id <= d.node_id AND d.node_type != "cc") AND c.status="待审批"`
				joinCondition = ``
				pars = append(pars, sysUser.AdminId)
			} else if reqStatus == "处理中" {
				condition += ` AND (d.approve_user_id = ? AND a.curr_node_id > d.node_id AND d.node_type != "cc") AND c.status="待审批"`
				joinCondition = " AND a.curr_node_id != d.node_id"
				pars = append(pars, sysUser.AdminId)
			} else if reqStatus == "已撤回" {
				condition += ` AND c.status = ? AND c.user_id = ?`
				pars = append(pars, reqStatus, sysUser.AdminId)
			} else {
				condition += ` AND c.status = ?`
				pars = append(pars, reqStatus)
			}
		} else {
			condition += ` AND (c.status = "已撤回" AND c.user_id = ? ) OR (c.status != "已撤回") AND (c.status != "待提交")`
			pars = append(pars, sysUser.AdminId)
		}
	} else {
		// 销售
		condition += ` AND (c.user_id = ? OR (d.approve_user_id = ? AND d.node_id <= a.curr_node_id) OR (d.approve_user_id = ? AND d.node_type = "cc") )`
		pars = append(pars, sysUser.AdminId, sysUser.AdminId, sysUser.AdminId)
		if reqStatus != "" {
			switch reqStatus {
			case "待审批":
				condition += ` AND c.status = "待审批" AND ( (((c.user_id = ? and a.start_node_id = a.curr_node_id) OR (d.approve_user_id = ? AND a.curr_node_id=d.node_id)) ) OR (d.approve_user_id = ? AND a.curr_node_id > d.node_id AND d.node_type="cc") )`
				joinCondition = ``
				pars = append(pars, sysUser.AdminId, sysUser.AdminId, sysUser.AdminId)
			case "处理中":
				condition += ` AND ((c.user_id = ? AND a.start_node_id != a.curr_node_id) OR (d.approve_user_id = ? AND a.curr_node_id > d.node_id AND d.node_type != "cc")) AND c.status="待审批" `
				joinCondition = " AND a.curr_node_id != d.node_id"
				pars = append(pars, sysUser.AdminId, sysUser.AdminId)
			case "已撤回":
				condition += ` AND (c.status = "已撤回" AND c.user_id = ? ) `
				pars = append(pars, sysUser.AdminId)
			case "已审批", "已驳回", "已签回", "已作废":
				joinCondition = ``
				condition += ` AND c.status = ?`
				pars = append(pars, reqStatus)
			}
		} else {
			joinCondition = ``
			condition += ` AND ((c.status = "已撤回" AND c.user_id = ? ) OR (c.status != "已撤回")) `
			pars = append(pars, sysUser.AdminId)
		}
	}

	// 合同类型
	reqContractType := this.GetString("ContractType")
	if reqContractType != "" {
		condition += ` AND c.service_type = ? `
		pars = append(pars, reqContractType)
	}
	// 所属销售-多个
	reqSellerId := this.GetString("SellerId")
	if reqSellerId != "" {
		condition += ` AND c.user_id IN (` + reqSellerId + `)`
	}
	// 提交时间
	reqStartTime := this.GetString("StartTime")
	reqEndTime := this.GetString("EndTime")
	if reqStartTime != "" && reqEndTime != "" {
		reqStartTime += " 00:00:00"
		reqEndTime += " 23:59:59"
		condition += ` AND c.create_time >= ? AND c.create_time <= ?`
		pars = append(pars, reqStartTime, reqEndTime)
	}
	// 客户名称-社会信用码
	reqKeyword := this.GetString("Keyword")
	if reqKeyword != "" {
		keywords := "%" + reqKeyword + "%"
		condition += ` AND (c.company_name LIKE ? OR c.use_company_name LIKE ? OR c.credit_code LIKE ?)`
		pars = append(pars, keywords, keywords, keywords)
	}

	// 归属公司
	affiliatedCompany := this.GetString("AffiliatedCompany")
	if affiliatedCompany != "" {
		condition += ` AND c.affiliated_company = ?`
		pars = append(pars, affiliatedCompany)
	}

	//导出excel
	if isExport {
		ApprovalListExport(this, condition, joinCondition, pars, br)
		return
	}

	// 列表
	listData, listTotal, err := seal.GetSealApprovalPageList(condition, joinCondition, pars, startSize, pageSize, sysUser)
	if err != nil {
		br.Msg = "审批列表获取失败!"
		br.ErrMsg = "审批列表获取失败!" + err.Error()
		return
	}
	page := paging.GetPaging(currentIndex, pageSize, listTotal)

	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = response.SealApprovalListResp{
		Paging: page,
		List:   listData,
	}
}

// ApprovalListExport 审批列表导出
func ApprovalListExport(this *SealApprovalController, condition, joinCondition string, pars []interface{}, br *models.BaseResponse) {
	list, err := sealModels.GetSealApprovalList(condition, joinCondition, pars)
	if err != nil {
		br.Msg = "审批列表获取失败!"
		br.ErrMsg = "审批列表获取失败!" + err.Error()
		return
	}
	////超级管理员和权益管理员、权益研究员可以下载所有客户,销售组长能下载本组客户,销售只能下载本人名下客户
	//resp := new(cygx.CanDownload)
	//adminInfo, errAdmin := system.GetSysUserById(sysUser.AdminId)
	//if errAdmin != nil {
	//	br.Msg = "获取失败"
	//	br.ErrMsg = "获取失败,Err:" + errAdmin.Error()
	//	return
	//}
	//if adminInfo.Role == "admin" || adminInfo.Role == "researcher" {
	//	resp.IsCanDownload = true
	//}

	if len(list) > 0 {
		// 取出所有列表的关联合同id
		contractIdSlice := make([]string, 0)
		contractApprovalIdSlice := make([]string, 0)
		for i := 0; i < len(list); i++ {
			contractIdSlice = append(contractIdSlice, strconv.Itoa(list[i].ContractId))
			contractApprovalIdSlice = append(contractApprovalIdSlice, strconv.Itoa(list[i].ContractApprovalId))
		}

		// 获取所有关联的合同列表
		selfContractMap := make(map[int]*contract.ContractList)
		{
			if len(contractIdSlice) > 0 {
				contractIdStr := strings.Join(contractIdSlice, ",")
				contractList, tempErr := contract.GetContractListByContractIds(contractIdStr)
				if tempErr != nil {
					err = errors.New(fmt.Sprint("获取合同失败,Err:"+tempErr.Error(), err))
					return
				}
				for i := 0; i < len(contractList); i++ {
					selfContractMap[contractList[i].ContractId] = contractList[i]
				}
			}
		}

		selfContractApprovalRecordMap := make(map[int][]*contract.ContractApprovalRecord)
		{
			if len(contractApprovalIdSlice) > 0 {
				contractApprovalIdStr := strings.Join(contractApprovalIdSlice, ",")
				contractApprovalList, tempErr := contract.GetContractApprovalRecordListByContractApprovalIds(contractApprovalIdStr)
				if tempErr != nil {
					err = errors.New(fmt.Sprint("获取合同审批记录失败,Err:"+tempErr.Error(), err))
					return
				}
				for i := 0; i < len(contractApprovalList); i++ {
					selfContractApprovalRecordMap[contractApprovalList[i].ContractApprovalId] = append(selfContractApprovalRecordMap[contractApprovalList[i].ContractApprovalId], contractApprovalList[i])
				}
			}
		}

		for i, v := range list {
			// 合同编码
			if selfContract, has := selfContractMap[v.ContractId]; has {
				list[i].ContractCode = selfContract.ContractCode
			}

			// 审批人和抄送人
			if recordList, ok := selfContractApprovalRecordMap[v.ContractApprovalId]; ok {
				keySort := make([]int, 0)
				flowNodeMap := make(map[int][]contract.ContractApprovalRecord, 0)
				for _, approvalRecord := range recordList {
					if tmpFlowNodeList, ok := flowNodeMap[approvalRecord.NodeId]; ok {
						flowNodeMap[approvalRecord.NodeId] = append(tmpFlowNodeList, *approvalRecord)
					} else {
						tmpFlowNodeList := make([]contract.ContractApprovalRecord, 1)
						tmpFlowNodeList[0] = *approvalRecord
						flowNodeMap[approvalRecord.NodeId] = tmpFlowNodeList

						keySort = append(keySort, approvalRecord.NodeId)
					}
				}
				approversList := make([][]string, 0)
				ccList := make([][]string, 0)
				for _, key := range keySort {
					approver := make([]string, 0)
					cc := make([]string, 0)
					if node, ok := flowNodeMap[key]; ok {
						for _, vv := range node {
							if vv.NodeType == "check" {
								approver = append(approver, vv.ApproveUserName)
							} else if vv.NodeType == "cc" {
								cc = append(cc, vv.ApproveUserName)
							}
						}
						if len(approver) > 0 {
							approversList = append(approversList, approver)
						}
						if len(cc) > 0 {
							ccList = append(ccList, cc)
						}
					}
				}
				if len(approversList) > 0 {
					list[i].FirstLevelApprovers = strings.Join(approversList[0], ",")
				}
				if len(ccList) > 0 {
					list[i].FirstLevelCC = strings.Join(ccList[0], ",")
				}
				if len(approversList) > 1 {
					list[i].SecondLevelApprovers = strings.Join(approversList[1], ",")
				}
				if len(ccList) > 1 {
					list[i].SecondLevelCC = strings.Join(ccList[1], ",")
				}
				if len(approversList) > 2 {
					list[i].ThirdLevelApprovers = strings.Join(approversList[2], ",")
				}
				if len(ccList) > 2 {
					list[i].ThirdLevelCC = strings.Join(ccList[2], ",")
				}
			}
		}
	}
	//创建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

	sheetName := "审批列表"
	sheet, err := xlsxFile.AddSheet(sheetName)
	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 = "合同编号"
	cellF := rowTitle.AddCell()
	cellF.Value = "合同类型"
	cellG := rowTitle.AddCell()
	cellG.Value = "加盖印章"
	cellH := rowTitle.AddCell()
	cellH.Value = "所属销售"
	cellI := rowTitle.AddCell()
	cellI.Value = "提交时间"
	cellJ := rowTitle.AddCell()
	cellJ.Value = "用印状态"
	cellK := rowTitle.AddCell()
	cellK.Value = "一级审批人"
	cellL := rowTitle.AddCell()
	cellL.Value = "一级抄送人"
	cellM := rowTitle.AddCell()
	cellM.Value = "二级审批人"
	cellN := rowTitle.AddCell()
	cellN.Value = "二级抄送人"
	cellO := rowTitle.AddCell()
	cellO.Value = "三级审批人"
	cellP := rowTitle.AddCell()
	cellP.Value = "三级抄送人"

	for _, v := range list {
		row := sheet.AddRow()
		cellA := row.AddCell()
		cellA.Value = v.AffiliatedCompany
		cellB := row.AddCell()
		cellB.Value = v.CompanyName
		cellC := row.AddCell()
		cellC.Value = v.CreditCode
		cellD := row.AddCell()
		cellD.Value = v.Use
		cellE := row.AddCell()
		cellE.Value = v.ContractCode
		cellF := row.AddCell()
		cellF.Value = v.ContractType
		cellG := row.AddCell()
		cellG.Value = v.SealType
		cellH := row.AddCell()
		cellH.Value = v.ApplyUserName
		cellI := row.AddCell()
		cellI.Value = v.CreateTime.Format(utils.FormatDateTime)
		cellJ := row.AddCell()
		cellJ.Value = v.Status
		cellK := row.AddCell()
		cellK.Value = v.FirstLevelApprovers
		cellL := row.AddCell()
		cellL.Value = v.FirstLevelCC
		cellM := row.AddCell()
		cellM.Value = v.SecondLevelApprovers
		cellN := row.AddCell()
		cellN.Value = v.SecondLevelCC
		cellO := row.AddCell()
		cellO.Value = v.ThirdLevelApprovers
		cellP := row.AddCell()
		cellP.Value = v.ThirdLevelCC
	}

	err = xlsxFile.Save(downLoadnFilePath)
	if err != nil {
		br.Msg = "保存文件失败"
		br.ErrMsg = "保存文件失败"
		return
	}
	downloadFileName := "用印审批列表" + time.Now().Format("2006.01.02") + ".xlsx"
	this.Ctx.Output.Download(downLoadnFilePath, downloadFileName)
	defer func() {
		os.Remove(downLoadnFilePath)
	}()
	br.Success = true
	br.Ret = 200
	br.IsAddLog = true
}

// 用印申请
// @Title 用印申请
// @Description 用印申请
// @Param	request	body request.SealApprovalApplyReq true "type json string"
// @Success 200 申请成功
// @router /applySealApproval [post]
func (this *SealApprovalController) Apply() {
	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 request.SealApprovalApplyReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常!"
		br.ErrMsg = "参数解析异常!Err:" + err.Error()
		return
	}
	reqVerify := utils.Rules{
		"Use":               {utils.NotEmpty()},
		"CompanyName":       {utils.NotEmpty()},
		"CreditCode":        {utils.NotEmpty()},
		"ServiceType":       {utils.NotEmpty()},
		"SealType":          {utils.NotEmpty()},
		"FileUrls":          {utils.NotEmpty()},
		"AffiliatedCompany": {utils.NotEmpty()},
	}

	err = utils.Verify(req, reqVerify, utils.LANG_CN)
	if err != nil {
		br.Msg = "参数丢失!"
		br.ErrMsg = "参数丢失!Err:" + err.Error()
		return
	}

	// 申请用印
	err = seal.ApplySeal(this.SysUser, req)
	if err != nil {
		br.Msg = "申请用印失败!"
		br.ErrMsg = "申请用印失败!Err:" + err.Error()
		return
	}

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

// 编辑用印申请
// @Title 编辑用印申请
// @Description 编辑用印申请
// @Param	request	body request.SealApprovalEditReq true "type json string"
// @Success 200 操作成功
// @router /editSealApproval [post]
func (this *SealApprovalController) 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 request.SealApprovalEditReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常!"
		br.ErrMsg = "参数解析异常!Err:" + err.Error()
		return
	}
	if req.SealId <= 0 {
		br.Msg = "用印审批ID有误"
		br.ErrMsg = "用印审批ID有误"
		return
	}
	if req.Use == "" {
		br.Msg = "用印用途不能为空"
		br.ErrMsg = "用印用途不能为空"
		return
	}
	if req.CompanyName == "" {
		br.Msg = "客户名称不能为空"
		br.ErrMsg = "客户名称不能为空"
		return
	}
	if req.CreditCode == "" {
		br.Msg = "社会统一信用代码不能为空"
		br.ErrMsg = "社会统一信用代码不能为空"
		return
	}
	if req.ServiceType == "" {
		br.Msg = "合同类型不能为空"
		br.ErrMsg = "合同类型不能为空"
		return
	}
	if req.SealType == "" {
		br.Msg = "印章类型不能为空"
		br.ErrMsg = "印章类型不能为空"
		return
	}
	if len(req.FileUrls) == 0 {
		br.Msg = "合同附件不能为空"
		br.ErrMsg = "合同附件不能为空"
		return
	}
	if req.AffiliatedCompany == "" {
		br.Msg = "归属公司不能为空"
		br.ErrMsg = "归属公司不能为空"
		return
	}

	// 编辑用印
	err = seal.EditApply(this.SysUser, req)
	if err != nil {
		br.Msg = "编辑用印申请失败!"
		br.ErrMsg = "编辑用印申请失败!Err:" + err.Error()
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "编辑用印申请成功"
}

// 审批角色编辑
// @Title 审批角色编辑
// @Description 审批角色编辑
// @Param	request	body request.SealApprovalEditReq true "type json string"
// @Success 200 操作成功
// @router /verifierEditSealApproval [post]
func (this *SealApprovalController) VerifierEdit() {
	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 request.SealApprovalEditReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常!"
		br.ErrMsg = "参数解析异常!Err:" + err.Error()
		return
	}
	if req.SealId <= 0 {
		br.Msg = "用印审批ID有误"
		br.ErrMsg = "用印审批ID有误"
		return
	}
	if req.Use == "" {
		br.Msg = "用印用途不能为空"
		br.ErrMsg = "用印用途不能为空"
		return
	}
	if req.CompanyName == "" {
		br.Msg = "客户名称不能为空"
		br.ErrMsg = "客户名称不能为空"
		return
	}
	if req.CreditCode == "" {
		br.Msg = "社会统一信用代码不能为空"
		br.ErrMsg = "社会统一信用代码不能为空"
		return
	}
	if req.ServiceType == "" {
		br.Msg = "合同类型不能为空"
		br.ErrMsg = "合同类型不能为空"
		return
	}
	if req.SealType == "" {
		br.Msg = "印章类型不能为空"
		br.ErrMsg = "印章类型不能为空"
		return
	}
	if len(req.FileUrls) == 0 {
		br.Msg = "合同附件不能为空"
		br.ErrMsg = "合同附件不能为空"
		return
	}
	if req.AffiliatedCompany == "" {
		br.Msg = "归属公司不能为空"
		br.ErrMsg = "归属公司不能为空"
		return
	}

	// 审批者编辑
	err = seal.VerifierEditApply(this.SysUser, req)
	if err != nil {
		br.Msg = "编辑用印申请失败!"
		br.ErrMsg = "编辑用印申请失败!Err:" + err.Error()
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "编辑用印申请成功"
}

// 用印审批详情
// @Title 用印审批详情
// @Description 用印审批详情
// @Param   SealId	query	int	false	"用印审批ID"
// @Success 200 {object} response.SealApprovalDetail
// @router /getSealApprovalDetail [get]
func (this *SealApprovalController) Detail() {
	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
	}
	sealId, _ := this.GetInt("SealId")
	sealInfo, flowNodeListResp, opButton, err := seal.GetSealApprovalDetail(sealId, sysUser)
	if err != nil {
		br.Msg = "获取用印详情失败"
		br.ErrMsg = "获取用印详情失败,Err:" + err.Error()
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = response.SealApprovalDetail{
		SealDetail:   sealInfo,
		FlowNodeList: flowNodeListResp,
		OpButton:     opButton,
	}
}

// 撤回用印申请
// @Title 撤回用印申请
// @Description 撤回用印申请
// @Param	request	body request.SealApprovalCancelReq true "type json string"
// @Success 200 操作成功
// @router /cancelSealApproval [post]
func (this *SealApprovalController) Cancel() {
	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 request.SealApprovalCancelReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常!"
		br.ErrMsg = "参数解析异常!Err:" + err.Error()
		return
	}
	if req.SealId <= 0 {
		br.Msg = "参数异常!"
		br.ErrMsg = "参数异常!"
		return
	}

	err = seal.CancelSealApproval(req.SealId, sysUser)
	if err != nil {
		br.Msg = "用印审批撤回失败"
		br.ErrMsg = "用印审批撤回失败,Err:" + err.Error()
		return
	}

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

// 删除用印申请
// @Title 删除用印申请
// @Description 删除用印申请
// @Param	request	body request.SealApprovalDelReq true "type json string"
// @Success 200 操作成功
// @router /delSealApproval [post]
func (this *SealApprovalController) Del() {
	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 request.SealApprovalDelReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常!"
		br.ErrMsg = "参数解析异常!Err:" + err.Error()
		return
	}
	if req.SealId <= 0 {
		br.Msg = "参数异常!"
		br.ErrMsg = "参数异常!"
		return
	}

	err = seal.DelSealApproval(req.SealId, sysUser)
	if err != nil {
		br.Msg = "用印申请删除失败"
		br.ErrMsg = "用印申请删除失败,Err:" + err.Error()
		return
	}

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

// 通过用印申请
// @Title 通过用印申请
// @Description 通过用印申请
// @Param	request	body request.SealApplyApprovedReq true "type json string"
// @Success 200 操作成功
// @router /approvedSealApproval [post]
func (this *SealApprovalController) Approved() {
	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 request.SealApplyApprovedReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常!"
		br.ErrMsg = "参数解析异常!Err:" + err.Error()
		return
	}
	if req.SealId <= 0 {
		br.Msg = "参数异常!"
		br.ErrMsg = "参数异常!"
		return
	}

	err = seal.ApprovedApproval(req.SealId, sysUser, req.Remark)
	if err != nil {
		br.Msg = "用印审批失败"
		br.ErrMsg = "用印审批失败,Err:" + err.Error()
		return
	}

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

// 驳回用印申请
// @Title 驳回用印申请
// @Description 驳回用印申请
// @Param	request	body request.SealApplyRejectReq true "type json string"
// @Success 200 操作成功
// @router /rejectSealApproval [post]
func (this *SealApprovalController) Reject() {
	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 request.SealApplyRejectReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常!"
		br.ErrMsg = "参数解析异常!Err:" + err.Error()
		return
	}
	if req.SealId <= 0 {
		br.Msg = "参数异常!"
		br.ErrMsg = "参数异常!"
		return
	}
	remark := strings.Trim(req.Remark, " ")
	if remark == "" {
		br.Msg = "请输入驳回理由"
		br.ErrMsg = "请输入驳回理由"
		return
	}

	err = seal.RejectApproval(req.SealId, sysUser, remark)
	if err != nil {
		br.Msg = "用印驳回失败"
		br.ErrMsg = "用印驳回失败,Err:" + err.Error()
		return
	}

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

// 作废用印申请
// @Title 作废用印申请
// @Description 作废用印申请
// @Param	request	body request.SealApplyInvalidReq true "type json string"
// @Success 200 操作成功
// @router /invalidSealApproval [post]
func (this *SealApprovalController) Invalid() {
	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 request.SealApprovalInvalidReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常!"
		br.ErrMsg = "参数解析异常!Err:" + err.Error()
		return
	}
	if req.SealId <= 0 {
		br.Msg = "参数异常!"
		br.ErrMsg = "参数异常!"
		return
	}

	err = seal.InvalidSealApproval(req.SealId, sysUser)
	if err != nil {
		br.Msg = "用印作废失败"
		br.ErrMsg = "用印作废失败,Err:" + err.Error()
		return
	}

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

// OperationList
// @Title 用印操作日志列表
// @Description 用印操作日志列表接口
// @Param   SealId	query	int	true	"用印申请ID"
// @Success 200 {object} response.SealOperationListResp
// @router /getOperationList [get]
func (this *SealApprovalController) OperationList() {
	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
	}

	reqSealId, _ := this.GetInt("SealId", 0)
	if reqSealId <= 0 {
		br.Msg = "用印申请编号获取失败!"
		br.ErrMsg = "用印申请编号获取失败!"
		return
	}

	list, err := seal.GetSealOperationRecordList(reqSealId)
	if err != nil {
		br.Msg = "获取列表失败!"
		br.ErrMsg = "获取列表失败!"
		return
	}

	br.Ret = 200
	br.Msg = "获取成功"
	br.Success = true
	br.Data = response.SealOperationListResp{
		List: list,
	}
}

// 关联公司列表
// @Title 关联公司列表
// @Description 关联公司列表
// @Success 200 {object} response.SealApprovalListResp
// @router /getAffiliatedCompany [get]
func (this *SealApprovalController) AffiliatedCompanyList() {
	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
	}
	crmConfig, err := company.GetConfigDetailByCode("affiliated_company")
	if err != nil {
		br.Msg = "获取配置失败"
		br.ErrMsg = "获取配置失败"
		br.IsSendEmail = false
		return
	}
	list := strings.Split(crmConfig.ConfigValue, ",")

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