import {Component, OnInit, ViewChild} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {HttpClient} from '@angular/common/http';
import {NzFormatEmitEvent, NzMessageService, NzModalService, NzTreeComponent, UploadFile} from 'ng-zorro-antd';

import {LocalStorageService} from '../../../services/local-storage.service';
import {ADMIN_INFO_OBJECT} from '../../../services/local-storage.namespace';
import {environment} from '../../../../environments/environment';


function getBase64(file: File): Promise<string | ArrayBuffer | null> {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}

@Component({
  selector: 'app-cms-category',
  templateUrl: './cms-category.component.html',
  styleUrls: ['./cms-category.component.less']
})
export class CmsCategoryComponent implements OnInit {
  // @ts-ignore
  @ViewChild('nzTreeComponent') nzTreeComponent: NzTreeComponent;
  searchValue = '';
  imgLoading = false;
  previewImage: string | undefined = '';
  previewVisible = false;
  coverImgArray = [];
  WEB_SERVE_URL;
  FILE_URL;
  nodes = [];
  roles = [];
/*  checkOptions = [
    {label: '房管局', value: 1, checked: false},
    {label: '街道办', value: 2, checked: false},
    {label: '物业', value: 3, checked: false},
    {label: '小区', value: 4, checked: false},
    {label: '业委会', value: 5, checked: false}
  ];
  showCheck = [
    {label: '房管局', value: 1, checked: false},
    {label: '街道办', value: 2, checked: false},
    {label: '物业', value: 3, checked: false},
    {label: '小区', value: 4, checked: false},
    {label: '业委会', value: 4, checked: false}
  ];*/
  cmsCategory = {
    id: '',
    parentId: '',
    name: '',
    code: '',
    sort: '',
    coverImg: '',
    status: '',
    remark: '',
  };
  ext1 = {
    unitName: '',
    address: '',
    contact: '',
  };
  validateForm: FormGroup;
  isVisible = false;
  isOkLoading = false;
  isOkEditLoading = false;
  isLoadingDelete = false;
  isVisibleEdit = false;
  addHasImage = 0;
  // tslint:disable-next-line:variable-name
  BTN_cmscategory_add = 0;
  // tslint:disable-next-line:variable-name
  BTN_cmscategory_edit = 0;
  // tslint:disable-next-line:variable-name
  BTN_cmscategory_delete = 0;

  id;

  constructor(
    private http: HttpClient,
    private message: NzMessageService,
    private store: LocalStorageService,
    private fb: FormBuilder, // 表单
    private modalService: NzModalService, // 对话框
  ) {
  }

