import {Component, OnInit} from '@angular/core';
import { environment } from '../../../../environments/environment';
import {FormsModule, ReactiveFormsModule, UntypedFormBuilder, UntypedFormGroup, Validators} from "@angular/forms";
import {StoreService} from "../../../services/store.service";
import {NzModalComponent, NzModalService} from "ng-zorro-antd/modal";
import {NzMessageService} from "ng-zorro-antd/message";
import {SystemVersionService} from "../../../services/system-version.service";
import {NzUploadComponent, NzUploadFile} from "ng-zorro-antd/upload";
import {RouterLink} from "@angular/router";
import {SalesmanStatusPipe} from "../../../pipes/salesman-status.pipe";
import {DatePipe, NgForOf, NgIf} from "@angular/common";
import {BreadcrumbComponent} from "../../common/breadcrumb/breadcrumb.component";
import {NzFormDirective} from "ng-zorro-antd/form";
import {NzColDirective, NzRowDirective} from "ng-zorro-antd/grid";
import {NzOptionComponent, NzSelectComponent} from "ng-zorro-antd/select";
import {NzInputDirective} from "ng-zorro-antd/input";
import {NzButtonComponent} from "ng-zorro-antd/button";
import {NzIconDirective} from "ng-zorro-antd/icon";
import {NzCellFixedDirective, NzTableComponent, NzThMeasureDirective} from "ng-zorro-antd/table";
import {AgentStatusPipe} from "../../../pipes/agent-status.pipe";
import {NzBreadCrumbComponent, NzBreadCrumbItemComponent} from "ng-zorro-antd/breadcrumb";
import {NzSiderComponent} from "ng-zorro-antd/layout";
import {NzSwitchComponent} from "ng-zorro-antd/switch";
import {NzDescriptionsComponent, NzDescriptionsItemComponent} from "ng-zorro-antd/descriptions";
import {BrowserStorageService} from "../../../utils/localStorage.service";
import {NzSpinComponent} from "ng-zorro-antd/spin";
import {NzDropDownDirective, NzDropdownMenuComponent} from "ng-zorro-antd/dropdown";
import {NzMenuDirective, NzMenuItemComponent} from "ng-zorro-antd/menu";

@Component({
  selector: 'app-version',
  standalone: true,
  imports: [
    RouterLink,
    SalesmanStatusPipe,
    DatePipe,
    BreadcrumbComponent,
    NzFormDirective,
    NzRowDirective,
    NzColDirective,
    NzSelectComponent,
    NzOptionComponent,
    ReactiveFormsModule,
    NgIf,
    NzInputDirective,
    NzButtonComponent,
    NzIconDirective,
    NzTableComponent,
    NzThMeasureDirective,
    NzCellFixedDirective,
    NgForOf,
    AgentStatusPipe,
    NzBreadCrumbItemComponent,
    NzBreadCrumbComponent,
    NzSiderComponent,
    NzSwitchComponent,
    FormsModule,
    NzModalComponent,
    NzDescriptionsComponent,
    NzDescriptionsItemComponent,
    NzSpinComponent,
    NzUploadComponent,
    NzDropdownMenuComponent,
    NzDropDownDirective,
    NzMenuItemComponent,
    NzMenuDirective
  ],
  templateUrl: './version.component.html',
  styleUrl: './version.component.less'
})
export class VersionComponent implements OnInit {
  WEB_SERVE_URL = environment.baseUrl;
  FILE_URL = environment.imageUrl;
  loading = false;
  dataObject: any = {};
  tableLoading = true;
  searchForm: UntypedFormGroup;
  pageNum: number;
  whereObject: any = {};
  loadingObject = {
    spinning: false,
    msg: '加载中'
  };

  termTypeArray = [
    {
      codeValue: 'APP',
      codeName: 'APP'
    }
  ];
  versionTypeArray = [
    {
      codeValue: '1',
      codeName: '小版本'
    },
    {
      codeValue: '2',
      codeName: '大版本'
    }
  ];
  versionDetailModal = false;
  versionDetailObject: any = {};
  editVersionModal = false;
  editVersionModalForm: UntypedFormGroup;
  versionFileUrl;
  constructor(private store: BrowserStorageService, // 数据请求
              private modal: NzModalService,
              private message: NzMessageService,
              private systemVersionService: SystemVersionService,
              private storeService: StoreService,
              private form: UntypedFormBuilder) { }

