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

    WEB_SERVE_URL = environment.imageUrl;
    searchForm: FormGroup; // 搜索框
    validateForm: FormGroup; // 添加框
    requestData = []; // 列表数据
    priceArray = []; // 价格数据
    platformArray = []; // 充值平台数据

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

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

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

    // 获取初始化数据
    private getInitData(): void {
        // 获取价格数据
        this.common.getDictionary('RECHARGE_AMOUNT  ', data => {
            this.priceArray = data['return_data'];
        });
        // 获取充值平台
        this.common.getDictionary('RECHARGE_PLATFORM  ', data => {
            this.platformArray = data['return_data'];
        });
    }

    public init(): void {
        this.searchForm = this.form.group({
            operatorType : [null],
            rechargePlatform: [null],
            phoneRechargeType: [null],
            status: [null],
        });
        this.validateForm = this.form.group({
            operatorType: [null, [Validators.required]],
            prices: [null, [Validators.required]],
            phoneRechargeType: [null, [Validators.required]],
            rechargePlatform: [null, [Validators.required]],
            rechargePrice: [null],
            sort: [null],
            productId: [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.getListApiProduct(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 getEdit(id?: number): void {
        if (id != null) {
            this.id = id;
            this.edit = true;
            this.apiProduct.findById(id, data => {
                data['return_data']['rechargePlatform'] = data['return_data']['rechargePlatform'].substring(1 , data['return_data']['rechargePlatform'].length - 1).split('-');
                data['return_data']['prices'] = ['1'];
                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('必填项不能为空');
                return;
            }
        }

        if (this.edit) {
            this.validateForm.value['id'] = this.id;
            this.apiProduct.updateProduct(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.insertProduct(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 getForbiddenUser(idPost, status: any): void {

        let statusPost;
        let message;

        switch (status) {
            case 101:
                statusPost = 102;
                message = '是否下线';
                break;
            case 102:
                statusPost = 101;
                message = '是否上线';
                break;
        }

        this.common.showConfirm(message, item => {
            if (item) {
                this.apiProduct.editProductStatus( {
                    id: idPost,
                    status: statusPost
                }, data => {
                    if (data['return_code'] === '000000') {
                        this.message.success('提交成功');
                        this.getRequest(false, this.searchForm.value);
                    } else {
                        this.message.error(data['return_msg']);
                    }
                });
            }
        });
    }

    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']);
                    }
                });
            }
        });
    }


}
