import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormControl, FormGroup, Validators} from '@angular/forms';
import {HttpClient, HttpEvent, HttpEventType, HttpRequest, HttpResponse} from '@angular/common/http';
import {NzMessageService, NzModalService, UploadXHRArgs} from 'ng-zorro-antd';
import {Router} from '@angular/router';
import {LocalStorageService} from '../../../services/local-storage.service';
import {environment} from '../../../../environments/environment';
import {ADMIN_INFO_OBJECT} from '../../../services/local-storage.namespace';


@Component({
  selector: 'app-cms-category-module',
  templateUrl: './cms-category-module.component.html',
  styleUrls: ['./cms-category-module.component.less']
})
export class CmsCategoryModuleComponent implements OnInit {
  // 定义表单
  validateForm: FormGroup;
  // 搜索按钮等待特效
  isLoadingSearch = false;
  // 模板名称
  title = '';
  // 状态搜索
  selectedValueSearch = '';
  // 查询数组
  requestData = [];
  // 查询数组等待特效
  loading = true;
  // 请求页码
  pageIndex = 1;
  // 请求条数
  pageSize = 10;
  // 查询总条数
  total = 0;
  nodes = [];
  // expandKeys = [];
  // 选择的分类ID
  categoryId: '';
  isVisible = false;
  isOkLoading = false;
  isOkEditLoading = false;
  isLoadingDelete = false;
  isVisibleEdit = false;
  WEB_SERVE_URL;
  FILE_URL;
  fileList = [];
  modulePath = '';
  cmsCategoryModule = {
    id : '',
    categoryId : '',
    categoryCode: '',
    moduleName : '',
    moduleDesc : '',
    modulePath : '',
    status : '',
    createTime : '',
    opId : ''
  };
    // tslint:disable-next-line:variable-name
  BTN_cmscategorymodule_add = 0;
  // tslint:disable-next-line:variable-name
  BTN_cmscategorymodule_edit = 0;
  // tslint:disable-next-line:variable-name
  BTN_cmscategorymodule_delete = 0;
  // tslint:disable-next-line:variable-name
  BTN_cmscategorymodule_up_down = 0;
  // 重置
  resetForm(): void {
    this.title = '';
    this.selectedValueSearch = '';
  }
  constructor(
    private fb: FormBuilder,
    private http: HttpClient, // http请求
    private message: NzMessageService, // 信息提示
    private router: Router,
    private store: LocalStorageService , // 请求缓存
    private modalService: NzModalService // 对话框
  ) {
      this.WEB_SERVE_URL = environment.baseUrl;
      this.FILE_URL = environment.imageUrl;
  }

