import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {CouponService} from '../../../services/coupon.service';
import {ActivateService} from '../../../services/activate.service';
import {NzMessageService, NzUploadFile} from 'ng-zorro-antd';
import {environment} from '../../../../environments/environment';
import {AgentService} from '../../../services/agent.service';
import {ActivatedRoute} from '@angular/router';

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

  validateForm!: FormGroup;
  validateFormAward!: FormGroup;
  data: any;
  editFlag = false;
  id: number;
  agentId: number;
  listOfOption: string[] = [];
  listOfData = [];
  agentData = [];
  current = 0;
  listOfControl = [{
    isEdit: true,
    agentId: null,
    agentName: null,
    prizeNum: null,
    prizeId: null,
    prizeName: null,
    loading : false
  }];
  FILE_URL = environment.imageUrl;
  POST_URL = environment.baseUrl;
  isVisible = false;
  logoFile = [];
  previewImage: string | undefined = '';
  previewVisible = false;
  discountList = []; // 列表数据
  constructor(
      private fb: FormBuilder,
      private coupon: CouponService,
      private activate: ActivateService,
      private message: NzMessageService, // 信息提示
      private activatedRoute: ActivatedRoute,
      private agent: AgentService,
  ) { }

  ngOnInit(): void {
    this.activatedRoute.queryParams.subscribe(queryParams => {
      if (queryParams.id != null) {
        this.editFlag = true;
        this.id = queryParams.id;
        this.getDetails(queryParams.id);
      }
    });
    this.validateForm = this.fb.group({
      title: [null, [Validators.required]],
      productIdArray: [null, [Validators.required]],
      type: [null, [Validators.required]],
      content: [null, [Validators.required]],
      time: [null, [Validators.required]],
    });

    this.validateFormAward = this.fb.group({
      name: [null, [Validators.required]],
      num: [null, [Validators.required]],
    });

    const whereObject = {
      pageNum: 1 ,
      pageSize: 800 ,
      status: 2
    };

    const whereObjectA = {
      pageNum: 1 ,
      pageSize: 800 ,
      type: 1
    };

    this.getCouponList(whereObject);
    this.getListAgent(whereObjectA);


  }

  public getCouponList(whereObject) {
    whereObject.status = 2;
    this.coupon.getCouponList(whereObject, data => {
      if (data['return_code'] === '000000') {
        this.listOfOption = data['return_data'].list;
      } else {
        this.message.error(data['return_msg']);
      }
    });
  }

  // 绑定优惠券
  public getDiscount(id: number , i ): void {
    this.listOfControl[i].agentName = this.agentData.find(item => {
      return item.id == id;
    }).agentName;
    this.agentId = id;
    const whereObject = {};
    whereObject['pageNum'] = 1;
    whereObject['pageSize'] = 10000;
    whereObject['agentId'] = id;
    this.agent.getDiscountAgentList(whereObject, data => {
      if (data['return_code'] === '000000') {
        this.discountList = data['return_data'].list;
      } else {
        this.message.error(data['return_msg']);
      }
    });
  }

  getDiscountName(id: number , i ) {
    this.listOfControl[i].prizeName = this.discountList.find(item => {
      return item['highDiscount'].id == id;
    })['highDiscount'].discountName;
    console.log(this.listOfControl);
  }

  public getListAgent(whereObject) {
    this.agent.getListAgent(whereObject, data => {
      if (data['return_code'] === '000000') {
        this.agentData = data['return_data'].list;
      } else {
        this.message.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;
  }

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

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

  // 基本信息提交
  public editActivityInfo(): 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;
      }
    }

    this.validateForm.value.ruleArray = [{
      partakeMode: 1,
      productType: 1 ,
      productIdArray: this.validateForm.value.productIdArray
    }];
    this.validateForm.value.startTime = this.validateForm.value.time[0].getTime();
    this.validateForm.value.endTime = this.validateForm.value.time[1].getTime();

    if (this.editFlag) {
      this.validateForm.value.id = this.id;
    }
    this.activate.editActivityInfo(this.validateForm.value, data => {
      if (data['return_code'] === '000000') {
        this.editFlag = true;
        this.id = data['return_data'].id;
        this.current += 1;
        this.message.success('编辑成功');
      } else {
        this.message.create('error', '编辑失败');
      }
    });
  }

  // 查询详情
  public getDetails(id) {
    this.activate.getDetailById(id, data => {
      if (data['return_code'] === '000000') {
        data['return_data'].time = [new Date(data['return_data']['startTime']), new Date(data['return_data']['endTime'])];
        data['return_data'].type = String(data['return_data'].type);
        data['return_data'].productIdArray = data['return_data'].ruleArray[0].productIdArray;
        this.validateForm.patchValue(data['return_data']);
      } else {
        this.message.create('error', data['return_msg']);
      }
    });
    this.getListByActivityId(id);

  }

  getListByActivityId(id: number ) {
    this.activate.getListByActivityId(id , data => {
      if (data['return_code'] === '000000') {
        this.listOfData = data['return_data'];
      } else {
        this.message.create('error', data['return_msg']);
      }
    });
  }

  // 上一步
  pre(): void {
    this.current -= 1;
  }

  // 下一步
  getNest(): void {
    if (this.current === 0) {
      this.editActivityInfo();
    } else {
      history.back();
    }

  }

  // 完成
  done(): void {

  }

  // 新增
  addField(i): void {
    if (
        this.listOfControl[i].prizeId == null ||
        this.listOfControl[i].prizeNum == null ||
        this.listOfControl[i].agentId == null
    ) {
      this.message.error('请填写必填项！');
      return;
    }
    this.listOfControl[i].isEdit = false;
    const control = {
      isEdit: true,
      agentId: null,
      agentName: null,
      prizeNum: null,
      prizeId: null,
      prizeName: null,
      loading : false
    };
    this.listOfControl.push(control);

  }

  // 删除资质
  removeField(i, e: MouseEvent): void {
    e.preventDefault();
    if (this.listOfControl.length > 1) {
      this.listOfControl.splice(i, 1);
      this.listOfControl[i - 1].isEdit = true;
    }
  }


  // 添加配置
  getAdd(): void {
    this.isVisible = true;
  }


  handleOk(): void {

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

    if (
        this.listOfControl[this.listOfControl.length - 1].prizeId == null ||
        this.listOfControl[this.listOfControl.length - 1].prizeNum == null ||
        this.listOfControl[this.listOfControl.length - 1].agentId == null
    ) {
      this.message.error('请填写必填项！');
      return;
    }

    this.validateFormAward.value.activityPrizes = this.listOfControl;
    this.validateFormAward.value.activityInfoId = this.id;
    if (this.logoFile.length !== 0) {
      if (this.logoFile[0]['response'] != null) {
        this.validateFormAward.value.img = this.logoFile[0]['response']['return_data'][0];
      } else {
        this.validateFormAward.value.img = this.logoFile[0].name;
      }
    }
    this.message.loading('生成奖品中！');
    this.activate.editActivityAward(this.validateFormAward.value , data => {
      if (data['return_code'] === '000000') {
        this.isVisible = false;
        this.getListByActivityId(this.id);
        this.message.success('编辑成功');
      } else {
        this.message.create('error', '编辑失败');
      }
    });

  }

  handleCancel(): void {
    this.isVisible = false;
  }


  deleteActivateAward(id: number) {
    this.activate.deleteActivateAward(id , data => {
      if (data['return_code'] === '000000') {
        this.getListByActivityId(this.id);
        this.message.success('成功');
      } else {
        this.message.create('error', '编辑失败');
      }
    });
  }
}
