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

@Component({
  selector: 'app-cms-content-add',
  templateUrl: './cms-content-add.component.html',
  styleUrls: ['./cms-content-add.component.less']
})
export class CmsContentAddComponent implements OnInit {
  config: any = {
    initialFrameHeight: 400,
  };
  // 判断是否为编辑 or  添加
  editFlag = 0;
  // 详情id
  id;
  // 定义表单
  validateForm: FormGroup;
  // 定义路径
  WEB_SERVE_URL;
  // 定义回调路径
  FILE_URL;
  // 提交等待
  isOkLoading = false;
  // 选择分类
  category = '';
  /** 分类树数据 **/
  nodes = [];
  // 列表图片上传等待
  loadingImg = false;
  // 列表图片
  listImg = null;
  // 附件类型
  patchTypeCheck = '0';
  // 附件返回地址
  patchPath = '';
  // 是否有附属信息
  hasPatch = 0;
  // 允许上传的文件类型
  annexForm: FormGroup;   /** 定义附件表单 **/
  isVisible = false;   /** 是否弹出添加 **/
  fileList = [];
  // 上传的后缀名
  suffix = '';
  // 允许上传的文件类型
  imageSuffix = [
    'jpg',
    'jpeg',
    'png',
    'jif',
    'dwg',
    'dxf',
    'jp2',
    'jpe',
    'svf',
    'tif',
    'tiff',
  ];
  audioSuffix = [
    '3gpp',
    'ac3',
    'mp2',
    'mp3',
    'asf',
    'cda',
    'wav',
    'wma',
    'mid',
    'ra',
    'rma',
    'mod',
  ];
  videoSuffix = [
    '3gpp',
    'mp2',
    'mp4',
    'mpeg',
    'mpg',
    'avi',
    'rmvb',
    'flv',
    '3pg',
    'rm',
    'mov',
    'wmv',
    'mkv',
    'f4v',
    'm4v',
  ];
  applicationSuffix = [
    'asf',
    'doc',
    'dot',
    'dtd',
    'htm',
    'html',
    'css',
    'csv',
    'js',
    'json',
    'mpp',
    'ogg',
    'pdf',
    'pot',
    'pps',
    'ppt',
    'rtf',
    'txt',
    'wdb',
    'wps',
    'xhtml',
    'xlc',
    'xlm',
    'xls',
    'xlt',
    'xlw',
    'xml',
    'zip',
    'docx',
    'xlsx',
    'pptx',
    'sql'
  ];
  // 保存附件集合
  suffixList = [];
  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.editFlag = queryParams.editFlag;
    });
  }
  ngOnInit() {
    // 判断表单
    this.validateForm = this.fb.group({
      title: [null, [Validators.required]],
      recommend: [null],
      description: [null, [Validators.required]],
      sortId: [null, [Validators.required]],
      content: [null],
      jumpType: [null],
      ext1: [null],
      tag: [null],
    });
    this.annexForm = this.fb.group({
      patchName: [null, [Validators.required]],
      patchDesc: [null],
      patchType: [null, [Validators.required]],
      sort: [null, [Validators.required]],
    });
    // 获取登录人 角色类型，查询分类树
    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);
  }
  // 查询分类树
  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;
    console.log(this.nodes);
  }
  // 返回
  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('');
      /** 关闭等待 **/
    } else {
      this.message.create('error', `上传失败！`);
    }
  }

  emptyForm(e: MouseEvent): void {
    e.preventDefault();
    this.annexForm.reset();
    for (const key in this.annexForm.controls) {
      this.annexForm.controls[key].markAsPristine();
      this.annexForm.controls[key].updateValueAndValidity();
    }
  }
  /** 弹出添加弹框 **/
  goAddShow() {
    this.isVisible = true;
  }
  // 取消按钮
  handleCancel(): void {
    this.isVisible = false;
    this.patchPath = '';
    this.fileList = [];
    /** 隐藏弹框 **/
  }
  // 附件类型选择
  getChange(event) {
    if (event != null) {
      this.patchTypeCheck = event;
      console.log(event);
    }
  }
  // 附件上传设置
  customReq = (item: UploadXHRArgs) => {
    this.patchPath = ''; // 置空路径
    const formData = new FormData();
    formData.append('requestFile', item.file as any);
    formData.append('uploadType', 'cmsPatch');
    console.log(item);
    const req = new HttpRequest('POST', item.action!, formData, {
      reportProgress: true,
    });
    console.log(req);
    return this.http.request(req).subscribe(
      (event: HttpEvent<any>) => {
        console.log(event);
        if (event.type === HttpEventType.UploadProgress) {
          if (event.total! > 0) {
            (event as any).percent = (event.loaded / event.total!) * 100;
          }
          item.onProgress!(event, item.file!);
        } else if (event instanceof HttpResponse) {
          item.onSuccess!(event.body, item.file!, event);
          if (event.body.return_code === '000000') {
            this.patchPath = event.body.return_data[item.file.name];
            this.suffix = this.patchPath.split('.')[this.patchPath.split('.').length - 1];
          }
          console.log(this.patchPath);
          console.log(this.fileList);
        }
      },
      err => {
        item.onError!(err, item.file!);
      }
    );
  }
  // 附件弹窗确定添加按钮
  handlePatchOk(value: any): void {
    // 校验类型选择与必填
    if (value.patchName == null || value.patchName == '') {
      this.message.create('error', `请填写附件名称！`);
      return;
    }
    if (value.sort == null || value.sort == '') {
      this.message.create('error', `请填写附件排序，越小越靠前！`);
      return;
    }
    if (value.patchType == '1') {
      if (this.imageSuffix.indexOf(this.suffix) == -1) {
        this.message.create('error', `请上传图片类型的附件！`);
        return;
      }
    } else if (value.patchType == '2') {
      if (this.audioSuffix.indexOf(this.suffix) == -1) {
        this.message.create('error', `请上传音频类型的附件！`);
        return;
      }
    } else if (value.patchType == '3') {
      if (this.videoSuffix.indexOf(this.suffix) == -1) {
        this.message.create('error', `请上传视频类型的附件！`);
        return;
      }
    } else if (value.patchType == '4') {
      if (this.applicationSuffix.indexOf(this.suffix) == -1) {
        this.message.create('error', `请上传文档类型的附件！`);
        return;
      }
    } else if (value.patchType == '5') {
    } else {
      this.message.create('error', `请选择附件类型！`);
      return;
    }
    if (this.patchPath == null || this.patchPath == '') {
      this.message.create('error', `请上传附件！`);
      return;
    }
    // 定义附件数据
    const params = {
      'patchName': value.patchName,
      'patchDesc': value.patchDesc,
      'patchType': value.patchType,
      'patchPath': this.patchPath,
      'source': 1,
      'sort': value.sort,
      'suffixName': this.suffix,
      'addTime': new Date()
    };
    this.suffixList.push(params);
    this.isVisible = false;
    this.isOkLoading = false;
    this.fileList = [];
    this.patchTypeCheck = '0';
    this.message.create('success', `上传成功！`);
    console.log(this.suffixList);
  }
  // 移除附件
  deletePatch(i) {
    this.suffixList.splice(i, 1);
  }
  // 保存内容
  handleOk(value: any): void {


    // 校验必填
    if (this.category == null || this.category == '') {
      this.message.create('error', `请选择分类！`);
      return;
    }
    if (value.title == null || value.title == '') {
      this.message.create('error', `请填写内容标题！`);
      return;
    }
    if (value.description == null || value.description == '') {
      this.message.create('error', `请填写简要描述！`);
      return;
    }
/*    if (this.listImg == null || this.listImg == '') {
      this.message.create('error', `请上传封面！`);
      return;
    }*/
    if (value.sortId == null || value.sortId == '') {
      this.message.create('error', `请填写内容排序，越小越靠前！`);
      return;
    }
    if (this.suffixList.length != 0) {
      this.hasPatch = 1;
    }
    // 定义附件数据
    const params = {
      'cmsContent': {
        'title': value.title,
        'categoryId': this.category,
        'description': value.description,
        'content': value.content,
        'tag' : value.tag,
        'jumpUrl' : value.jumpUrl,
        'ext1' : value.ext1,
        'jumpType' : value.jumpType,
        'hasPatch': this.hasPatch,
        'imgSource': 1,
        'status': 1,
        'imgData': this.listImg,
        'sortId': value.sortId,
        'recommend': value.recommend
      },
      'patches': this.suffixList
    };
    /** 确定等待 **/
    this.http.post(this.WEB_SERVE_URL + '/cmsContent/addContent', params).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', `未知错误！`);
    });
  }
}
