import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {NzMessageService} from 'ng-zorro-antd';
import {ActivatedRoute} from '@angular/router';
import {CouponService} from '../../../services/coupon.service';
import {ActivateService} from '../../../services/activate.service';
import {NzUploadFile} from 'ng-zorro-antd';
import {environment} from '../../../../environments/environment';
import {AgentService} from '../../../services/agent.service';
import {CommonsService} from '../../../services/commons.service';
import {DiscountPackageService} from '../../../services/discount-package.service';
import {DiscountService} from '../../../services/discount.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-discount-package-edit',
  templateUrl: './discount-package-edit.component.html',
  styleUrls: ['./discount-package-edit.component.scss']
})
export class DiscountPackageEditComponent implements OnInit {

  validateForm!: FormGroup;
  validateFormAward!: FormGroup;
  data: any;
  editFlag = false;
  id: number;
  listOfData = [];
  usingAttribution = [];
  current = 0;
  FILE_URL = environment.imageUrl;
  POST_URL = environment.baseUrl;
  isVisible = false;
  previewImage: string | undefined = '';
  previewVisible = false;
  discountList = []; // 列表数据
  agentData = []; // 列表数据
  listImg = [];
  bannerImg = [];
  detailsImg = [];


  constructor(
      private fb: FormBuilder,
      private coupon: CouponService,
      private activate: ActivateService,
      private message: NzMessageService, // 信息提示
      private activatedRoute: ActivatedRoute,
      private agent: AgentService,
      private commonsService: CommonsService,
      private disCountPackage: DiscountPackageService,
      private discount: DiscountService
  ) { }

  ngOnInit(): void {
    this.commonsService.getDictionary('USING_ATTRIBUTION', data => {
      this.usingAttribution = data['return_data'];
    });
    const whereObject = {
      pageNum: 1 ,
      pageSize: 800 ,
      type: 1
    };
    this.agent.getListAgent(whereObject, data => {
      if (data['return_code'] === '000000') {
        this.agentData = data['return_data'].list;
      } else {
        this.message.error(data['return_msg']);
      }
    });
    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]],
      usingAttribution: [null],
      salesType: [null, [Validators.required]],
      price: [null],
      purchaseNum: [null],
    });

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

  }

  // 图片查看
  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 editInfo(): 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.imgIsPost();


    if (this.editFlag) {
      this.validateForm.value.id = this.id;
      this.disCountPackage.updateCouponPackageInfo(this.validateForm.value, data => {
        if (data['return_code'] === '000000') {
          this.editFlag = true;
          this.id = data['return_data'].id;
          this.getListByActivityId(data['return_data'].id);
          this.current += 1;
          this.message.success('编辑成功');
        } else {
          this.message.create('error', data['return_msg']);
        }
      });
    } else {
      this.disCountPackage.insertCouponPackageInfo(this.validateForm.value, data => {
        if (data['return_code'] === '000000') {
          this.editFlag = true;
          this.id = data['return_data'].id;
          this.getListByActivityId(data['return_data'].id);
          this.current += 1;
          this.message.success('编辑成功');
        } else {
          this.message.create('error', data['return_msg']);
        }
      });
    }

  }

  public imgIsPost(): boolean {
    if (this.listImg.length !== 0) {
      if (this.listImg[0]['response'] != null) {
        this.validateForm.value.listImg = this.listImg[0]['response']['return_data'][0];
      } else {
        this.validateForm.value.listImg = this.listImg[0].name;
      }
    } else {
      this.message.error('请上传列表图片');
      return false;
    }

    const bannerImg = [];

    if (this.bannerImg.length !== 0) {
      for (const i of this.bannerImg) {
        if (i['response'] != null) {
          bannerImg.push(i['response']['return_data'][0]);
        } else {
          bannerImg.push(i.name);
        }
      }
    } else {
      this.message.error('请上传轮播展示图');
      return false;
    }
    const detailsImg = [];

    if (this.detailsImg.length !== 0) {
      for (const i of this.detailsImg) {
        if (i['response'] != null) {
          detailsImg.push(i['response']['return_data'][0]);
        } else {
          detailsImg.push(i.name);
        }
      }
    } else {
      this.message.error('请上传详情展示图');
      return false;
    }
    this.validateForm.value.bannerImg = bannerImg.join(',');
    this.validateForm.value.detailsImg = detailsImg.join(',');
  }

  // 查询详情
  public getDetails(id) {
    this.disCountPackage.getDiscountPackageById(id, data => {
      if (data['return_code'] === '000000') {
        data['return_data']['usingAttribution'] = String(data['return_data']['usingAttribution']);
        if (data['return_data']['listImg'] != null && data['return_data']['listImg'] !== '') {
          const listImg = String(data['return_data']['listImg']);
          const listImgArray = [];
          listImgArray.push(
              {
                uid: 1,
                name: listImg,
                status: 'done',
                url: environment.imageUrl + listImg
              });
          this.listImg = listImgArray;
        }
        if (data['return_data']['bannerImg'] != null && data['return_data']['bannerImg'] !== '') {
          const bannerImg = data['return_data']['bannerImg'].split(',');
          const bannerImgArray = [];
          for (const i of bannerImg) {
            bannerImgArray.push(
                {
                  uid: i,
                  name: i,
                  status: 'done',
                  url: environment.imageUrl + i
                });
          }
          this.bannerImg = bannerImgArray;
        }
        if (data['return_data']['detailsImg'] != null && data['return_data']['detailsImg'] !== '') {
          const detailsImg = data['return_data']['detailsImg'].split(',');
          const detailsImgArray = [];
          for (const i of detailsImg) {
            detailsImgArray.push(
                {
                  uid: i,
                  name: i,
                  status: 'done',
                  url: environment.imageUrl + i
                });
          }
          this.detailsImg = detailsImgArray;
        }
        this.validateForm.patchValue(data['return_data']);
      } else {
        this.message.create('error', data['return_msg']);
      }
    });
    this.getListByActivityId(id);
  }

  getListByActivityId(id: number ) {
    this.disCountPackage.getDiscountPackageRuleById(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.editInfo();
    } else {
      history.back();
    }

  }


  // 添加配置
  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;
      }
    }
    this.validateFormAward.value['discountPackageId'] = this.id;
    this.disCountPackage.insertCouponPackageRule(this.validateFormAward.value , data => {
      if (data['return_code'] === '000000') {
        this.isVisible = false;
        this.getListByActivityId(this.id);
        this.validateFormAward.reset();
        this.message.success('编辑成功');
      } else {
        this.message.create('error', data['return_msg']);
      }
    });

  }

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


  deleteActivateAward(id: number) {
    this.disCountPackage.deleteDiscountPackageRule(id , data => {
      if (data['return_code'] === '000000') {
        this.getListByActivityId(this.id);
        this.message.success('成功');
      } else {
        this.message.create('error', data['return_msg']);
      }
    });
  }

  public getDiscountPackageByList(e): void {

    const params = {
      pageNum: 1,
      pageSize: 10000,
      agentId: e
    };

    this.agent.getDiscountAgentList(params , data => {
      this.discountList = data['return_data'].list;
    });
  }
}
