import { Component, OnInit } from '@angular/core';
import { FlexTableComponent } from '../../../shared/common/FlexTable.component';
import { FormBuilder, Validators } from '@angular/forms';
import { FrameRequest } from '../../../shared/frame/frame-request';
import { FrameFunction } from '../../../shared/frame/frame_function';
import * as _ from 'lodash';
import { AppComponent } from '../../..';
@Component({
  selector: 'app-res',
  templateUrl: './res.component.html',
  styleUrls: ['./res.component.scss']
})
export class ResComponent extends FlexTableComponent implements OnInit {

  QUERY_URL = "frame/res/page.htm";
  ADD_URL = "frame/res/add.htm";
  DELETE_URL = "frame/res/delete.htm";
  GET_URL = "frame/res/find.htm";
  EDIT_URL = "frame/res/edit.htm";
  LIST_URL = "frame/res/all.htm";

  private resArray = [];
  private viewStep: any;

  constructor(fb: FormBuilder) {
    super();
    this.viewStep = 'page';
    this.formModel = fb.group({
      res_name: [null, Validators.required],
      res_status: [null, Validators.required],
      res_type: [null, Validators.required],
      res_url: [null],
      res_order: [null, Validators.required],
      res_css: [null],
      res_pid: [null, Validators.required],
      res_desc: [null]
    });
  }

  ngOnInit() {
    FrameRequest.requestArray(this.LIST_URL, {}, (array) => {
	  this.resArray = array;
	  this.resArray.unshift({res_id:'0',res_name:'--无上级资源--'});
    });
  }
  goResEdit(editShowType: any, item?: any) {
    FrameFunction.UntouchedForm(this.formModel);
	//新增
	this.hideModal();
    if (!item || item.res_id === undefined) {
      if (!this.item) {
        this.item = {};
      }
	  this.formModel.reset();
      this.editShowType = editShowType;
    } else {
      FrameRequest.requestEntity(this.GET_URL, { resId: item.res_id }, (entity) => {
        setTimeout(() => {
          this.item = entity;
          this.editShowType = editShowType;
        }, 100)
      });
    }
  }

  saveRes() {
    if (!FrameFunction.validForm(this.formModel)) {
      return;
    }
    let url = this.item.res_id ? this.EDIT_URL: this.ADD_URL;
    if(_.isUndefined(this.item.res_id)) delete this.item.res_id;
    for (const key in this.item) {
      if(!this.item[key]) this.item[key] = '';
    }
    FrameRequest.requestEntity(url, this.item, async () => {
      AppComponent.GobalComponent.successMsg('信息保存成功');
      this.framePager.reload();
      if(this.bsModalWin)this.bsModalWin.hide();
      this.resetPage();
    });
  }

  deleteRes(item){
    AppComponent.confirm("确定删除",()=>{
      FrameRequest.request(this.DELETE_URL, {key:item.res_id}, () => {
        AppComponent.GobalComponent.successMsg('数据删除成功');
        this.framePager.reload();
      });
    });
  }
}
