import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {environment} from '../../../../environments/environment';
import {MerchantService} from '../../../services/merchant.service';
import {NzMessageService, NzUploadFile} from 'ng-zorro-antd';
import {ActivatedRoute} from '@angular/router';
import {ValidatorsService} from '../../../services/validators.service';
import {CompanyService} from '../../../services/company.service';

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-company-edit',
  templateUrl: './company-edit.component.html',
  styleUrls: ['./company-edit.component.scss']
})
export class CompanyEditComponent implements OnInit {

  validateForm!: FormGroup;
  data: any;
  editFlag = false;
  id: number;
  passwordVisible = false;
  logoFile = [];
  WEB_SERVE_URL = environment.baseUrl;
  previewImage: string | undefined = '';
  previewVisible = false;
  regionId;
  userId: number;
  time;
  constructor(
      private fb: FormBuilder,
      private company: CompanyService,
      private message: NzMessageService, // 信息提示
      private activatedRoute: ActivatedRoute,
  ) {
  }

  ngOnInit(): void {
    this.activatedRoute.queryParams.subscribe(queryParams => {
      if (queryParams.companyId != null) {
        this.editFlag = true;
        this.id = queryParams.companyId;
        this.getDetails(queryParams.companyId);
      }
    });
    this.validateForm = this.fb.group({
      loginName: [null, [Validators.required, ValidatorsService.maxLength(20)]],
      password: [null, [Validators.required]],
      regionId: [null],
      name: [null, [Validators.required, ValidatorsService.maxLength(50)]],
      logo: [null],
      regionName: [null],
      company: {},
      user: {},
    });
  }

  // 返回
  getBack() {
    history.back();
  }

  // 重置
  public resetForm(): void {
    this.validateForm.reset();
  }

  // 课程保存
  public getSave(): void {
    // tslint:disable-next-line:forin
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
      if (this.validateForm.controls[i].errors != null) {
        this.message.error('必填项不能为空');
        return;
      }
    }

    if (this.logoFile.length !== 0) {
      if (this.logoFile[0]['response'] != null) {
        this.validateForm.value.logo = this.logoFile[0]['response']['return_data'][0];
      } else {
        this.validateForm.value.logo = this.logoFile[0].name;
      }
    }
    this.validateForm.value['company']['name'] = this.validateForm.value.name;
    this.validateForm.value['company']['regionId'] = this.regionId;
    this.validateForm.value['company']['logo'] = this.validateForm.value.logo;
    this.validateForm.value['user']['loginName'] = this.validateForm.value.loginName;
    this.validateForm.value['user']['password'] = this.validateForm.value.password;
    if (this.editFlag) {
      this.validateForm.value['company'].id = this.id;
      this.validateForm.value['company'].status = 1;
      this.validateForm.value['company'].createTime = this.time;
      this.validateForm.value['user'].id = this.userId;
      this.company.updateCompany(this.validateForm.value, data => {
        if (data['return_code'] === '000000') {
          this.getBack();
          this.message.success('修改成功');
        } else {
          this.message.create('error', '修改失败');
        }
      });
    } else {

      this.company.addCompanyAndUser(this.validateForm.value, data => {
        console.log(data);
        if (data['return_code'] === '000000') {
          this.getBack();
          this.message.success('添加成功');
        } else {
          this.message.create('error', data['return_msg']);
        }
      });
    }
  }

  // 图片查看
  handlePreview = async (file: NzUploadFile) => {
    if (!file.url && !file.preview) {
      // tslint:disable-next-line:no-non-null-assertion
      file.preview = await getBase64(file.originFileObj!);
    }
    this.previewImage = file.url || file.preview;
    this.previewVisible = true;
  }

  public getDetails(id) {
    this.company.companyView(id, data => {
      if (data['return_code'] === '000000') {
        data['return_data']['company'].loginName = data['return_data'].user.loginName;
        data['return_data']['company'].password = data['return_data'].user.password;
        this.regionId = data['return_data'].company.regionId;
        this.userId = data['return_data'].user.id;
        this.time = data['return_data'].company.createTime;
        if (data['return_data']['company']['logo'] != null && data['return_data']['company']['logo'] !== '') {
          const logo = String(data['return_data']['company']['logo']);
          const logoArray = [];
          logoArray.push(
              {
                uid: 1,
                name: logo,
                status: 'done',
                url: environment.imageUrl + logo
              });
          this.logoFile = logoArray;
        }
        this.validateForm.patchValue(data['return_data']['company']);
      } else {
        this.message.create('error', data['return_msg']);
      }
    });
  }

  regionChange(regionId) {
    this.regionId = regionId;
  }
}
