import { Component, OnInit } from '@angular/core';
import {environment} from '../../../../environments/environment';
import {FormBuilder, FormGroup} from '@angular/forms';
import {AgentService} from '../../../services/agent.service';
import {IconService} from '../../../services/icon.service';
import {NzMessageService} from 'ng-zorro-antd';
import {Router} from '@angular/router';
import {CommonsService} from '../../../services/commons.service';
import {DiscountService} from '../../../services/discount.service';
import {CouponService} from '../../../services/coupon.service';
import {MerchantService} from '../../../services/merchant.service';

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

  WEB_SERVE_URL = environment.imageUrl;
  searchForm: FormGroup; // 搜索框
  searchFormCoupon: FormGroup; // 搜索框
  requestData = []; // 列表数据
  couponData = []; // 列表数据
  optionList = []; // 列表数据
  discountCoupon = []; // 列表数据
  total: number; // 页码
  pageNum = 1; // 页码
  pageSize = 10; // 条码
  loading = true;
  isVisible = false;
  isVisibleList = false;
  couponList: any;
  requestCouponData = []; // 列表数据
  loadingCoupon = true;
  loadingDiscountCoupon = true;
  discountId: number;
  RelByDiscountId: number;

  setOfCheckedId = new Set<number>();
  checked = false;
  indeterminate = false;

  updateCheckedSet(id: number, checked: boolean): void {
    if (checked) {
      this.setOfCheckedId.add(id);
    } else {
      this.setOfCheckedId.delete(id);
    }
  }

  onItemChecked(id: number, checked: boolean): void {
    this.updateCheckedSet(id, checked);
    this.refreshCheckedStatus();
  }

  onAllChecked(value: boolean): void {
    this.requestCouponData.forEach(item => this.updateCheckedSet(item.id, value));
    this.refreshCheckedStatus();
  }



  refreshCheckedStatus(): void {
    this.checked = this.requestCouponData.every(item => this.setOfCheckedId.has(item.id));
    this.indeterminate = this.requestCouponData.some(item => this.setOfCheckedId.has(item.id)) && !this.checked;
  }

  constructor(
      private form: FormBuilder,
      private discount: DiscountService,
      private iconService: IconService,
      private merchant: MerchantService,
      private message: NzMessageService,
      private router: Router,
      private common: CommonsService,
      private coupon: CouponService
  ) {
  }

  ngOnInit(): void {
    this.init();
    const whereObject = {};
    whereObject['pageNum'] = 1;
    whereObject['pageSize'] = 30000;
    this.merchant.getMerchantList(whereObject , data => {
      if (data['return_code'] === '000000' ) {
        this.optionList  = data['return_data'].list;
      }
    });
  }

  public init(): void {
    this.searchForm = this.form.group({
      discountKey: [null],
      discountName: [null],
      discountType: [null],
    });
    this.searchFormCoupon = this.form.group({
      merchantId: [null],
      couponName: [null],
      couponType: [null],
      couponSource: [null],
      status: [2],
    });
    this.getRequest(true, this.searchForm.value);
  }

  // 查询列表
  public getRequest(reset: boolean = false, whereObject: object) {

    this.loading = false;
    if (reset) {
      this.pageNum = 1;
    }
    whereObject['pageNum'] = this.pageNum;
    whereObject['pageSize'] = this.pageSize;
    this.discount.getDiscountList(whereObject, data => {
      if (data['return_code'] === '000000') {
        this.requestData = data['return_data'].list;
        this.total = data['return_data'].total;
      } else {
        this.message.error(data['return_msg']);
      }
    });
  }

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

  public getForbiddenUser(id, status: any): void {
    const message = (status === 2 ? '是否下架当前优惠券' : '是否上架当前优惠券');
    const s = status === 2 ? 3 : 2;
    this.common.showConfirm(message, data => {
      if (data) {
        this.discount.editStatus(id, s , dataUser => {
          if (dataUser['return_code'] === '000000') {
            this.message.success(dataUser['return_data']);
          } else {
            this.message.error(dataUser['return_msg']);
          }
          this.getRequest(false , this.searchForm.value);
        });
      }
    });
  }


  // 修改
  public getEdit(id: number): void {
    this.router.navigate(['/admin/discount/discount-detail'], {
      queryParams: {
        discountId: id
      }
    }).then(r => console.log(r));
  }

  // 查看详情
  public getDetail(id: number): void {
    this.router.navigate(['/admin/company/company-detail'], {
      queryParams: {
        companyId: id
      }
    }).then(r => console.log(r));
  }

  // 绑定卡券
  public getCoupon(whereObject: object , id: number): void {
    this.isVisible = true;
    this.discountId = id;
    whereObject['pageNum'] = 1;
    whereObject['pageSize'] = 30000;
    this.coupon.getCouponList(whereObject, data => {
      if (data['return_code'] === '000000') {
        this.loadingCoupon = false;
        this.requestCouponData = data['return_data'].list;
      } else {
        this.message.error(data['return_msg']);
      }
    });

  }

  handleOk(): void {
    const couponIdStr = [];
    this.setOfCheckedId.forEach(item => couponIdStr.push(item));
    const params = {
      discountId : this.discountId,
      couponIdStr : couponIdStr.join(',')
    };
    this.discount.insertDiscountCoupon(params , data => {
      if (data['return_code'] === '000000') {
          this.message.success(data['return_data']);
      } else {
        this.message.error(data['return_msg']);
      }
    });
    this.isVisible = false;
  }

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


  // 重置
  public resetCouponForm(): void {
    this.searchFormCoupon.reset();
  }

  public getCouponList(id: number): void {
    this.RelByDiscountId = id;
    this.getRelByDiscount(id);
    this.isVisibleList = true;
  }

  getRelByDiscount(id: number): void {
    this.loadingDiscountCoupon = true;
    this.discount.getRelByDiscount(id , data => {
      if (data['return_code'] === '000000') {
        this.loadingDiscountCoupon = false;
        this.discountCoupon = data['return_data'];
      } else {
        this.message.error(data['return_msg']);
      }
    });
  }

  handleCancelList(): void {
    this.isVisibleList = false;
  }

  showDeleteConfirmDelete(id: number): void {
    this.common.showConfirm('是否确定删除！' , dataR => {
      if (dataR) {
        this.discount.delete(id, data => {
          if (data['return_code'] === '000000') {
            this.getRelByDiscount(this.RelByDiscountId);
            this.message.success(data['return_data']);
          } else {
            this.message.error(data['return_msg']);
          }
        });
      }
    });
  }


}

