# -*- coding: utf-8 -*-
class UndergroundsController < ApplicationController
    $department = 'construction'
    $department_id = '676'
  before_filter :isAuthorization, :except => :new
  before_filter :set_var#, :except => :new
  before_filter :get_reports, :only => [:index, :index_excel]

  def index
  end
  
  def new

# Тип клиента (t_type):
# 10 Развитие сети
# 20 Корпоративный
# 30 Строительный подряд
# 40 Ремонт
# 50 Легализация
# 60 ЖД

# Все остальное строка или текст.

# $fields = array('t_id' => '##obji_id##',
# 't_type' =>'##field_tip_clienta_value_id##'
# ,'t_loginroot' =>'##field_loginroot_value##'
# ,'t_end' =>'##field_con_points_value##'
# ,'t_start' =>'##field_st_point_value##'
# ,'t_cable' =>'##field_marka_kabelay_value##'
# ,'t_number' =>'##field_agreement_number_value##'
# ,'t_summ' =>'##field_invoice_sum_value##'

# );
    category = nil
    if params[:t_id] && request.remote_ip == "195.54.215.98"
      t_id = params[:t_id].to_i
      category = 86 # временно
      case params[:t_type].to_i
      when 10
      when 20
        category = 87
      when 30
      when 40
      when 50
      when 60
      end
      

      if @report=Report.find(:first, :conditions =>"tracker_id = #{t_id}")
        respond_to do |format|
          format.json { render :json => {:error => "Отчет с данным tracker_id =#{t_id.to_s}  уже существует: № #{@report.id.to_s}" }}
        end 
      else
        @report = Report.new(:department => 'underground', :date => Date.today, :login_from => params[:t_start], :name => params[:t_end], :tracker_id => params[:t_id], :category => category, :com_stay_work => params[:t_cable], :status => 0, :total_sum_comment => params[:t_number], :total_sum_get_money => params[:t_summ])
      jsn = { }
      if @report.save
        jsn[:id] = @report.id
      else
        errors = ""
        @report.errors.each_full{ |msg| errors += msg + " "}
        jsn[:error] = errors
      end
      respond_to do |format|
        format.json { render :json => jsn}
      end 
    end
        
    elsif @boss # UNCOMMENT

      # else
      @report = Report.new(:department => 'underground', :date => Time.now, :category => Category.active.underground.first.id, :dhcp_login => 'new', :status => 0)
    @pricelist = Division.underground.pricelist.with_category(@report.category) if @report

    else  # UNCOMMENT
      flash[:error] = "Новые отчеты следует создавать из трекера!"
      redirect_to :action => 'index'
    end

  end

  def create
    @report = Report.new(params[:report])
    @report.department = 'underground'
    @report.save
    if @report.new_record?
      flash.now[:error] =  (@report.errors.each_full { |msg| puts msg }).to_s
    end
    respond_to do |format|
      unless flash.size > 0
        flash[:notice] = 'Запись обновлена'
        format.html { redirect_to undergrounds_path(:filter_month => @report.date.to_date.month, :filter_year => @report.date.to_date.year)}
        format.xml  { head :ok }
      else
        @pricelist = Division.underground.pricelist.personnel.with_category(@report.category)
        @top_works = DoneWork.top_works(@report)#@pricelist.select{|i| [87, 88, 307, 308, 283, 42].include? i.id}
        @pricelist = @top_works + (@pricelist - @top_works)
        format.html { render :action => "new", :report => @report }
      end
    end
  end


  def edit
    @report = Report.find params[:id]
  end

  def update
    @report = Report.find(params[:id])
    respond_to do |format|
      if @boss || @report.status == 0
        if @report.update_attributes(params[:report])
        flash[:notice] = 'Запись обновлена'
        format.html { redirect_to undergrounds_path(:filter_month => @report.date.to_date.month, :filter_year => @report.date.to_date.year)}
        format.xml  { head :ok }
        else
          flash.now[:error] = @report.errors.each_full { |msg| puts msg }
          format.html { render :action => "edit" }
          format.xml  { render :xml => @report.errors, :status => :unprocessable_entity }
        end
      else
        flash[:error] = 'У вас недостаточно прав для изменения отчета'
      end
    end
  end


  def destroy
    @report =   Report.find(params[:id])
    if @boss || @report.status == 0
      if @report.destroy
        flash[:notice] = 'Отчет № ' + params[:id] + ' был удален!'
      else
        messages = ''
        flash[:error] = @report.errors.each_full {|msg| messages += msg + "<br/>"}
      end
    else
      flash[:error] = "Отчет был переведен в статус #{@report.status_name}, правка возможна только superuser."
    end

    respond_to do |format|
      format.html { redirect_to undergrounds_path(:filter_month => @report.date.to_date.month, :filter_year => @report.date.to_date.year)}
    end
  end


  def change_price
    if params[:id].to_i != 0
      @report = Report.find params[:id]
