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

@Component({
  selector: 'app-cms-content-edit',
  templateUrl: './cms-content-edit.component.html',
  styleUrls: ['./cms-content-edit.component.less']
})
export class CmsContentEditComponent implements OnInit {
  config: any = {
    initialFrameHeight: 400,
  };
  // 详情id
  id;
  cmsContentView: any = {};
  // 定义表单
  validateForm: FormGroup;
  // 定义路径
  WEB_SERVE_URL;
  // 定义回调路径
  FILE_URL;
  nodes = [];
  // 列表图片上传等待
  loadingImg = false;
  // 列表图片
  listImg = null;
  constructor(
    private activatedRoute: ActivatedRoute,
    private fb: FormBuilder, // 表单
    private http: HttpClient, // http请求
    private message: NzMessageService, // 信息提示
  ) {
    this.WEB_SERVE_URL = environment.baseUrl;
    this.FILE_URL = environment.imageUrl;
    activatedRoute.queryParams.subscribe(queryParams => {
      this.id = queryParams.id;
      this.findContentView(queryParams.id);
    });
  }
  ngOnInit() {
    // 判断表单
    this.validateForm = this.fb.group({
      title: [null, [Validators.required]],
      recommend: [null],
      description: [null, [Validators.required]],
      ext1: [null],
      jumpType: [null],
      sortId: [null, [Validators.required]],
      content: [null],
      tag: [null],
    });
    // 获取登录人 角色类型，查询分类树
    let roleType = 1;
   /* if (0 === this.store.get(ADMIN_INFO_OBJECT)['bsCompany']['companyType']) {
      roleType = 1; // 运营平台
    } else if (1 === this.store.get(ADMIN_INFO_OBJECT)['bsCompany']['companyType']) {
      if (this.store.get(ADMIN_INFO_OBJECT)['bsCompany']['isService'] === true) {
        roleType = 3; // 服务机构
      } else {
        roleType = 2; // 普通企业
      }
    } else if (2 === this.store.get(ADMIN_INFO_OBJECT)['bsCompany']['companyType']) {
      roleType = 3; // 司法局
    } else if (3 == this.store.get(ADMIN_INFO_OBJECT)['bsCompany']['companyType']) {
      roleType = 4; // 行政部门
    }*/
    this.findCategoryTree(roleType);
  }
  // 查询内容详情
  findContentView(id) {
    this.http.get(this.WEB_SERVE_URL + '/cmsContent/getContentById?id=' + id).subscribe(data => {
      if (data['return_code'] === '000000') {
        data['return_data'].jumpType = String(data['return_data'].jumpType);
        this.cmsContentView = data['return_data'];
        this.listImg = data['return_data'].imgData;
      } else {
        this.message.create('error', data['return_msg']);
      }
    });
  }
  // 查询分类树
  findCategoryTree(roleType) {
    this.http.get(this.WEB_SERVE_URL + '/cmsCategory/getOwnCategoryTree?roleType=' + roleType).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']);
      }
    });
  }
  // 递归分类树
  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;
  }
  // 返回
  getBack() {
    history.back();
  }
  // 上传封面图片
  handleChange(info: any): void {
    this.loadingImg = true;
    if (info.file.response == null) {
      return;
    }
    this.loadingImg = false;
    if (info.file.response['return_code'] === '000000') {
    this.listImg = info.file.response['return_data'].join('');
    this.cmsContentView.imgData = this.listImg;
    } else {
      this.message.create('error', `上传失败！`);
    }
  }
  // 修改保存内容
  handleOk(value: any): void {
    // 校验必填
    if (this.cmsContentView.categoryId == null || this.cmsContentView.categoryId === '') {
      this.message.create('error', `请选择分类！`);
      return;
    }
    if (this.cmsContentView.title == null || this.cmsContentView.title === '') {
      this.message.create('error', `请填写内容标题！`);
      return;
    }
    if (this.cmsContentView.description == null || this.cmsContentView.description === '') {
      this.message.create('error', `请填写简要描述！`);
      return;
    }
/*    if (this.cmsContentView.imgData == null || this.cmsContentView.imgData == '') {
      this.message.create('error', `请上传封面！`);
      return;
    }*/
    if (this.cmsContentView.sortId == null || this.cmsContentView.sortId === '') {
      this.message.create('error', `请填写内容排序，越小越靠前！`);
      return;
    }
    this.http.post(this.WEB_SERVE_URL + '/cmsContent/updateContent', this.cmsContentView).subscribe(data => {
      if (data['return_code'] === '000000') {
        this.getBack();
        this.message.create('success', `修改成功！`);
      } else {
        this.message.create('warning', data['return_msg']);
      }
    }, error => {
      this.message.create('error', `未知错误！`);
    });
  }
}
