package seal

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

// 用印审批管理
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	"搜索关键词(客户名称/社会信用码)"
// @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)

	// 筛选条件
	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)
	}

	// 列表
	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,
	}
}

// 用印申请
// @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()},
	}

	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
	}

	// 编辑用印
	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
	}

	// 审批者编辑
	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,
	}
}