  ngOnInit() {
    this.WEB_SERVE_URL = environment.baseUrl;
    this.FILE_URL = environment.imageUrl;
    // 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_cmscategory_add') {
        this.BTN_cmscategory_add = 1;
      }
      if (this.store.get(ADMIN_INFO_OBJECT)['buttonList'][i].permissionCode === 'BTN_cmscategory_edit') {
        this.BTN_cmscategory_edit = 1;
      }
      if (this.store.get(ADMIN_INFO_OBJECT)['buttonList'][i].permissionCode === 'BTN_cmscategory_delete') {
        this.BTN_cmscategory_delete = 1;
      }
    }
    // 判断表单
    this.validateForm = this.fb.group({
      name: [null, [Validators.required]],
      code: [null, [Validators.required]],
      sort: [null, [Validators.required]],
      coverImg: [null],
      /*hasImage: [null, [Validators.required]],
      imageWidth: [null],
      imageHeight: [null],*/
      remark: [null],
    });
    this.goRequest();
  }

  goRequest() {
    this.http.get(this.WEB_SERVE_URL + '/cmsCategory/getCategoryTree').subscribe(data => {
      console.log(data);
      if (data['return_code'] === '000000') {
        this.nodes = data['return_data'];
        if (this.nodes.length !== 0) {
          this.generateComment(this.nodes);
        }
      } else {
        this.message.create('warning', 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;
  }

  nzEvent(event: NzFormatEmitEvent): void {
    this.roles = [];
    const selected = this.nzTreeComponent.getSelectedNodeList();
    if (selected.length === 0) {
      this.cmsCategory = {
        id: '',
        parentId: '',
        name: '',
        code: '',
        sort: '',
        coverImg: '',
        status: '',
        remark: '',
      };
      this.id = '';
    /*  this.showCheck = [
        {label: '房管局', value: 1, checked: false},
        {label: '街道办', value: 2, checked: false},
        {label: '物业', value: 3, checked: false},
        {label: '小区', value: 4, checked: false},
        {label: '业委会', value: 4, checked: false}
      ];*/
      this.ext1 = {
        unitName: '',
        address: '',
        contact: '',
      };
    } else {
      if (selected[0].key == null) {
        return;
      }
      this.id = selected[0].key;
      this.goCategory(selected[0].key);
    }
  }

  goCategory(id) {
    this.coverImgArray = [];
    if (id === undefined || id == null || id === '') {
      return;
    }
    this.http.get(this.WEB_SERVE_URL + '/cmsCategory/getCategoryById?id=' + id).subscribe(category => {
      if (category['return_code'] === '000000') {
        this.cmsCategory = category['return_data'];
        if (category['return_data'].coverImg != null && category['return_data'].coverImg != '') {
          this.coverImgArray = [{
            uid: '-1',
            name: category['return_data'].coverImg,
            status: 'done',
            url: this.FILE_URL + category['return_data'].coverImg
          }];
        }
        if (category['return_data']['ext1'] !== '' && category['return_data']['ext1'] !== null) {
          this.ext1 = JSON.parse(category['return_data']['ext1']);
        } else {
          this.ext1 = {
            unitName: '',
            address: '',
            contact: '',
          };
        }
        if (this.cmsCategory.parentId == null || this.cmsCategory.parentId === '' || this.cmsCategory.parentId === undefined || this.cmsCategory.parentId.length === 0) {
        /*  this.showCheck = [
            {label: '房管局', value: 1, checked: false},
            {label: '街道办', value: 2, checked: false},
            {label: '物业', value: 3, checked: false},
            {label: '小区', value: 4, checked: false},
            {label: '业委会', value: 4, checked: false}
          ];*/
          // 查询自己已分配的权限,然后勾选
          this.http.get(this.WEB_SERVE_URL + '/cmsCategory/getRolesOfCategory?id=' + id).subscribe(allot => {
            if (allot['return_code'] === '000000') {
              // tslint:disable-next-line:forin
            /*  for (const i in allot['return_data']) {
                for (const j in this.showCheck) {
                  if (allot['return_data'][i] === this.showCheck[j].value) {
                    this.showCheck[j].checked = true;
                    this.roles.push(this.showCheck[j].value);
                    console.log(this.roles);
                  }
                }
              }*/
            } else {
              this.message.create('warning', allot['return_msg']);
            }
          });
        } else {
          this.http.get(this.WEB_SERVE_URL + '/cmsCategory/getRolesOfCategory?id=' + this.cmsCategory.parentId).subscribe(parent => {
            if (parent['return_code'] === '000000') {
           /*   this.showCheck = [];
              // tslint:disable-next-line:forin
              for (const i in parent['return_data']) {
                if (parent['return_data'][i] === 1) {
                  const params = {
                    label: '中心平台',
                    value: 1,
                    disabled: true,
                    checked: false
                  };
                  this.showCheck.push(params);
                }
                if (parent['return_data'][i] === 2) {
                  const params = {
                    label: '企业',
                    value: 2,
                    disabled: true,
                    checked: false
                  };
                  this.showCheck.push(params);
                }
                if (parent['return_data'][i] === 3) {
                  const params = {
                    label: '服务机构',
                    value: 3,
                    disabled: true,
                    checked: false
                  };
                  this.showCheck.push(params);
                }
                if (parent['return_data'][i] === 4) {
                  const params = {
                    label: '行政部门',
                    value: 4,
                    disabled: true,
                    checked: false
                  };
                  this.showCheck.push(params);
                }
              }*/
              // 查询自己已分配的权限,然后勾选
              this.http.get(this.WEB_SERVE_URL + '/cmsCategory/getRolesOfCategory?id=' + id).subscribe(allot2 => {
                if (allot2['return_code'] === '000000') {
                  // tslint:disable-next-line:forin
                  /*for (const i in allot2['return_data']) {
                    for (const j in this.showCheck) {
                      if (allot2['return_data'][i] === this.showCheck[j].value) {
                        this.showCheck[j].checked = true;
                        this.roles.push(this.showCheck[j].value);
                        console.log(this.roles);
                      }
                    }
                  }*/
                } else {
                  this.message.create('warning', allot2['return_msg']);
                }
              });
            } else {
              this.message.create('warning', parent['return_msg']);
            }
          });
        }
      } else {
        this.message.create('warning', category['return_msg']);
      }
    });
  }

  goAddShow() {
    this.coverImgArray = [];
    if (this.id == null || this.id === '' || this.id.length === 0) {
      this.cmsCategory = {
        id: '',
        parentId: '',
        name: '',
        code: '',
        sort: '5',
        coverImg: '',
        status: '',
        remark: '',
      };
      this.ext1 = {
        unitName: '',
        address: '',
        contact: '',
      };
      // this.checkOptions = [
      //   {label: '中心平台', value: 1, checked: false},
      //   {label: '企业', value: 2, checked: false},
      //   {label: '服务机构', value: 3, checked: false},
      //   {label: '行政部门', value: 4, checked: false}
      // ];
    } else {
      this.findAddRoleType(this.id);
      this.cmsCategory = {
        id: '',
        parentId: '',
        name: '',
        code: '',
        sort: '5',
        coverImg: '',
        status: '',
        remark: '',
      };
      this.ext1 = {
        unitName: '',
        address: '',
        contact: '',
      };
    }
    this.isVisible = true;
  }

  // 确定添加按钮
  handleOk(value: any): void {
    if (value.name == null || value.name === '') {
      this.message.create('error', `请填写分类名称！`);
      return;
    }
    if (value.code == null || value.code === '') {
      this.message.create('error', `请填写分类编码！`);
      return;
    }
    if (value.sort == null || value.sort === '') {
      this.message.create('error', `请选择输入排序序号！`);
      return;
    }
/*    if (this.roles.length === 0) {
      this.message.create('error', `请选择分类权限！`);
      return;
    }*/
    let coverImgStr = null;
    for (let i = 0; i < this.coverImgArray.length; i++) {
      if (this.coverImgArray[i].response != null && this.coverImgArray[i].response != '') {
        coverImgStr = this.coverImgArray[i].response.return_data[0];
      } else {
        coverImgStr = this.coverImgArray[i].name;
      }
    }
    // 定义请求数据
    const params = {
      category: {
        name: value.name,
        code: value.code,
        parentId: this.id,
        sort: value.sort,
        coverImg: coverImgStr,
        remark: value.remark,
        ext1: JSON.stringify(this.ext1)
      },
      roles: [1]
    };
    this.isOkLoading = true;
    this.http.post(this.WEB_SERVE_URL + '/cmsCategory/addCategory', params).subscribe(data => {
      if (data['return_code'] === '000000') {
        this.message.create('success', `新增成功！`);
        this.goRequest();
        this.isVisible = false;
        this.addHasImage = 0;
        this.cmsCategory = {
          id: '',
          parentId: '',
          name: '',
          code: '',
          sort: '',
          coverImg: '',
          status: '',
          remark: '',
        };
        this.ext1 = {
          unitName: '',
          address: '',
          contact: '',
        };
     /*   this.checkOptions = [
          {label: '中心平台', value: 1, checked: false},
          {label: '企业', value: 2, checked: false},
          {label: '服务机构', value: 3, checked: false},
          {label: '行政部门', value: 4, checked: false}
        ];*/
        this.id = '';
      } else {
        this.message.create('warning', data['return_msg']);
      }
      setTimeout(() => {
        this.isOkLoading = false;
      }, 1000);
    }, error => {
      this.isOkLoading = false;
      this.message.create('error', `未知错误！`);
    });
  }

  // 取消按钮
  handleCancel(): void {
    this.isVisible = false;
  }

  resetForm(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();
    }
    this.addHasImage = 0;
  }

  // 显示修改
  goDetails() {
    if (this.cmsCategory.id.length === 0) {
      this.message.create('error', `请选择编辑的分类！`);
      return;
    }
    // tslint:disable-next-line:forin
 /*   for (const i in this.showCheck) {
      this.showCheck[i].disabled = false;
    }*/
    this.isVisibleEdit = true;
  }

// 修改确定按钮
  handleOkEdit(value: any) {
    // tslint:disable-next-line:forin
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
    if (value.name == null || value.name === '') {
      this.message.create('error', `请填写分类名称！`);
      return;
    }
    if (value.code == null || value.code === '') {
      this.message.create('error', `请填写分类编码！`);
      return;
    }
    if (value.sort == null || value.sort === '') {
      this.message.create('error', `请选择输入排序序号！`);
      return;
    }
/*    if (this.roles.length === 0) {
      this.message.create('error', `请选择分类权限！`);
      return;
    }*/
    let coverImgStr = null;
    for (let i = 0; i < this.coverImgArray.length; i++) {
      if (this.coverImgArray[i].response != null && this.coverImgArray[i].response != '') {
        coverImgStr = this.coverImgArray[i].response.return_data[0];
      } else {
        coverImgStr = this.coverImgArray[i].name;
      }
    }
    // 定义请求数据
    const params = {
      category: {
        id: this.cmsCategory.id,
        name: value.name,
        code: value.code,
        parentId: this.cmsCategory.parentId,
        sort: value.sort,
        coverImg: coverImgStr,
        status: this.cmsCategory.status,
        remark: value.remark,
        ext1: JSON.stringify(this.ext1)
      },
      roles: [1]
    };
    this.isOkLoading = true;
    this.http.post(this.WEB_SERVE_URL + '/cmsCategory/updateCategory', params).subscribe(data => {
      if (data['return_code'] === '000000') {
        this.message.create('success', `修改成功！`);
        this.goRequest();
        this.addHasImage = 0;
        this.isVisibleEdit = false;
        this.cmsCategory = {
          id: '',
          parentId: '',
          name: '',
          code: '',
          sort: '',
          coverImg: '',
          status: '',
          remark: '',
        };
        this.ext1 = {
          unitName: '',
          address: '',
          contact: '',
        };
       /* this.showCheck = [
          {label: '房管局', value: 1, checked: false},
          {label: '街道办', value: 2, checked: false},
          {label: '物业', value: 3, checked: false},
          {label: '小区', value: 4, checked: false},
          {label: '业委会', value: 4, checked: false}
        ];*/
      } else {
        this.message.create('warning', data['return_msg']);
      }
      setTimeout(() => {
        this.isOkLoading = false;
      }, 1000);
    }, error => {
      this.isOkLoading = false;
      this.message.create('error', `未知错误！`);
    });
  }

  // 修改取消按钮
  handleCancelEdit(): void {
    this.goCategory(this.id);
    this.isVisibleEdit = false;
  }

  // 删除提示
  showDeleteConfirm(id): void {
    if (id == null || id === '' || id === undefined) {
      this.message.create('error', `请选择删除的分类！`);
      return;
    }
    this.modalService.confirm({
      nzTitle: '您确定要删除吗?',
      nzOkText: '是',
      nzOkType: 'danger',
      nzOnOk: () => this.goDelete(id),
      nzCancelText: '否',
    });
  }

  // 删除
  goDelete(id) {
    this.isLoadingDelete = true;
    this.http.get(this.WEB_SERVE_URL + '/cmsCategory/delCategory?id=' + id).subscribe(data => {
      this.isLoadingDelete = false;
      if (data['return_code'] === '000000') {
        this.message.create('success', '删除成功');
        // 调用请求方法
        this.isVisible = false;
        this.addHasImage = 0;
        this.cmsCategory = {
          id: '',
          parentId: '',
          name: '',
          code: '',
          sort: '',
          coverImg: '',
          status: '',
          remark: '',
        };
        this.ext1 = {
          unitName: '',
          address: '',
          contact: '',
        };
        /*this.checkOptions = [
          {label: '房管局', value: 1, checked: false},
          {label: '街道办', value: 2, checked: false},
          {label: '物业', value: 3, checked: false},
          {label: '小区', value: 4, checked: false},
          {label: '业委会', value: 4, checked: false}
        ];
        this.showCheck = [
          {label: '房管局', value: 1, checked: false},
          {label: '街道办', value: 2, checked: false},
          {label: '物业', value: 3, checked: false},
          {label: '小区', value: 4, checked: false},
          {label: '业委会', value: 4, checked: false}
        ];*/
        this.id = '';
        this.goRequest();
      } else {
        this.message.create('error', data['return_msg']);
      }
    });
  }

  // 查询能分配的角色(上级已分配角色)
  findAddRoleType(id) {
    /*this.http.get(WEB_SERVE_URL + '/cmsCategory/getRolesOfCategory?id=' + id).subscribe(data => {
      if (data['return_code'] === '000000') {
        this.checkOptions = [];
        // tslint:disable-next-line:forin
        for (const i in data['return_data']) {
          if (data['return_data'][i] === 1) {
            const params = {
              label: '中心平台',
              value: 1,
              checked: false
            };
            this.checkOptions.push(params);
          }
          if (data['return_data'][i] === 2) {
            const params = {
              label: '企业',
              value: 2,
              checked: false
            };
            this.checkOptions.push(params);
          }
          if (data['return_data'][i] === 3) {
            const params = {
              label: '服务机构',
              value: 3,
              checked: false
            };
            this.checkOptions.push(params);
          }
          if (data['return_data'][i] === 4) {
            const params = {
              label: '行政部门',
              value: 4,
              checked: false
            };
            this.checkOptions.push(params);
          }
        }
      } else {
        this.message.create('warning', data['return_msg']);
      }
    });*/
  }

  // 是否包含图片
  getChange(event) {
    if (event === 1) {
      this.addHasImage = 1;
    } else if (event === 0) {
      this.addHasImage = 0;
    }
  }

  // 筛选出选中的角色类型
  allot(event) {
    console.log(event);
    this.roles = [];
    // tslint:disable-next-line:forin
    for (const checkbox in event) {
      console.log(checkbox);
      if (event[checkbox].checked) {
        this.roles.push(event[checkbox].value);
      }
    }
    console.log(this.roles);
  }

  handlePreview = async (file: UploadFile) => {
    console.log(file);
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj!);
    }
    this.previewImage = file.url || file.preview;
    this.previewVisible = true;
  };

}