  ngOnInit() {
    // tslint:disable-next-line:prefer-for-of
    for (let i = 0; i < this.store.get(ADMIN_INFO_OBJECT)['buttonList']  .length; i++) {
      if (this.store.get(ADMIN_INFO_OBJECT)['buttonList'][i].permissionCode === 'BTN_cmscategorymodule_add' ) {
        this.BTN_cmscategorymodule_add = 1;
      }
      if (this.store.get(ADMIN_INFO_OBJECT)['buttonList'][i].permissionCode === 'BTN_cmscategorymodule_edit' ) {
        this.BTN_cmscategorymodule_edit = 1;
      }
      if (this.store.get(ADMIN_INFO_OBJECT)['buttonList'][i].permissionCode === 'BTN_cmscategorymodule_delete' ) {
        this.BTN_cmscategorymodule_delete = 1;
      }
      if (this.store.get(ADMIN_INFO_OBJECT)['buttonList'][i].permissionCode === 'BTN_cmscategorymodule_up_down' ) {
        this.BTN_cmscategorymodule_up_down = 1;
      }
    }
    // // 获取登录人 角色类型，查询分类树
    // console.log(this.store.get(DATA)['secRole'].roleType);
    this.findCategoryTree();
    // 调用请求方法
    this.getRequest();
    // 判断表单
    this.validateForm = this.fb.group({
      moduleName: [null, [Validators.required]],
      categoryId: [null, [Validators.required]],
      remark: [null],
    });
  }
  // 请求列表
  getRequest(reset: boolean = false) {
    this.loading = false;
    if (reset) {
      this.pageIndex = 1;
    }
    if (this.selectedValueSearch == null) {
      this.selectedValueSearch = '';
    }
    this.http.get(this.WEB_SERVE_URL + '/cmsCategoryModule/getListCategoryModule?pageNum=' + this.pageIndex + '&pageSize=' + this.pageSize + '&moduleName=' + this.title + '&status=' + this.selectedValueSearch).subscribe(data => {
      console.log(data);
      if (data['return_code'] === '000000') {
        this.requestData = data['return_data'].list;
        this.total = data['return_data'].total;
        this.isLoadingSearch = false;
      } else {
        this.message.create('error', data['return_msg']);
      }
    });
  }
  // 查询分类树
  findCategoryTree() {
    this.http.get(this.WEB_SERVE_URL + '/cmsCategory/getCategoryTree').subscribe(data => {
      if (data['return_code'] === '000000') {
        this.nodes = data['return_data'];
        if (this.nodes.length !== 0) {
          this.generateComment(this.nodes);
        } else {
          this.nodes = [];
        }
      } else {
        this.message.create('error', data['return_msg']);
      }
    });
  }
  // 搜索
  getSearch() {
    this.getRequest();
  }
  // 递归分类树
  generateComment(data) {
    for (const i in data) {
      if (data[i].nodes == null) {
        const item  = {
          isLeaf: true,
          title: data[i].text,
          key: data[i].id,
          children: data[i].nodes,
        };
        data[i] = item;
      } else {
        const item  = {
          isLeaf: false,
          title: data[i].text,
          key: data[i].id,
          children: data[i].nodes,
        };
        data[i] = item;
        this.generateComment(data[i].children);
      }
    }
    this.nodes = data;
    console.log(this.nodes);
  }
  emptyForm(e: MouseEvent): void {
    e.preventDefault();
    this.validateForm.reset();
    // tslint:disable-next-line:forin
    for (const key in this.validateForm.controls) {
      this.validateForm.controls[key].markAsPristine();
      this.validateForm.controls[key].updateValueAndValidity();
    }
  }
  goAddShow() {
    this.isVisible = true;
  }
  // 确定添加按钮
  handleOk(value: any): void {
    console.log('确认添加');
    if (this.categoryId == null || this.categoryId === '' || this.categoryId === undefined) {
      this.message.create('error', `请选择内容分类！`);
      return;
    }
    if (value.moduleName == null || value.moduleName === '') {
      this.message.create('error', `请填写模板名称！`);
      return;
    }
    if (this.modulePath == null || this.modulePath === '' || this.fileList.length === 0) {
      this.message.create('error', `请上传模板！`);
      return;
    }
    // 定义请求数据
    const params = {
      categoryId: this.categoryId,
      moduleDesc: value.remark,
      moduleName: value.moduleName,
      modulePath: this.modulePath
    };
    this.isOkLoading = true;
    this.http.post(this.WEB_SERVE_URL + '/cmsCategoryModule/addCategoryModule', params).subscribe(data => {
      if (data['return_code'] === '000000') {
        this.message.create('success', `新增成功！`);
        this.getRequest();
        this.isVisible = false;
        this.empty();
      } else {
        this.message.create('warning', data['return_msg']);
      }
      setTimeout(() => {
        this.isOkLoading = false;
      }, 1000);
    }, error => {
      this.isOkLoading = false;
      this.message.create('error', `未知错误！`);
    });
  }
  // 分类树选择
  onChange($event: string): void {
    console.log($event);
  }
  // 取消按钮
  handleCancel(): void {
    this.isVisible = false;
    this.fileList = [];
    this.modulePath = '';
  }
  // 显示修改
  goDetails(id) {
    if (id == null || id === '' || id === undefined) {
      this.message.create('error', `请选择要编辑的模板！`);
      return;
    }
    this.findModuleView(id);
    this.isVisibleEdit = true;
  }
  // 修改确定按钮
  handleOkEdit(value: any) {
    console.log('修改确认');
    console.log(this.cmsCategoryModule);
    if (this.cmsCategoryModule.categoryId == null || this.cmsCategoryModule.categoryId === '' || this.cmsCategoryModule.categoryId === undefined) {
      this.message.create('error', `请选择内容分类！`);
      return;
    }
    if (value.moduleName == null || value.moduleName === '') {
      this.message.create('error', `请填写模板名称！`);
      return;
    }
    if (this.modulePath == null || this.modulePath === '' || this.fileList.length === 0) {
      this.message.create('error', `请上传模板！`);
      return;
    } else {
      this.cmsCategoryModule.modulePath = this.modulePath;
    }
    this.isOkLoading = true;
    this.http.post(this.WEB_SERVE_URL + '/cmsCategoryModule/updateCategoryModule',  this.cmsCategoryModule).subscribe(data => {
      if (data['return_code'] === '000000') {
        this.message.create('success', `修改成功！`);
        this.getRequest();
        this.isVisibleEdit = false;
        this.empty();
      } else {
        this.message.create('warning', data['return_msg']);
      }
      setTimeout(() => {
        this.isOkLoading = false;
      }, 1000);
    }, error => {
      this.isOkLoading = false;
      this.message.create('error', `未知错误！`);
    });
  }
  // 修改取消按钮
  handleCancelEdit(): void {
    this.isVisibleEdit = false;
    this.fileList = [];
    this.modulePath = '';
  }
  // 模板上传设置
  customReq = (item: UploadXHRArgs) => {
    this.modulePath = ''; // 置空路径
    const formData = new FormData();
    formData.append('requestFile', item.file as any);
    formData.append('uploadType', 'cmsModule');
    // tslint:disable-next-line:no-non-null-assertion
    const req = new HttpRequest('POST', item.action!, formData, {
      reportProgress: true,
    });
    return this.http.request(req).subscribe(
      (event: HttpEvent<any>) => {
        console.log(event);
        if (event.type === HttpEventType.UploadProgress) {
          // tslint:disable-next-line:no-non-null-assertion
          if (event.total! > 0) {
            // tslint:disable-next-line:no-non-null-assertion
            (event as any).percent = (event.loaded / event.total!) * 100;
          }
          // tslint:disable-next-line:no-non-null-assertion
          item.onProgress!(event, item.file!);
        } else if (event instanceof HttpResponse) {
          // tslint:disable-next-line:no-non-null-assertion
          item.onSuccess!(event.body, item.file!, event);
          if (event.body.return_code === '000000') {
            this.modulePath = event.body.return_data[item.file.name];
          }
          console.log(this.modulePath);
        }
      },
      err => {
        // tslint:disable-next-line:no-non-null-assertion
        item.onError!(err, item.file!);
      }
    );
  }
  // 初始化数据
  empty() {
    this.categoryId = '';
    this.fileList = [];
    this.modulePath = '';
  }
  // 查询模板详情
  findModuleView(id) {
    if (id === undefined) {
      return;
    }
    if (id === null) {
      return;
    }
    if (id === '') {
      return;
    }
    this.http.get(this.WEB_SERVE_URL + '/cmsCategoryModule/getCategoryModuleById?id=' + id).subscribe( data => {
      if (data['return_code'] === '000000') {
        this.cmsCategoryModule = data['return_data'];
        console.log(this.cmsCategoryModule);
        this.fileList = [];
        this.modulePath = this.cmsCategoryModule.modulePath;
        const file = {
          uid: -1,
          name: data['return_data']['modulePath'],
          status: 'done',
          url: this.FILE_URL + data['return_data']['modulePath'],
          thumbUrl: this.FILE_URL + data['return_data']['modulePath'],
          sem: 'on',
        };
        this.fileList.push(file);
      } else {
        this.message.create('warning', data['return_msg']);
      }
    });
  }
  // 对话框启用
  showDeleteConfirmUp(id): void {
    this.modalService.confirm({
      nzTitle: '是否确定启用',
      nzOkText: '是',
      nzOnOk: () => this.enableModule(id),
      nzCancelText: '否',
    });
  }
  // 对话框停用
  showDeleteConfirmOut(id): void {
    this.modalService.confirm({
      nzTitle: '是否确定停用',
      nzOkText: '是',
      nzOnOk: () => this.disableModule(id),
      nzCancelText: '否',
    });
  }
  // 对话框删除
  showDeleteConfirmDelete(id): void {
    this.modalService.confirm({
      nzTitle: '是否确定删除',
      nzOkText: '是',
      nzOnOk: () => this.deleteModule(id),
      nzCancelText: '否',
    });
  }
  // 启用
  enableModule(ids) {
    // 定义请求数据
    const params = {
      id: ids,
      status: 1
    };
    this.http.post(this.WEB_SERVE_URL + '/cmsCategoryModule/updateStatusOfModule', params).subscribe(data => {
      if (data['return_code'] === '000000') {
        this.message.create('success', `启用成功！`);
        this.getRequest();
      } else {
        this.message.create('warning', data['return_msg']);
      }
    }, error => {
      this.isOkLoading = false;
      this.message.create('error', `未知错误！`);
    });
  }
  // 停用
  disableModule(ids) {
    // 定义请求数据
    const params = {
      id: ids,
      status: 2
    };
    this.http.post(this.WEB_SERVE_URL + '/cmsCategoryModule/updateStatusOfModule', params).subscribe(data => {
      if (data['return_code'] === '000000') {
        this.message.create('success', `停用成功！`);
        this.getRequest();
      } else {
        this.message.create('warning', data['return_msg']);
      }
    }, error => {
      this.isOkLoading = false;
      this.message.create('error', `未知错误！`);
    });
  }
  // 删除
  deleteModule(id) {
    if (id === undefined) {
      return;
    }
    if (id === null) {
      return;
    }
    if (id === '') {
      return;
    }
    this.http.get(this.WEB_SERVE_URL + '/cmsCategoryModule/delCategoryModule?id=' + id).subscribe( data => {
      if (data['return_code'] === '000000') {
        this.message.create('success', `删除成功！`);
        this.getRequest();
      } else {
        this.message.create('warning', data['return_msg']);
      }
    });
  }
}
