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, NzUploadFile} from 'ng-zorro-antd';
import {ActivatedRoute} from '@angular/router';
import {CouponService} from '../../../services/coupon.service';
import {IconService} from '../../../services/icon.service';
import {CommonsService} from '../../../services/commons.service';
import {ConfigService} from "../../../services/config.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-coupon-edit',
  templateUrl: './coupon-edit.component.html',
  styleUrls: ['./coupon-edit.component.scss']
})
export class CouponEditComponent implements OnInit {



  validateForm!: FormGroup;
  data: any;
  editFlag = false;
  id: number;
  couponImg = [];
  couponCarouselImg = [];
  couponDescImg = [];
  WEB_SERVE_URL = environment.baseUrl;
  previewImage: string | undefined = '';
  previewVisible = false;
  optionList: string[] = [];
  isLoading = false;
  pageNum = 1;
  pageSize = 10;
  pageSizeCoupon = 10;
  merchantName: string;
  optionListCoupon: string[] = [];
  isLoadingCoupon = false;
  pageNumCoupon = 1;
  couponName: string;
  content: string;
  goodsTypeData;
  brandData;
  constructor(
      private fb: FormBuilder,
      private merchant: MerchantService,
      private coupon: CouponService,
      private common: CommonsService,
      private config: ConfigService,
      private message: NzMessageService, // 信息提示
      private activatedRoute: ActivatedRoute,
  ) {
  }

  ngOnInit(): void {
    this.activatedRoute.queryParams.subscribe(queryParams => {
      if (queryParams.couponId != null) {
        this.editFlag = true;
        this.id = queryParams.couponId;
        this.getDetails(queryParams.couponId);
        this.pageSize = 10000;
        this.pageSizeCoupon = 10000;
        this.loadMore();
        this.loadMoreCoupon();
      }
    });
    this.validateForm = this.fb.group({
      couponName: [null, [Validators.required]],
      couponDesc: [null],
      couponType: [null, [Validators.required]],
      salesEndTime: [null, [Validators.required]],
      recycleDay: [1, [Validators.required]],
      limitNumber: [null, [Validators.required]],
      salesPrice: [null, [Validators.required]],
      discountPrice: [null, [Validators.required]],
      merchantId: [null, [Validators.required]],
      isPresent: [false],
      reserveStatus: [false],
      buyPoints: [false],
      payType: [null, [Validators.required]],
      displayArea: [null],
      couponSource: [null],
      handselCouponId: [null],
      status: [null],
      couponKey: [null],
      createTime: [null],
      brandId: [null],
      goodsTypeId: [null],
      secUser: {},
    });

    const params = {
      pageNum: 1,
      pageSize: 10000
    };
    this.config.getListGoodsType(params , data => {
      this.goodsTypeData = data['return_data'].list;
    });

  }

  // 查询商户
  loadMore(): void {
    this.isLoading = true;
    const paramsObject = {
      pageNum: this.pageNum,
      pageSize: this.pageSize,
      merchantName: this.merchantName,
    };
    this.getMerchantList(paramsObject);
  }


  // 搜索商户
  search(e): void {
    this.optionList = [];
    this.isLoading = true;
    this.merchantName = e;
    this.pageNum = 1;
    const paramsObject = {
      pageNum: this.pageNum,
      pageSize: this.pageSize,
      merchantName: e,
    };
    this.getMerchantList(paramsObject);
  }

  // 查询商户
  public getMerchantList(paramsObject): void {
    this.merchant.getMerchantList(paramsObject , data => {
      if (data['return_code'] === '000000' && this.pageNum <= data['return_data'].pages ) {
        this.pageNum ++;
        this.isLoading = false;
        this.optionList = [...this.optionList, ...data['return_data'].list];
      } else {
        this.isLoading = false;
      }
    });
  }

  // 查询卡券
  loadMoreCoupon(): void {
    this.isLoadingCoupon = true;
    const paramsObject = {
      pageNum: this.pageNumCoupon,
      pageSize: this.pageSizeCoupon,
      merchantName: this.merchantName,
    };
    this.getCouponList(paramsObject);
  }

  // 搜索卡券
  searchCoupon(e): void {
    this.optionListCoupon = [];
    this.isLoadingCoupon = true;
    this.merchantName = e;
    this.pageNumCoupon = 1;
    const paramsObject = {
      pageNum: this.pageNumCoupon,
      pageSize: this.pageSizeCoupon,
      merchantName: e,
      status: 2,
    };
    this.getCouponList(paramsObject);
  }

  public getBrandByList(e): void {

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

    this.config.getBrandByList(params , data => {
      this.brandData = data['return_data'].list;
    });
  }

