import { Component, OnInit } from '@angular/core';
import {environment} from '../../../../environments/environment';
import {RechargeService} from '../../../services/recharge.service';
import {DiscountService} from '../../../services/discount.service';
import {CouponService} from '../../../services/coupon.service';
import {IconService} from '../../../services/icon.service';
import {CommonsService} from '../../../services/commons.service';
import {ApiProductService} from '../../../services/api-product.service';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {NzMessageService} from 'ng-zorro-antd';
import {Router} from '@angular/router';

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

    WEB_SERVE_URL = environment.imageUrl;
    searchForm: FormGroup; // 搜索框
    validateForm: FormGroup; // 添加框
    requestData = []; // 列表数据
    productArray = []; // 价格数据
    priceTypeArray = []; // 支付类型数据
    platformArray = []; // 充值平台数据
    productPlatformArray = []; // 展示平台数据

    total: number; // 页码
    pageNum = 1; // 页码
    pageSize = 10; // 条码
    loading = true;
    isVisible = false;
    isVisibleProduct = false;
    id: number;
    edit = false;
    payPrice;
    isVisibleGoods = false;
    realPrice = 0;
    data = {};

    formatterPercent = (value: number): string => `${value == null ? 0 : value} %`;
    parserPercent = (value: string): string => value.replace(' %', '');

    constructor(
        private form: FormBuilder,
        private recharge: RechargeService,
        private discount: DiscountService,
        private coupon: CouponService,
        private iconService: IconService,
        private message: NzMessageService,
        private router: Router,
        private common: CommonsService,
        private apiProduct: ApiProductService
    ) {
    }

    ngOnInit(): void {
        this.init();
        this.getInitData();

    }

    // 获取初始化数据
    private getInitData(): void {
        // 获取星巴克数据
        this.apiProduct.getStarbucksProducts(data => {
            this.productArray = data['return_data'];
        });
        // 获取支付类型
        this.common.getDictionary('PAY_TYPE  ', data => {
            this.priceTypeArray = data['return_data'];
        });
        // 获取展示平台
        this.common.getDictionary('SHOW_PLATFORM  ', data => {
            this.productPlatformArray = data['return_data'];
        });

    }


    public init(): void {
        this.searchForm = this.form.group({
            productType: [null],
            productName: [null],
        });
        this.validateForm = this.form.group({
            discount: [null, [Validators.required]],
            integralDiscount: [0],
            productPlatform: [null, [Validators.required]],
            payType: [null, [Validators.required]],
            productType: [null, [Validators.required]],
            productName: [null],
        });


        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.apiProduct.getProductConfig(whereObject, data => {
            if (data['return_code'] === '000000') {
                console.log(data);
                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 getEdit(id?: number): void {
        if (id != null) {
            this.id = id;
            this.edit = true;
            this.apiProduct.findProductConfig(id, data => {
                data['return_data']['productPlatform'] = data['return_data']['productPlatformString'].substring(0 , data['return_data']['productPlatformString'].length - 1).split(',');
                data['return_data']['payType'] = data['return_data']['productPayTypeString'].substring(0 , data['return_data']['productPayTypeString'].length - 1).split(',');
                this.validateForm.patchValue(data['return_data']);
                this.isVisible = true;
            });
        } else {
            this.validateForm.reset();
            this.isVisible = true;
            this.edit = false;
        }
    }

    handleOk(): void {
        console.log(this.validateForm.value);
        const wait = this.message.loading('提交中..', { nzDuration: 0 }).messageId;
        // 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('必填项不能为空');
                this.message.remove(wait);
                return;
            }
        }

        if (this.edit) {
            this.validateForm.value['id'] = this.id;
            this.apiProduct.updateProductConfig(this.validateForm.value, data => {
                this.message.remove(wait);
                if (data['return_code'] === '000000') {
                    this.message.success('修改成功');
                    this.getRequest(false, this.searchForm.value);
                    this.validateForm.reset();
                    this.isVisible = false;
                } else {
                    this.message.error(data['return_msg']);
                }
            });
        } else {
            this.apiProduct.productConfig(this.validateForm.value, data => {
                this.message.remove(wait);
                if (data['return_code'] === '000000') {
                    this.message.success('添加成功');
                    this.getRequest(false, this.searchForm.value);
                    this.isVisible = false;
                    this.validateForm.reset();
                } else {
                    this.message.error(data['return_msg']);
                }
            });
        }

    }

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

    public getForbiddenUserD(idPost): void {

        this.common.showConfirm('是否删除', item => {
            if (item) {
                this.recharge.editPriceStatus({
                    id: idPost,
                    status: 0
                }, data => {
                    if (data['return_code'] === '000000') {
                        this.message.success('删除成功');
                        this.getRequest(false, this.searchForm.value);
                    } else {
                        this.message.error(data['return_msg']);
                    }
                });
            }
        });
    }

    // 详情
    public getDetail(id: number): void {
        this.id = id;
        this.apiProduct.findStarbucksProducts(id, data => {
            if (data['return_code'] === '000000') {
                this.data = data['return_data'];
                this.isVisibleProduct = true;
            } else {
                this.message.error(data['return_msg']);
            }
        });
    }




}
