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

@Component({
    selector: 'app-price-list',
    templateUrl: './price-list.component.html',
    styleUrls: ['./price-list.component.scss']
})
export class PriceListComponent implements OnInit {
    WEB_SERVE_URL = environment.imageUrl;
    searchForm: FormGroup; // 搜索框
    validateForm: FormGroup; // 添加框
    requestData = []; // 列表数据
    priceArray = []; // 价格数据
    priceTypeArray = []; // 支付类型数据
    platformArray = []; // 充值平台数据
    productPlatformArray = []; // 展示平台数据

    total: number; // 页码
    pageNum = 1; // 页码
    pageSize = 10; // 条码
    loading = true;
    isVisible = false;
    isVisibleProductCode = false;
    id: number;
    edit = false;
    payPrice;
    isVisibleGoods = false;
    realPrice = 0;
    rechargeCodeList: any;
    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
    ) {
    }

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

    // 获取初始化数据
    private getInitData(): void {
        // 获取价格数据
        this.common.getDictionary('RECHARGE_AMOUNT  ', data => {
            this.priceArray = data['return_data'];
        });
        // 获取支付类型
        this.common.getDictionary('PAY_TYPE  ', data => {
            this.priceTypeArray = data['return_data'];
        });
        // 获取充值平台
        this.common.getDictionary('RECHARGE_PLATFORM  ', data => {
            this.platformArray = data['return_data'];
        });
        // 获取展示平台
        this.common.getDictionary('SHOW_PLATFORM  ', data => {
            this.productPlatformArray = data['return_data'];
        });

    }

    public init(): void {
        this.searchForm = this.form.group({
            operatorType : [null],
            rechargePlatform: [null],
            // rechargeType: [null],
            rechargeWay: [null],
            status: [null],
        });
        this.validateForm = this.form.group({
            discount: [null, [Validators.required]],
            integralDiscount: [0],
            operatorType: [null, [Validators.required]],
            rechargePrices: [null, [Validators.required]],
            productPlatform: [null, [Validators.required]],
            // rechargeType: [null, [Validators.required]],
            rechargePlatform: [null, [Validators.required]],
            rechargeWay: [null, [Validators.required]],
            payType: [null, [Validators.required]],
            rechargePrice: [null],
            payPrice: [null],
            sort: [null],
            goodsId: [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.recharge.getListOutRechargePrice(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.recharge.findById(id, data => {
                data['return_data']['productPlatform'] = data['return_data']['productPlatformString'].substring(0 , data['return_data']['productPlatformString'].length - 1).split(',');
                data['return_data']['rechargePlatform'] = data['return_data']['rechargePlatform'].substring(1 , data['return_data']['rechargePlatform'].length - 1).split('-');
                data['return_data']['payType'] = data['return_data']['productPayTypeString'].substring(0 , data['return_data']['productPayTypeString'].length - 1).split(',');
                data['return_data']['rechargePrices'] = ['1'];
                this.validateForm.patchValue(data['return_data']);
                this.isVisible = true;
            });
        } else {
            this.validateForm.reset();
            this.isVisible = true;
            this.edit = false;
        }
    }

    handleOk(): void {
        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.recharge.updatePrice(this.validateForm.value, data => {
                if (data['return_code'] === '000000') {
                    this.message.remove(wait);
                    this.message.success('修改成功');
                    this.getRequest(false, this.searchForm.value);
                    this.validateForm.reset();
                    this.isVisible = false;
                } else {
                    this.message.error(data['return_msg']);
                }
            });
        } else {
            this.recharge.insertPrice(this.validateForm.value, data => {
                if (data['return_code'] === '000000') {
                    this.message.remove(wait);
                    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 1:
                statusPost = 2;
                message = '是否售空';
                break;
            case 2:
                statusPost = 1;
                message = '是否上线';
                break;
            case 3:
                statusPost = 1;
                message = '是否上线';
                break;
        }

        this.common.showConfirm(message, item => {
            if (item) {
                this.recharge.editPriceStatus( {
                    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']);
                    }
                });
            }
        });
    }

    public changePayType(e): void {
        this.payPrice = this.validateForm.value['rechargePrice'] * e / 100;
    }

    // 配置产品编码
    public getProductCode(productId: number): void {
        const paramsObject = {
            id: productId,
            codeType: 'RECHARGE_PLATFORM'
        };
        this.recharge.getRechargeCodeList(paramsObject , data => {
            if (data['return_code'] === '000000') {
                this.isVisibleProductCode = true;
                this.rechargeCodeList = data['return_data'];
                for (const i of this.rechargeCodeList) {
                    i['sourceId'] = productId;
                    i['type'] = 1;
                }
            } else {
                this.message.error(data['return_msg']);
            }
        });
    }

    // 上传配置
    public handleOkCode(): void {
        this.recharge.editRechargeCode(this.rechargeCodeList , data => {
            if (data['return_code'] === '000000') {
                this.isVisibleProductCode = false;
                this.message.success('编辑成功');
                this.getRequest(false, this.searchForm.value);
            } else {
                this.message.error(data['return_msg']);
            }
        });
    }

}
