import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormGroup} from '@angular/forms';
import {NzMessageService, NzModalService} from 'ng-zorro-antd';
import {TyAgentService} from '../../../../services/ty-agent.service';

@Component({
  selector: 'app-ty-agent-list',
  templateUrl: './ty-agent-list.component.html',
  styleUrls: ['./ty-agent-list.component.scss']
})
export class TyAgentListComponent implements OnInit {

  dataObject: any = {};
  tableLoading = true;
  searchForm: FormGroup;
  pageNum: number;
  whereObject: any = {};

  constructor(private modal: NzModalService,
              private message: NzMessageService,
              private tyAgentService: TyAgentService,
              private form: FormBuilder) { }

  ngOnInit(): void {
    this.searchForm = this.form.group({
      agentKey: [null],
      agentName: [null],
      agentUser: [null],
      agentPhone: [null],
    });
    this.requestData(1);
  }

  /**
   * 请求数据
   */
  requestData(pageNum) {
    this.tableLoading = true;
    this.whereObject['pageNum'] = pageNum;
    this.whereObject['pageSize'] = 10;
    this.tyAgentService.getAgentList(this.whereObject, data => {
      if (data['return_code'] === '000000') {
        this.dataObject = data['return_data'];
      } else {
        this.modal.error(data['return_msg']);
      }
      this.tableLoading = false;
    });
  }

  /**
   * 搜索
   * @param whereObject 条件
   */
  search(whereObject: object) {
    this.whereObject = whereObject;
    this.requestData(1);
  }

  /**
   * 重置
   */
  resetForm(): void {
    this.searchForm.reset();
  }
  /**
   * 弹出密码重置对话框
   */
  showPwdResetConfirm(key: string): void {
    this.modal.confirm({
      nzTitle: '警告',
      nzContent: '是否重置代理商密码！',
      nzOkText: '是',
      nzCancelText: '否',
      nzOkType: 'danger',
      nzOnOk: () => this.pwdReset(key)
    });
  }

  /**
   * 密码重置
   *
   */
  pwdReset(key: string) {
    this.tyAgentService.agentPwdReset({ agentKey : key}, data => {
      if (data['return_code'] === '000000') {
        this.modal.success({
          nzTitle: '提示',
          nzContent: '重置成功！密码为：123456'
        });
      } else {
        this.modal.error({
          nzTitle: '提示',
          nzContent: data['return_msg']
        });
      }
    });
  }

  /**
   * 弹出删除对话框
   */
  showDeleteConfirm(key: string): void {
    this.modal.confirm({
      nzTitle: '警告',
      nzContent: '是否删除该代理商',
      nzOkText: '是',
      nzCancelText: '否',
      nzOkType: 'danger',
      nzOnOk: () => this.deleteData(key)
    });
  }

  /**
   * 删除数据
   *
   */
  deleteData(key: string) {
    this.tyAgentService.delAgent({ agentKey: key}, data => {
      if (data['return_code'] === '000000') {
        this.requestData(this.whereObject['pageNum']);
      } else {
        this.modal.error({
          nzTitle: '提示',
          nzContent: data['return_msg']
        });
      }
    });
  }
}