  // 查询卡券
  public getCouponList(paramsObject): void {
    this.coupon.getCouponList(paramsObject , data => {
      if (data['return_code'] === '000000' && this.pageNumCoupon <= data['return_data'].pages ) {
        this.pageNumCoupon ++;
        this.isLoadingCoupon = false;
        this.optionListCoupon = [...this.optionListCoupon, ...data['return_data'].list];
      } else {
        this.isLoadingCoupon = false;
      }
    });
  }

  // 返回
  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.validateForm.value.isPresent == null) {
      this.validateForm.value.isPresent = false;
    }

    if (this.validateForm.value.isPresent === false) {
          this.validateForm.value.handselCouponId = [];
    }

    if (this.couponImg.length !== 0) {
      if (this.couponImg[0]['response'] != null) {
        this.validateForm.value.couponImg = this.couponImg[0]['response']['return_data'][0];
      } else {
        this.validateForm.value.couponImg = this.couponImg[0].name;
      }
    } else {
      this.message.error('请上传卡券图片');
      return;
    }

    const couponCarouselImg = [];

    if (this.couponCarouselImg.length !== 0) {
      for (const i of this.couponCarouselImg) {
        if (i['response'] != null) {
          couponCarouselImg.push(i['response']['return_data'][0]);
        } else {
          couponCarouselImg.push(i.name);
        }
      }
    } else {
      this.message.error('请上传卡券轮播图');
      return;
    }
    const couponDescImg = [];

    if (this.couponDescImg.length !== 0) {
      for (const i of this.couponDescImg) {
        if (i['response'] != null) {
          couponDescImg.push(i['response']['return_data'][0]);
        } else {
          couponDescImg.push(i.name);
        }
      }
    } else {
      this.message.error('请上传卡券详情图');
      return;
    }

    this.validateForm.value.couponCarouselImg = couponCarouselImg.join(',');
    this.validateForm.value.couponDesc = couponDescImg.join(',');
    if (this.editFlag) {
      this.common.showConfirm('是否确定修改,确定将下架' , dataR => {
           if (dataR) {
             this.validateForm.value.id = this.id;
             this.coupon.updateCoupon(this.validateForm.value, data => {
               if (data['return_code'] === '000000') {
                 this.getBack();
                 this.message.success('修改成功，卡券已下架！');
               } else {
                 this.message.error(data['return_msg']);
               }
             });
           }
      });
    } else {

      this.coupon.insertCoupon(this.validateForm.value, data => {
        if (data['return_code'] === '000000') {
          this.getBack();
          this.message.success('添加成功');
        } 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;
  }

  public getDetails(id) {
    this.coupon.getCouponById(id, data => {
      if (data['return_code'] === '000000') {
        data['return_data']['couponType'] = String(data['return_data']['couponType']);
        data['return_data']['displayArea'] = String(data['return_data']['displayArea']);
        data['return_data']['payType'] = String(data['return_data']['payType']);
        data['return_data']['brandId'] = String(data['return_data']['brandId']);
        data['return_data']['goodsTypeId'] = String(data['return_data']['goodsTypeId']);
        data['return_data']['couponSource'] = String(data['return_data']['couponSource']);
        if (data['return_data']['couponImg'] != null && data['return_data']['couponImg'] !== '') {
          const couponImg = String(data['return_data']['couponImg']);
          const couponArray = [];
          couponArray.push(
              {
                uid: 1,
                name: couponImg,
                status: 'done',
                url: environment.imageUrl + couponImg
              });
          this.couponImg = couponArray;
        }
        if (data['return_data']['couponCarouselImg'] != null && data['return_data']['couponCarouselImg'] !== '') {
          const couponCarouselImg = data['return_data']['couponCarouselImg'].split(',');
          const couponCarouselArray = [];
          for (const i of couponCarouselImg) {
            couponCarouselArray.push(
                {
                  uid: i,
                  name: i,
                  status: 'done',
                  url: environment.imageUrl + i
                });
          }
          this.couponCarouselImg = couponCarouselArray;
        }
        if (data['return_data']['couponDesc'] != null && data['return_data']['couponDesc'] !== '') {
          const couponDescImg = data['return_data']['couponDesc'].split(',');
          const couponDescArray = [];
          for (const i of couponDescImg) {
            couponDescArray.push(
                {
                  uid: i,
                  name: i,
                  status: 'done',
                  url: environment.imageUrl + i
                });
          }
          this.couponDescImg = couponDescArray;
        }

        this.validateForm.patchValue(data['return_data']);
      } else {
        this.message.create('error', data['return_msg']);
      }
    });
  }

  // 富文本内容
  textData(content) {
    this.content = content;
  }
}
