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

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

    WEB_SERVE_URL = environment.imageUrl;
    inviteUrl = environment.inviteUrl;
    searchForm: FormGroup; // 搜索框
    validateForm: FormGroup; // 搜索框
    validateFormDistribute: FormGroup; // 搜索框
    requestData = []; // 列表数据
    discountList = []; // 列表数据
    couponList = []; // 列表数据
    distributeList = []; // 列表数据
    total: number; // 页码
    pageNum = 1; // 页码
    pageSize = 10; // 条码
    loading = true;
    isVisible = false;
    isVisibleDiscount = false;
    isVisibleDistribute = false;
    isVisibleList = false;
    id: number;
    isSpinning = false;
    isSpinningDistribute = false;
    requestDataDiscount = []; // 列表数据
    totalDiscount: number; // 页码
    pageNumDiscount = 1; // 页码
    pageSizeDiscount = 10; // 条码
    loadingDiscount = true;
    agentId: number;
    requestDataList = []; // 列表数据
    totalList: number; // 页码
    pageNumList = 1; // 页码
    pageSizeList = 10; // 条码
    loadingList = true;
    isOkLoading = false;
    isVisibleShow = false;
    dataSet;
    constructor(
        private form: FormBuilder,
        private agent: AgentService,
        private audit: AuditService,
        private discount: DiscountService,
        private coupon: CouponService,
        private iconService: IconService,
        private message: NzMessageService,
        private router: Router,
        private clipboardService: ClipboardService,
        private common: CommonsService
    ) {
    }

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

    public init(): void {
        this.searchForm = this.form.group({
            agentName: [null],
            agentPhone: [null],
            status: [null],
            type: [null],
        });
        this.validateForm = this.form.group({
            discountId: [null, [Validators.required]],
            stockCount: [null, [Validators.required]],
        });
        this.validateFormDistribute = this.form.group({
            couponId: [null, [Validators.required]],
            type: [null, [Validators.required]],
            stockCount: [null, [Validators.required]],
        });
        this.getRequest(true, this.searchForm.value);

        this.coupon.getCouponListByAll({} , data => {
            if (data['return_code'] === '000000') {
                this.couponList = 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.agent.getListAgent(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 getForbiddenUser(id, status: any): void {
        const message = (status === 1 ? '是否禁用当前代理商' : '是否启用当前代理商');

        this.common.showConfirm(message, data => {
            if (data) {
                this.agent.editStatus(id, dataUser => {
                    this.getRequest(false, this.searchForm.value);
                });
            }
        });
    }

    // 修改
    public getEdit(id: number): void {
        this.router.navigate(['/admin/agent/agent-edit'], {
            queryParams: {
                agentId: id
            }
        }).then(r => console.log(r));
    }

    // 查看详情
    public getDetail(id: number): void {
        this.router.navigate(['/admin/company/company-detail'], {
            queryParams: {
                companyId: id
            }
        }).then(r => console.log(r));
    }

    // 绑定优惠券
    public getDiscount(id: number): void {
        this.id = id;
        const whereObject = {};
        whereObject['pageNum'] = 1;
        whereObject['pageSize'] = 10000;
        this.discount.getDiscountList(whereObject, data => {
            if (data['return_code'] === '000000') {
                this.discountList = data['return_data'].list;
            } else {
                this.message.error(data['return_msg']);
            }
        });
        this.isVisible = true;
    }

    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;
            }
        }
        // this.isSpinning = true;
        this.validateForm.value['agentId'] = this.id;
        this.agent.insertDiscountAgent(this.validateForm.value , data => {
            if (data['return_code'] === '000000') {
                this.message.success('生成中，请耐心等待！');
                this.isVisible = false;
            } else {
                this.message.error(data['return_msg']);
            }
            this.isSpinning = false;
        });
    }

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

    public getDiscountList(id: number): void {
        this.id = id;
        this.isVisibleDiscount = true;
        this.getRequestDiscount(true);
    }

    public getDistributionList(id: number): void {
        this.id = id;
        this.isVisibleList = true;
        this.getRequestList(true);
    }

    handleCancelList() {
        this.isVisibleList = false;
    }

    handleCancelDiscount() {
        this.isVisibleDiscount = false;
    }
    handleCancelDistribute() {
        this.isVisibleDistribute = false;
    }
    // 查询列表
    public getRequestDiscount(reset: boolean = false) {
        const whereObject = {};
        this.loadingDiscount = true;
        if (reset) {
            this.pageNumDiscount = 1;
        }
        whereObject['pageNum'] = this.pageNumDiscount;
        whereObject['pageSize'] = this.pageSizeDiscount;
        whereObject['agentId'] = this.id;
        this.agent.getDiscountAgentList(whereObject, data => {
            this.loadingDiscount = false;
            if (data['return_code'] === '000000') {
                this.requestDataDiscount = data['return_data'].list;
                this.totalDiscount = data['return_data'].total;
            } else {
                this.message.error(data['return_msg']);
            }
        });
    }

    // 提交分发审批
    public addApprove(): void {

        // tslint:disable-next-line:forin
        for (const i in this.validateFormDistribute.controls) {
            this.validateFormDistribute.controls[i].markAsDirty();
            this.validateFormDistribute.controls[i].updateValueAndValidity();
            if (this.validateFormDistribute.controls[i].errors != null) {
                this.message.error('必填项不能为空');
                return;
            }
        }
        this.isOkLoading = true;

        this.validateFormDistribute.value['agentName'] = this.requestData.find(data => data.id = this.agentId).agentName;
        this.validateFormDistribute.value['couponName'] = this.couponList.find(data => data.id = this.validateFormDistribute.value['couponId']).couponName;
        this.validateFormDistribute.value['agentId'] = this.agentId;

        const whereObject = {
            objectType: 3,
            approveObject: this.validateFormDistribute.value,
        };

        this.audit.addApprove(whereObject , data => {
            if (data['return_code'] === '000000') {
                this.validateFormDistribute.reset();
                this.message.success('提交成功');
                this.isVisibleDistribute = false;
            } else {
                this.message.error(data['return_msg']);
            }
            this.isOkLoading = false;
        });

    }

    // 分发卡券
    public getDistribution(id: number): void {
        this.isSpinningDistribute = true;
        this.agentId = id;
        const whereObject = {};
        whereObject['pageNum'] = 1;
        whereObject['pageSize'] = 10000;
        this.coupon.getCouponList(whereObject, data => {
            if (data['return_code'] === '000000') {
                this.distributeList = data['return_data'].list;
            } else {
                this.message.error(data['return_msg']);
            }
            this.isSpinningDistribute = false;
        });
        this.isVisibleDistribute = true;
    }

    // 查询f分发列表
    public getRequestList(reset: boolean = false) {
        const whereObject = {};
        this.loadingList = true;
        if (reset) {
            this.pageNumList = 1;
        }
        whereObject['pageNum'] = this.pageNumList;
        whereObject['pageSize'] = this.pageSizeList;
        whereObject['agentId'] = this.id;
        this.agent.getCouponByAgent(whereObject, data => {
            this.loadingList = false;
            if (data['return_code'] === '000000') {
                this.requestDataList = data['return_data'].list;
                this.totalList = data['return_data'].total;
            } else {
                this.message.error(data['return_msg']);
            }
        });
    }

    // 提交分发
    public handleOkDistribute(): void {
        // tslint:disable-next-line:forin
        for (const i in this.validateFormDistribute.controls) {
            this.validateFormDistribute.controls[i].markAsDirty();
            this.validateFormDistribute.controls[i].updateValueAndValidity();
            if (this.validateFormDistribute.controls[i].errors != null) {
                this.message.error('必填项不能为空');
                return;
            }
        }
        this.isOkLoading = true;
        this.validateFormDistribute.value['agentId'] = this.agentId;
        this.agent.assignCouponAgent(this.validateFormDistribute.value , data => {
            if (data['return_code'] === '000000') {
                this.validateFormDistribute.reset();
                this.message.success('分发成功');
                this.isVisibleDistribute = false;
                this.isOkLoading = false;
            } else {
                this.message.error(data['return_msg']);
            }
            this.isSpinning = false;
        });
    }

    public getList(id: number): void {
        const whereObject = {};
        whereObject['pageNum'] = 1;
        whereObject['pageSize'] = 10000;
        whereObject['couponAgentId'] = id;
        this.isVisibleShow = true;
        this.agent.getRecordByCouponAgentId(whereObject , data => {
            if (data['return_code'] === '000000') {
                this.dataSet = data['return_data'].list;
            } else {
                this.message.error(data['return_msg']);
            }
        });
    }

    handleCancelListShow() {
        this.isVisibleShow = false;
    }

    public generateAgentQrCode(id: number): void {
        this.agent.generateRechargeAgentQrCode(id, data => {
            if (data['return_code'] === '000000') {
                window.location.href = this.WEB_SERVE_URL + data['return_data'];
            } else {
                this.message.error(data['return_msg']);
            }
        });
    }


    copyReceiveDiscountLink(id: number) {
        this.agent.getReceiveLink(id, data => {
           if (data['return_code']) {
               this.clipboardService.copy(data['return_data']);
               this.message.success('复制成功');
           } else {
               this.message.error('复制失败');
           }
        });
    }
}