#      @report.done_works.destroy_all
    else
      @report = Report.new
      @report.department = 'mod'
    end
    @report.category =  params[:type]
    @pricelist = Division.underground.pricelist.with_category(@report.category) if @report

    
    render :update do |page|
      page.replace_html  'pricelist_table', :partial => 'pricelist', :collection => @pricelist, :locals =>{:done_works => @report.done_works}
      page.call "ChangeMaterials"
    end
  end


  
  def stats
    if params[:date_from].to_s != ""
      @date_from = params[:date_from].to_date
    else
      @date_from = Date.today.beginning_of_month
    end
    if params[:date_to].to_s != ""
      @date_to = params[:date_to].to_date
    else
      @date_to = Date.today.end_of_month
    end

    @page_title = 'Статистика'
    @reports = Report.for_department('underground').in_period(@date_from, @date_to).with_category(params[:filter_worktype]).with_status(params[:filter_status]).with_empl(params[:filter_empl])
    @empls = @reports.map{ |i| i.done_employees.map{|i| i.employee}}.flatten.uniq
    @done_employees = @reports.map{ |i| i.done_employees}.flatten
  end



  private

  def set_var
    @employee = Employee.find(:all, :conditions => "division_id = 676")
    Employee.current_user = Employee.find(session[:user_id]) unless session[:user_id].nil?
    $department = 'underground'
    $department_id = '183'
    cookies[:sys_dep] = { :value => $department }
    @current_user = Employee.current_user
    @boss = (@current_user.accesses.for_department('underground').size > 0 && @current_user.accesses.for_department('underground').first.access_superuser == 1)
    
  end


  def get_reports
    @employees = Division.mod.employees.working
    if (params[:filter_month] && params[:filter_month] != '' && params[:filter_year])
      month = params[:filter_month].to_s
      year = params[:filter_year].to_s
    else
      month = Date.today.month.to_s
      year = Date.today.year.to_s
    end
    if params[:filter_day] && params[:filter_day] != ""
      @date = (month +'/'+params[:filter_day]+'/' + year).to_date
      date_from = @date
      date_to = @date
    else
      @date = (month +'/01/' + year).to_date
      date_from = @date
      date_to = @date.end_of_month
    end

    if @boss || @topologist
      @filter_empl =  params[:filter_empl]
    else
      @filter_empl = @current_user.id
    end

   
    cond = []
    cond << "r.department = 'underground'"
    if @filter_empl != '' && @filter_empl != nil
      cond << "r.id IN (SELECT de.report_id FROM done_employees de WHERE de.empl_id = #{@filter_empl})"
    end

    if params[:works] && params[:works].size > 0
      cond << "dw.work_id IN (#{params[:works].join(', ')})"
    end
    cond << "status = #{params[:filter_status]}" if params[:filter_status] && params[:filter_status] != '5'
    cond << "r.category = #{params[:filter_worktype]}" if params[:filter_worktype] && params[:filter_worktype] != ''
    if params[:topology_map] && !params[:topology_map].blank?
      cond << "r.topology_map = #{params[:topology_map].to_bool}"
    end
    cond = cond.join(" AND ")
    ActiveRecord::Base.connection.execute("SET group_concat_max_len = 2048;")
      @reports = 
      Report.find_by_sql(
                           "SELECT GROUP_CONCAT(DISTINCT CONCAT('<li>', done_employees.empl_name, '  (', done_employees.sum, '<font class=currency> руб.</font>)</li>') SEPARATOR ' ') as empls,
                                   GROUP_CONCAT(DISTINCT CONCAT('<li>', #{DoneMaterial.inst_type_for_sql}, ': ', dm.material_name, ' - ', dm.count, '</li>') SEPARATOR ' ') as mats, 
                                   GROUP_CONCAT(DISTINCT CONCAT('<li>', IFNULL(w.name, p.name), ' - ', dw.count, '</li>') SEPARATOR ' ') as wrks,
                                   IF((r.get_money_sum = 0 OR r.get_money_sum = NULL), '', CONCAT('<li>', 'НЕСТАНДАРТНАЯ РАБОТА: ', r.com_conflicts, ' - ', r.get_money_sum, '</li>') ) as not_standart_wrks, 
                                                        IF((r.request_id IS NULL), '', IF((r.request_closed IS TRUE), 'Закрыт', 'Открыт')) as req_status, 
                            r.id as id, r.request_id, r.name, r.date, r.sum, r.status, ct.name as cat_n, r.weather_temp, r.com_imperfection, r.com_stay_work as comment, ed.login as ed_name, r.topology_map topology_map, r.request_bonus_sum, r.topology_problem_tracker_id
                               FROM reports r 
                                    LEFT JOIN done_employees on done_employees.report_id = r.id 
                                    LEFT JOIN pricelist.pl_people ed on r.update_user_id = ed.id 
                                    LEFT JOIN done_materials dm ON dm.report_id = r.id AND (dm.inst_type != 6 OR dm.pay_type != 4)
                                    LEFT JOIN category ct ON ct.id = r.category 
                                    LEFT JOIN done_works dw ON dw.report_id = r.id
                                    LEFT JOIN works AS w ON dw.work_id=w.id && dw.pricelist=0
                                    LEFT JOIN pricelist.pl_items AS p ON dw.work_id=p.id && dw.pricelist=1
                                         WHERE DATE(r.date) BETWEEN DATE('#{date_from}') AND DATE('#{date_to}')  AND r.closed_at IS NULL AND #{cond}
                                               GROUP BY r.id ORDER BY r.request_id, r.date,r.name")      
  end


end
