import {Component, OnInit} from '@angular/core';
import {ActivatedRoute} from '@angular/router';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {NzMessageService, NzModalService, NzUploadChangeParam} from 'ng-zorro-antd';
import {CouponService} from '../../../services/coupon.service';
import {environment} from '../../../../environments/environment';

@Component({
    selector: 'app-sales-code-list',
    templateUrl: './sales-code-list.component.html',
    styleUrls: ['./sales-code-list.component.scss']
})
export class SalesCodeListComponent implements OnInit {
    FILE_URL = environment.imageUrl;
    searchForm: FormGroup; // 搜索框
    codeForm: FormGroup; // 搜索框
    requestData = []; // 列表数据
    total: number; // 页码
    pageNum = 1; // 页码
    pageSize = 10; // 条码
    loading = true;
    exportLoading = false;
    id = null;
    name: string;
    type: number;
    isVisible = false;
    WEB_SERVE_URL = environment.baseUrl;
    importErrorStudentArray = [];
    errorStudentVisible = false;

    exportSalesCodeModal = false;
    exportSalesCodeForm: FormGroup;

    constructor(
        private form: FormBuilder,
        private activatedRoute: ActivatedRoute,
        private message: NzMessageService,
        private modal: NzModalService,
        private coupon: CouponService
    ) {
    }

    ngOnInit(): void {
        this.activatedRoute.queryParams.subscribe(queryParams => {
            if (queryParams.couponId != null) {
                this.id = queryParams.couponId;
                this.name = queryParams.name;
                this.type = Number(queryParams.type);
                this.searchForm = this.form.group({
                    status: [null],
                    salesCode: [null],
                });
                this.getRequest(true, this.searchForm.value);
            }
        });
        this.codeForm = this.form.group({
            salesEndTime: [null, [Validators.required]],
            useEndTime: [null, [Validators.required]],
            generateNum: [null, [Validators.required]],
        });

        this.exportSalesCodeForm = this.form.group({
            createTime: [null],
            status: [null],
        });
    }

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

        this.loading = false;
        if (reset) {
            this.pageNum = 1;
        }
        whereObject['couponId'] = this.id;
        whereObject['pageNum'] = this.pageNum;
        whereObject['pageSize'] = this.pageSize;
        this.coupon.getCouponCodeList(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();
    }

    showModal(): void {
        this.isVisible = true;
    }

    handleOk(): void {
        // tslint:disable-next-line:forin
        for (const i in this.codeForm.controls) {
            this.codeForm.controls[i].markAsDirty();
            this.codeForm.controls[i].updateValueAndValidity();
            if (this.codeForm.controls[i].errors != null) {
                this.message.error('必填项不能为空');
                return;
            }
        }
        this.codeForm.value['couponId'] = this.id;
        this.coupon.writeStock(this.codeForm.value , data => {
            if (data['return_code'] === '000000') {
                this.getRequest(true, this.searchForm.value);
                this.message.success('生成成功');
            } else {
                this.message.create('error', '生成失败');
            }
        });
        this.isVisible = false;
    }

    handleCancel(): void {
        console.log('Button cancel clicked!');
        this.isVisible = false;
    }

    handleCancelError(): void {
        this.errorStudentVisible = false;
    }

    handleChange(info: NzUploadChangeParam): void {
        if (info.file.status === 'done') {
            if (info.file.response.return_code === '000000') {
                this.loading = false;
                if (info.file.response.return_data == null || info.file.response.return_data.errorTotal === 0) {
                    this.message.success('导入成功');
                    this.getRequest(true, this.searchForm.value);
                } else {
                    this.modal.warning({
                        nzTitle: '提示',
                        nzOkText: '查看失败数据',
                        nzContent: '只有部分数据导入成功',
                        nzOnOk: () => this.showErrorStudentModal(info.file.response.return_data)
                    });
                }
            } else {
                this.loading = false;
                this.message.error(info.file.response.return_msg);
            }
        } else if (info.file.status === 'error') {
            this.message.error('上传错误');
        }
    }

    //  打开模态框
    showErrorStudentModal(data: []) {
        this.getRequest(true, this.searchForm.value);
        this.importErrorStudentArray = data['errorData'];
        this.errorStudentVisible = true;
    }

    /**
     * 打开销售码数据
     */
    showExportSalesCodeModal() {
        this.exportSalesCodeModal = true;
    }

    /**
     * 导出销售码数据
     */
    exportSalesCodeData() {
        this.exportLoading = true;
        this.exportSalesCodeForm.value['couponId'] = this.id;
        if (this.exportSalesCodeForm.value.createTime != null) {
            this.exportSalesCodeForm.value['createTimeS'] = this.exportSalesCodeForm.value.createTime[0];
            this.exportSalesCodeForm.value['createTimeE'] = this.exportSalesCodeForm.value.createTime[1];
        } else {
            this.exportSalesCodeForm.value['createTimeS'] = null;
            this.exportSalesCodeForm.value['createTimeE'] = null;
        }
        this.coupon.exportStock(this.exportSalesCodeForm.value, data => {
            if (data['return_code'] === '000000') {
                window.location.href = this.FILE_URL + 'temporary/' + data['return_data'];
            } else {
                this.message.error(data['return_msg']);
            }
            this.exportLoading = false;
        });
    }

    /**
     * 关闭销售码数据
     */
    closeExportSalesCodeModal() {
        this.exportSalesCodeModal = true;
    }
}
