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} from 'ng-zorro-antd';
import {ActivatedRoute} from '@angular/router';
import {SystemService} from '../../../services/system.service';

@Component({
  selector: 'app-sinopec-edit',
  templateUrl: './sinopec-edit.component.html',
  styleUrls: ['./sinopec-edit.component.scss']
})
export class SinopecEditComponent implements OnInit {

  validateForm!: FormGroup;
  data: any;
  editFlag = false;
  id: number;
  WEB_SERVE_URL = environment.baseUrl;

  constructor(
      private fb: FormBuilder,
      private system: SystemService,
      private message: NzMessageService, // 信息提示
      private activatedRoute: ActivatedRoute,
  ) {
  }

  ngOnInit(): void {
    this.activatedRoute.queryParams.subscribe(queryParams => {
      if (queryParams.sinopecId != null) {
        this.editFlag = true;
        this.id = queryParams.sinopecId;
        this.getDetails(queryParams.sinopecId);
      }
    });
    this.validateForm = this.fb.group({
      appId: [null, [Validators.required]],
      appSecret: [null, [Validators.required]],
      code: [null, [Validators.required]],
      signkey: [null, [Validators.required]],
      name: [null, [Validators.required]],
    });
  }

  // 返回
  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.editFlag) {
      this.validateForm.value.id = this.id;
      this.system.updateMerchant(this.validateForm.value, data => {
        if (data['return_code'] === '000000') {
          this.getBack();
          this.message.success('修改成功');
        } else {
          this.message.create('error', data['return_msg']);
        }
      });
    } else {
      this.system.insertMerchant(this.validateForm.value, data => {
        if (data['return_code'] === '000000') {
          this.getBack();
          this.message.success('添加成功');
        } else {
          this.message.create('error', data['return_msg']);
        }
      });
    }
  }



  public getDetails(id) {
    this.system.findById(id, data => {
      if (data['return_code'] === '000000') {
        this.validateForm.patchValue(data['return_data']);
      } else {
        this.message.create('error', data['return_msg']);
      }
    });
  }
}
