import {Component, OnInit} from '@angular/core';
import {environment} from '../../../../environments/environment';
import {CouponService} from '../../../services/coupon.service';
import {IconService} from '../../../services/icon.service';
import {CommonsService} from '../../../services/commons.service';
import {ApiMerchantsService} from '../../../services/api-merchants.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;
    configVisible = false;
    editConfigVisible = false;
    visibleConfigProduct = false;
    id: number;
    edit = false;
    payPrice;
    isVisibleGoods = false;
    realPrice = 0;

    rechargeModal = false;
    rechargeForm: FormGroup;
    configValidateForm: FormGroup;
    rechargeParam: any = {};
    smsCodeBtnName = '获取验证码';
    smsCodeBtnLoading = false;
    submitRechargeBtnLoading = false;
    countdownTime;

    merchantArray = [];
    merchRechargeData = [];
    merchantId: number;
    configProductId: number;
    productArray = [];
    productConfigArray = [];
    discount;
    formatterPercent = (value: number): string => `${value == null ? 0 : value} %`;
    parserPercent = (value: string): string => value.replace(' %', '');

    constructor(
        private form: FormBuilder,
        private apiMerchants: ApiMerchantsService,
        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.rechargeForm = this.form.group({
            merchantId: [null, [Validators.required]],
            amount: [null, [Validators.required]],
            smsCode: [null, [Validators.required]],
        });
        this.searchForm = this.form.group({
            merchantName: [null],
            mchId: [null],
            phone: [null],
            status: [null],
        });
        this.validateForm = this.form.group({
            merchantName: [null, [Validators.required]],
            userName: [null, [Validators.required]],
            phone: [null, [Validators.required]],
        });
        this.configValidateForm = this.form.group({
            productIds: [null, [Validators.required]],
            discount: [null, [Validators.required]],
        });

        this.getRequest(true, this.searchForm.value);
        this.apiMerchants.getListApiMerchantByAll(data => {
            if (data['return_code'] === '000000') {
                this.merchantArray = data['return_data'];
            } else {
                this.message.error(data['return_msg']);
            }
        });
        this.apiProduct.getAvailableApiProductByList(data => {
            if (data['return_code'] === '000000') {
                this.productArray = data['return_data'];
            } else {
                this.message.error(data['return_msg']);
            }
        });

    }

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

        this.loading = false;
        if (reset) {
            this.pageNum = 1;
        }
        whereObject['pageNum'] = this.pageNum;
        whereObject['pageSize'] = this.pageSize;
        this.apiMerchants.getListApiMerchant(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.apiMerchants.findById(id, data => {
                this.validateForm.patchValue(data['return_data']);
                this.isVisible = true;
            });
        } else {
            this.validateForm.reset();
            this.isVisible = true;
            this.edit = false;
        }
    }

    handleOk(): 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;
            }
        }
        const wait = this.message.loading('提交中..', {nzDuration: 0}).messageId;
        if (this.edit) {
            this.validateForm.value['id'] = this.id;
            this.apiMerchants.updateMerchant(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.apiMerchants.insertMerchant(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 = 100;
                message = '是否上线';
                break;
            case 100:
                statusPost = 101;
                message = '是否禁用';
                break;
        }

        this.common.showConfirm(message, item => {
            if (item) {
                this.apiMerchants.editMerchantsStatus({
                    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 getEditConfigProductStatus(idPost, status: any): void {

        let statusPost;
        let message;

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

        this.common.showConfirm(message, item => {
            if (item) {
                this.apiMerchants.editConfigApiProductByStatus({
                    id: idPost,
                    status: statusPost
                }, data => {
                    if (data['return_code'] === '000000') {
                        this.message.success('提交成功');
                        this.getListMerchProduct(this.merchantId);
                    } else {
                        this.message.error(data['return_msg']);
                    }
                });
            }
        });
    }

    /**
     * 展示充值模态框
     */
    showRechargeModal() {
        this.rechargeModal = true;
    }

    /**
     * 发送验证码
     */
    sendSmsCode() {
        this.rechargeForm.controls.merchantId.enable();
        this.rechargeForm.controls.amount.enable();

        if (this.rechargeForm.value.merchantId == null) {
            this.message.error('请选择充值商户');
            return;
        }
        this.rechargeParam['merchantId'] = this.rechargeForm.value['merchantId'];
        this.rechargeParam['amount'] = this.rechargeForm.value['amount'];

        this.rechargeForm.controls.merchantId.disable();
        this.rechargeForm.controls.amount.disable();
        this.common.sendRechargeSmsCode('18090580471', this.rechargeParam['merchantId'], this.rechargeParam['amount'], data => {
            if (data['return_code'] === '000000') {
                this.getVerifyCodeCountdown();
            } else {
                this.message.error(data['return_msg']);
                this.rechargeForm.controls.merchantId.enable();
                this.rechargeForm.controls.amount.enable();
            }
        });
    }

    /**
     * 获取验证码倒计时
     */
    getVerifyCodeCountdown() {
        let countdownSecond = 60; // 倒计时60秒
        this.countdownTime = setInterval(() => {
            if (countdownSecond <= 1) {
                this.smsCodeBtnName = '获取验证码';
                this.smsCodeBtnLoading = false;
                clearInterval(this.countdownTime);
            } else {
                countdownSecond--;
                this.smsCodeBtnName = String(countdownSecond);
                this.smsCodeBtnLoading = true;
            }
        }, 1000);
    }

    /**
     * 提交充值
     */
    submitRecharge() {
        this.submitRechargeBtnLoading = true;
        // tslint:disable-next-line:forin
        for (const i in this.rechargeForm.controls) {
            this.rechargeForm.controls[i].markAsDirty();
            this.rechargeForm.controls[i].updateValueAndValidity();
        }
        this.rechargeParam.smsCode = this.rechargeForm.value['smsCode'];
        if (this.rechargeForm.status == null || this.rechargeForm.status !== 'VALID') {
            this.message.error('请填写所有必填项');
            this.submitRechargeBtnLoading = false;
            return;
        }
        this.apiMerchants.recharge(this.rechargeParam, data => {
            if (data['return_code'] === '000000') {
                this.message.success('充值成功');

                this.rechargeForm.controls.merchantId.enable();
                this.rechargeForm.controls.amount.enable();
                this.rechargeForm = this.form.group({
                    merchantId: [null, [Validators.required]],
                    amount: [null, [Validators.required]],
                    smsCode: [null, [Validators.required]],
                });

                this.rechargeModal = false;
                this.smsCodeBtnLoading = false;
                this.getRequest(false, this.searchForm.value);
            } else {
                this.message.error(data['return_msg']);
            }
            this.submitRechargeBtnLoading = false;
        });
    }


    // 请求商户充值记录
    public getMerchRechargeData(id: number): void {
        this.visible = true;
        this.apiMerchants.getMerchRechargeData(id, data => {
            if (data['return_code'] === '000000') {
                this.merchRechargeData = data['return_data'];
            } else {
                this.message.error(data['return_msg']);
            }
        });
    }

    // 配置产品
    public configProduct(id: number): void {
        this.merchantId = id;
        this.configVisible = true;
    }

    // 提交配置产品
    handleOkConfig(): void {
        // tslint:disable-next-line:forin
        for (const i in this.configValidateForm.controls) {
            this.configValidateForm.controls[i].markAsDirty();
            this.configValidateForm.controls[i].updateValueAndValidity();
            console.log(this.configValidateForm.controls[i]);
            if (this.configValidateForm.controls[i].errors != null) {
                this.message.error('必填项不能为空');
                return;
            }
        }
        this.configValidateForm.value['merchantsId'] = this.merchantId;
        this.apiMerchants.configApiProduct(this.configValidateForm.value , data => {
            if (data['return_code'] === '000000') {
                this.configVisible = false;
                this.configValidateForm.reset();
                this.message.success('提交成功');
            } else {
                this.message.error(data['return_msg']);
            }
        });
    }

    public showConfigProduct(id: number) {
        this.visibleConfigProduct = true;
        this.merchantId = id;
        this.getListMerchProduct(id);

    }

    public getListMerchProduct(id: number): void {
        this.apiProduct.getListMerchProduct(id , data => {
            if (data['return_code'] === '000000') {
                this.productConfigArray = data['return_data'];
            } else {
                this.message.error(data['return_msg']);
            }
        });
    }


    // 修改商品
    public getEditConfigProduct(id: number) {
        this.configProductId = id;
        this.apiMerchants.findConfigProduct(id , data => {
            if (data['return_code'] === '000000') {
                this.discount = data['return_data']['discount'];
            } else {
                this.message.error(data['return_msg']);
            }
        });
        this.editConfigVisible = true;
    }

    handleOkConfigEdit() {
        if (this.discount  == null) {
            this.message.error('请输入折扣比例');
        }

        const prams = {
            discount: this.discount,
            id: this.configProductId
        };
        this.apiMerchants.updateConfigApiProduct(prams , data => {
            if (data['return_code'] === '000000') {
                this.editConfigVisible = false;
                this.getListMerchProduct(this.merchantId);
            } else {
                this.message.error(data['return_msg']);
            }
        });
    }

    handleCancelConfig() {
        this.configVisible = false;
        this.configValidateForm.reset();
    }

}
