class ApplySignaturesController < ApplicationController
  include ApplicationHelper
  before_action :require_login
  before_action :find_project, only: [:index, :show_pro_info, :create, :create_simple_info, :update]
  before_action :require_owner, only: [:update]
  before_action :find_apply_signature, only: [:update, :create_detail]

  def index 
    search = params[:search].to_s.downcase
    @apply_signatures = @project.apply_signatures.with_status(status).includes(user: :user_extension)
    @apply_signatures = @apply_signatures.joins(:user).where("apply_signatures.name like ?" ,"%#{search}%").or(@apply_signatures.joins(:user).where("LOWER(CONCAT_WS(users.lastname, users.firstname, users.login, users.mail, users.nickname)) LIKE ?", "%#{search.split(" ").join('|')}%")) if search.present?
    @apply_signatures = kaminari_paginate(@apply_signatures)
  end

  def show_pro_info
    @user_apply_signature = @project.apply_signatures.with_user_id(current_user.id).take
  end

  def template_file
    license_name = params[:license_name] || "PHengLEI"
    license_name = "PHengLEI" if license_name =="undefined"
    license = License.find_by_name(license_name)
    file = license.attachments.take
    # normal_status(-1, "文件不存在") if file.blank?
    if file.blank?
      if license_name == "PHengLEI" && ["personal", "enterprise"].include?(params[:license_type].to_s)
        path = "#{Rails.root.to_s}/public/#{license_name}-License-#{params[:license_type]}.docx"
        file_name = "#{license_name}软件开源协议-#{params[:license_type] == "personal" ? "（个人版）" : "（企业版）"}.docx"
        send_file(path, filename: file_name, stream: false, type: 'application/octet-stream')
      else
        send_file("#{Rails.root.to_s}/public/#{license_name}-License.docx", filename: "#{license_name}软件开源协议.docx", stream: false, type: 'application/octet-stream')
      end
    else
      send_file(absolute_path(local_path(file)), filename: file.title,stream:false, type: file.content_type.presence || 'application/octet-stream')
    end
  end

  def create
    tip_exception "您已上传开源许可协议" if current_user.apply_signatures.where(project_id: params[:project_id]).where(status: ['waiting', 'passed']).present?
    ActiveRecord::Base.transaction do
      begin
        @signature = current_user.apply_signatures.find_or_create_by!(project_id: params[:project_id])
        @signature.status = 0
        @signature.attachments = Attachment.none
        @attachment = Attachment.where_id_or_uuid(params[:attachment_id]).first
        @attachment.container = @signature
        @signature.save!
        @attachment.save!
      rescue Exception => e
        tip_exception("#{e}")
        raise ActiveRecord::Rollback
      end
      render_json
    end
  end

  def create_simple_info 
    current_user.apply_signatures.where(project_id: params[:project_id]).where(status: ['unpassed']).destroy_all
    tip_exception "您已提交基本信息" if current_user.apply_signatures.where(project_id: params[:project_id]).where(status: ['waiting', 'passed']).present?
    ActiveRecord::Base.transaction do
      begin
        ApplySignatures::CreateSimpleInfoForm.new(simple_info_params).validate!
        @signature = current_user.apply_signatures.find_or_create_by!(project_id: params[:project_id])
        @signature.name = params[:name]
        @signature.phone = params[:phone]
        @signature.company_name = params[:company_name]
        @signature.position = params[:position]
        @signature.email = params[:email]
        @signature.remark = params[:remark]
        @signature.save!
      rescue Exception => e
        tip_exception("#{e}")
        raise ActiveRecord::Rollback
      end
    end
    render_ok
  end

  def create_detail
    if ApplySignatureReadDetail.create!(apply_signature: @apply_signature, user: @apply_signature.user)
      render_ok 
    else 
      render_error("阅读审核记录失败")
    end
  end

  def update
    return normal_status(-1, "已经是该状态了") if @apply_signature.status == params[:status]
    @apply_signature.update_attributes!(apply_signature_params)
    if @apply_signature.status == "passed"
      SendTemplateMessageJob.perform_later('ApplySignaturePassed', @apply_signature.user_id, @apply_signature.id)
      Projects::AddMemberInteractor.call(@apply_signature.project.owner, @apply_signature.project, @apply_signature.user, "read", true)
    else
      Projects::DeleteMemberInteractor.call(@apply_signature.project.owner, @apply_signature.project, @apply_signature.user)
    end
    render_ok
  rescue Exception => e
    uid_logger_error(e.message)
    tip_exception(e.message)
  end

  private
  def find_project
    @project = Project.find_by_id(params[:project_id])
    normal_status(-1, "项目不存在") unless @project.present?
  end

  def find_apply_signature
    @apply_signature = ApplySignature.find_by_id(params[:id])
    normal_status(-1, "申请不存在") unless @apply_signature.present?
  end

  def apply_signature_params
    params.permit(:status, :cdkey)
  end

  def simple_info_params 
    params.permit(:name, :phone, :remark, :company_name, :position, :email)
  end

  def status
    params.fetch(:status, "all")
  end

  def require_owner
    normal_status(403, "") unless @project.owner?(current_user) || current_user.admin?
  end
end 