  ngOnInit(): void {
    this.searchForm = this.form.group({
      termType: [null],
      versionType: [null],
      status: [null],
    });
    this.editVersionModalForm = this.form.group({
      id: [null],
      termType: ['APP', [Validators.required]],
      versionType: ['1', [Validators.required]],
      version: [null, [Validators.required]],
      content: [null, [Validators.required]],
      fileUrl: [null],
    });
    this.requestData(1);
  }

  /**
   * 请求数据
   */
  requestData(pageNum) {
    this.tableLoading = true;
    this.whereObject['pageNum'] = pageNum;
    this.whereObject['pageSize'] = 10;
    this.systemVersionService.getVersionList(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();
  }

  /**
   * 展示编辑模态框
   */
  showEditModal(id: number) {
    this.editVersionModal = true;
  }

  /**
   * 提交编辑数据
   */
  submitEdit() {
    for (const i in this.editVersionModalForm.controls) {
      this.editVersionModalForm.controls[i].markAsDirty();
      this.editVersionModalForm.controls[i].updateValueAndValidity();
    }
    console.log(this.editVersionModalForm.value);
    console.log(this.editVersionModalForm.status);
    if (this.editVersionModalForm.status == null || this.editVersionModalForm.status !== 'VALID') {
      this.modal.warning({
        nzTitle: '提示',
        nzContent: '请规范填写所有的必填项信息',
      });
      return;
    }
    if (this.versionFileUrl == null || this.versionFileUrl.length === 0) {
      this.modal.warning({
        nzTitle: '提示',
        nzContent: '未上传更新文件',
      });
      return;
    }
    this.editVersionModalForm.value.fileUrl = 'https://hsg.dctpay.com/filesystem/' + this.versionFileUrl;
    this.systemVersionService.editVersion(this.editVersionModalForm.value, data => {
      if (data['return_code'] === '000000') {
        this.modal.success({
          nzTitle: '提示',
          nzContent: '新增成功',
          nzOnOk: () => this.requestData(1)
        });
        this.closeEditModal();
      } else {
        this.modal.error({
          nzTitle: '提示',
          nzContent: data['return_msg'],
        });
      }
    });
  }
  /**
   * 关闭编辑模态框
   */
  closeEditModal() {
    this.editVersionModal = false;
  }

  /**
   * 弹出发布对话框
   */
  showReleaseConfirm(id: number): void {
    this.modal.confirm({
      nzTitle: '警告',
      nzContent: '确定发布版本吗？',
      nzOkText: '是',
      nzCancelText: '否',
      nzOnOk: () => this.requestRelease(id)
    });
  }

  /**
   * 发布数据
   *
   */
  requestRelease(id: number) {
    this.loading = true;
    this.systemVersionService.releaseVersion(id, data => {
      if (data['return_code'] === '000000') {
        this.modal.success({
          nzTitle: '提示',
          nzContent: '操作成功',
          nzOnOk: () => this.requestData(this.whereObject['pageNum'])
        });
      } else {
        this.modal.error({
          nzTitle: '提示',
          nzContent: data['return_msg']
        });
      }
      this.loading = false;
    });
  }

  /**
   * 弹出退款对话框
   */
  showDelConfirm(id: number): void {
    this.modal.confirm({
      nzTitle: '警告',
      nzContent: '确定删除吗？',
      nzOkText: '是',
      nzCancelText: '否',
      nzOnOk: () => this.requestDel(id)
    });
  }

  /**
   * 删除数据
   *
   */
  requestDel(id: number) {
    this.loading = true;
    this.systemVersionService.delVersion(id, data => {
      if (data['return_code'] === '000000') {
        this.modal.success({
          nzTitle: '提示',
          nzContent: '操作成功',
          nzOnOk: () => this.requestData(this.whereObject['pageNum'])
        });
      } else {
        this.modal.error({
          nzTitle: '提示',
          nzContent: data['return_msg']
        });
      }
      this.loading = false;
    });
  }

  fileHandleChange(info: { file: NzUploadFile }): void {
    switch (info.file.status) {
      case 'uploading':
        break;
      case 'done':
        this.versionFileUrl = info.file.response.return_data[0];
        break;
      case 'error':
        this.message.error('上传失败');
        break;
    }
  }


  showOpenDetail(data: object) {
    this.versionDetailObject = data;
    this.versionDetailModal = true;
  }

  closeVersionDetail() {
    this.versionDetailModal = false;
  }
}
