import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {HttpClient, HttpEvent, HttpEventType, HttpRequest, HttpResponse} from '@angular/common/http';
import {NzMessageService, NzModalService, UploadXHRArgs} from 'ng-zorro-antd';
import {Router} from '@angular/router';
import {LocalStorageService} from '../../../services/local-storage.service';
import {ADMIN_INFO_OBJECT} from '../../../services/local-storage.namespace';
import {environment} from '../../../../environments/environment';


@Component({
    selector: 'app-cms-content',
    templateUrl: './cms-content.component.html',
    styleUrls: ['./cms-content.component.less']
})
export class CmsContentComponent implements OnInit {
// 搜索按钮等待特效
    isLoadingSearch = false;
    // 搜索内容标题
    searchTitle = '';
    // 状态搜索
    searchStatus = '';
    // 分类搜索
    searchCategoryId = '';
    // 公司id
    searchCompanyId = '';
    // 查询数组
    requestData = [];
    // 查询数组等待特效
    loading = true;
    // 请求页码
    pageIndex = 1;
    // 请求条数
    pageSize = 10;
    // 查询总条数
    total = 0;
    /** 分类树数据 **/
    nodes = [];
    WEB_SERVE_URL;
    // 选中的内容id
    contentSelect = '';
    // 是否显示附件列表
    showPatch = 0;
    // 根据内容查询附件列表
    patchList = [];

    // 添加附件相关
    // 提交等待
    isOkLoading = false;
    // 附件类型
    patchTypeCheck = '0';
    // 附件返回地址
    patchPath = '';
    // 允许上传的文件类型
    annexForm: FormGroup;
    /** 定义附件表单 **/
    isVisible = false;
    /** 是否弹出添加 **/
    fileList = [];
    // 上传的后缀名
    suffix = '';
    // 允许上传的文件类型
    imageSuffix = [
        'jpg',
        'jpeg',
        'png',
        'jif',
        'dwg',
        'dxf',
        'jp2',
        'jpe',
        'svf',
        'tif',
        'tiff',
    ];
    audioSuffix = [
        '3gpp',
        'ac3',
        'mp2',
        'mp3',
        'asf',
        'cda',
        'wav',
        'wma',
        'mid',
        'ra',
        'rma',
        'mod',
    ];
    videoSuffix = [
        '3gpp',
        'mp2',
        'mp4',
        'mpeg',
        'mpg',
        'avi',
        'rmvb',
        'flv',
        '3pg',
        'rm',
        'mov',
        'wmv',
        'mkv',
        'f4v',
        'm4v',
    ];
    applicationSuffix = [
        'asf',
        'doc',
        'dot',
        'dtd',
        'htm',
        'html',
        'css',
        'csv',
        'js',
        'json',
        'mpp',
        'ogg',
        'pdf',
        'pot',
        'pps',
        'ppt',
        'rtf',
        'txt',
        'wdb',
        'wps',
        'xhtml',
        'xlc',
        'xlm',
        'xls',
        'xlt',
        'xlw',
        'xml',
        'zip',
        'docx',
        'xlsx',
        'pptx',
        'sql'
    ];

    isPublish = false;
    isPushOkLoading = false;
    moduleId = '';
    pushId = '';
    pushForm: FormGroup;
    // 可选择的模板列表
    selectModule = [];
    /** 按钮数据权限 **/
    BTN_cmscontent_add = 0;
    BTN_cmscontent_edit = 0;
    BTN_cmscontent_delete = 0;
    BTN_cmscontent_patch = 0;
    BTN_cmscontent_up_down = 0;

    constructor(
        private fb: FormBuilder,
        private http: HttpClient, // http请求
        private message: NzMessageService, // 信息提示
        private router: Router,
        private modalService: NzModalService, // 对话框
        private store: LocalStorageService, // 请求缓存
    ) {
        this.WEB_SERVE_URL = environment.baseUrl;
        this.searchCompanyId = this.store.get(ADMIN_INFO_OBJECT)['secUser']['companyId'];
    }

    ngOnInit() {
        /** 循环查询 按钮权限 **/
        for (let i = 0; i < this.store.get(ADMIN_INFO_OBJECT)['buttonList'].length; i++) {
            if (this.store.get(ADMIN_INFO_OBJECT)['buttonList'][i].permissionCode === 'BTN_cmscontent_add') {
                this.BTN_cmscontent_add = 1;
            }
            if (this.store.get(ADMIN_INFO_OBJECT)['buttonList'][i].permissionCode === 'BTN_cmscontent_edit') {
                this.BTN_cmscontent_edit = 1;
            }
            if (this.store.get(ADMIN_INFO_OBJECT)['buttonList'][i].permissionCode === 'BTN_cmscontent_delete') {
                this.BTN_cmscontent_delete = 1;
            }
            if (this.store.get(ADMIN_INFO_OBJECT)['buttonList'][i].permissionCode === 'BTN_cmscontent_patch') {
                this.BTN_cmscontent_patch = 1;
            }
            if (this.store.get(ADMIN_INFO_OBJECT)['buttonList'][i].permissionCode === 'BTN_cmscontent_up_down') {
                this.BTN_cmscontent_up_down = 1;
            }
        }
        this.annexForm = this.fb.group({
            patchName: [null, [Validators.required]],
            patchDesc: [null],
            patchType: [null, [Validators.required]],
            sort: [null, [Validators.required]],
        });
        this.pushForm = this.fb.group({
            moduleId: [null]
        });

        // 获取登录人 角色类型，查询分类树
        console.log(this.store.get(ADMIN_INFO_OBJECT));
        let roleType = 1;
        /* if (0 == this.store.get(ADMIN_INFO_OBJECT)['bsCompany']['companyType']) {
           roleType = 1;
         } else if (1 == this.store.get(ADMIN_INFO_OBJECT)['bsCompany']['companyType']) {
           if (this.store.get(ADMIN_INFO_OBJECT)['bsCompany']['isService'] == true) {
             roleType = 3;
           } else {
             roleType = 2;
           }
         } else if (2 == this.store.get(ADMIN_INFO_OBJECT)['bsCompany']['companyType']) {
           roleType = 3;
         }*/
        this.findCategoryTree(roleType);
        this.getRequest();
    }

    // 重置搜索
    resetSearch() {
        // 搜索内容标题
        this.searchTitle = '';
        // 状态搜索
        this.searchStatus = '';
        // 分类搜索
        this.searchCategoryId = '';
    }

    // 请求列表
    getRequest(reset: boolean = false) {
        this.showPatch = 0;
        this.loading = false;
        if (reset) {
            this.pageIndex = 1;
        }
        if (this.searchStatus == null) {
            this.searchStatus = '';
        }
        if (this.searchCategoryId == null) {
            this.searchCategoryId = '';
        }
        this.http.get(this.WEB_SERVE_URL + '/cmsContent/getListContent?pageNum=' + this.pageIndex + '&pageSize=' + this.pageSize + '&title=' + this.searchTitle + '&category=' + this.searchCategoryId + '&status=' + this.searchStatus + '&companyId=' + this.searchCompanyId).subscribe(data => {
            console.log(data);
            if (data['return_code'] === '000000') {
                this.requestData = data['return_data'].list;
                this.total = data['return_data'].total;
                this.isLoadingSearch = false;
            } else {
                this.message.create('error', data['return_msg']);
            }
        });
    }

    // 搜索
    getSearch() {
        this.getRequest();
    }

    // 查询分类树
    findCategoryTree(roleType) {
        this.http.get(this.WEB_SERVE_URL + '/cmsCategory/getOwnCategoryTree?roleType=' + roleType).subscribe(data => {
            if (data['return_code'] === '000000') {
                this.nodes = data['return_data'];
                if (this.nodes.length !== 0) {
                    this.generateComment(this.nodes);
                } else {
                    this.nodes = [];
                }
            } else {
                this.message.create('error', data['return_msg']);
            }
        });
    }

    // 递归分类树
    generateComment(data) {
        for (const i in data) {
            if (data[i].nodes == null) {
                const item = {
                    /** 重新赋值 **/
                    isLeaf: true,
                    title: data[i].text,
                    key: data[i].id,
                    children: data[i].nodes,
                };
                data[i] = item;
            } else {
                const item = {
                    /** 重新赋值 **/
                    isLeaf: false,
                    title: data[i].text,
                    key: data[i].id,
                    children: data[i].nodes,
                };
                data[i] = item;
                this.generateComment(data[i].children);
            }
        }
        this.nodes = data;
        console.log(this.nodes);
    }

    // 跳转添加
    getAdd() {
        this.router.navigate(['/admin/cms/cmscontentadd'], {
            queryParams: {
                editFlag: 0
            }
        });
    }

    // 跳转修改
    getEdit(id) {
        this.router.navigate(['/admin/cms/cmscontentedit'], {
            queryParams: {
                id: id
            }
        });
    }

    // 跳转详情
    getContentView(id) {
        this.router.navigate(['/admin/cms/cmscontentview'], {
            queryParams: {
                id: id
            }
        });
    }

    // 对话框删除
    showDeleteConfirmDelete(id): void {
        this.modalService.confirm({
            nzTitle: '是否确定删除',
            nzOkText: '是',
            nzOnOk: () => this.deleteContent(id),
            nzCancelText: '否',
        });
    }

    // 删除内容
    deleteContent(id) {
        if (id === undefined) {
            return;
        }
        if (id === null) {
            return;
        }
        if (id === '') {
            return;
        }
        this.http.get(this.WEB_SERVE_URL + '/cmsContent/delContent?id=' + id).subscribe(data => {
            if (data['return_code'] === '000000') {
                this.message.create('success', `删除成功！`);
                this.getRequest();
            } else {
                this.message.create('warning', data['return_msg']);
            }
        });
    }

    // 查询附件列表
    findPatchByContent(id) {
        this.contentSelect = id;
        this.http.get(this.WEB_SERVE_URL + '/cmsContent/getListPatches?pageNum=1&pageSize=100&contentId=' + id).subscribe(data => {
            if (data['return_code'] === '000000') {
                this.showPatch = 1;
                this.patchList = data['return_data'].list;
                console.log(this.patchList);
            } else {
                this.message.create('warning', data['return_msg']);
            }
        });
    }

    // 弹出添加附件
    addPatch() {
        this.isVisible = true;
    }

    // 删除附件确认
    showDeletePatch(id) {
        this.modalService.confirm({
            nzTitle: '是否确定删除',
            nzOkText: '是',
            nzOnOk: () => this.deletePatch(id),
            nzCancelText: '否',
        });
    }

    // 删除附件
    deletePatch(id) {
        if (id === undefined || id === null || id === '') {
            return;
        }
        this.http.get(this.WEB_SERVE_URL + '/cmsPatch/delPatch?id=' + id).subscribe(data => {
            if (data['return_code'] === '000000') {
                this.message.create('success', `删除成功！`);
                this.findPatchByContent(this.contentSelect);
            } else {
                this.message.create('warning', data['return_msg']);
            }
        });
    }

    // 取消按钮
    handleCancel(): void {
        this.isVisible = false;
        this.patchPath = '';
        this.fileList = [];
        /** 隐藏弹框 **/
    }

    // 附件类型选择
    getChange(event) {
        if (event != null) {
            this.patchTypeCheck = event;
            console.log(event);
        }
    }

    // 附件上传设置
    customReq = (item: UploadXHRArgs) => {
        this.patchPath = ''; // 置空路径
        const formData = new FormData();
        formData.append('requestFile', item.file as any);
        formData.append('uploadType', 'cmsPatch');
        console.log(item);
        const req = new HttpRequest('POST', item.action!, formData, {
            reportProgress: true,
        });
        console.log(req);
        return this.http.request(req).subscribe(
            (event: HttpEvent<any>) => {
                console.log(event);
                if (event.type === HttpEventType.UploadProgress) {
                    if (event.total! > 0) {
                        (event as any).percent = (event.loaded / event.total!) * 100;
                    }
                    item.onProgress!(event, item.file!);
                } else if (event instanceof HttpResponse) {
                    item.onSuccess!(event.body, item.file!, event);
                    if (event.body.return_code === '000000') {
                        this.patchPath = event.body.return_data[item.file.name];
                        this.suffix = this.patchPath.split('.')[this.patchPath.split('.').length - 1];
                    }
                }
            },
            err => {
                item.onError!(err, item.file!);
            }
        );
    }

    /** 清空 **/
    emptyForm(e: MouseEvent): void {
        e.preventDefault();
        this.annexForm.reset();
        for (const key in this.annexForm.controls) {
            this.annexForm.controls[key].markAsPristine();
            this.annexForm.controls[key].updateValueAndValidity();
        }
    }

    // 附件弹窗确定添加按钮
    handlePatchOk(value: any): void {
        // 校验类型选择与必填
        if (value.patchName == null || value.patchName == '') {
            this.message.create('error', `请填写附件名称！`);
            return;
        }
        if (value.sort == null || value.sort == '') {
            this.message.create('error', `请填写附件排序，越小越靠前！`);
            return;
        }
        if (value.patchType == '1') {
            if (this.imageSuffix.indexOf(this.suffix) == -1) {
                this.message.create('error', `请上传图片类型的附件！`);
                return;
            }
        } else if (value.patchType == '2') {
            if (this.audioSuffix.indexOf(this.suffix) == -1) {
                this.message.create('error', `请上传音频类型的附件！`);
                return;
            }
        } else if (value.patchType == '3') {
            if (this.videoSuffix.indexOf(this.suffix) == -1) {
                this.message.create('error', `请上传视频类型的附件！`);
                return;
            }
        } else if (value.patchType == '4') {
            if (this.applicationSuffix.indexOf(this.suffix) == -1) {
                this.message.create('error', `请上传文档类型的附件！`);
                return;
            }
        } else if (value.patchType == '5') {
        } else {
            this.message.create('error', `请选择附件类型！`);
            return;
        }
        if (this.patchPath == null || this.patchPath == '') {
            this.message.create('error', `请上传附件！`);
            return;
        }
        // 定义附件数据
        const params = {
            'contentId': this.contentSelect,
            'patchName': value.patchName,
            'patchDesc': value.patchDesc,
            'patchType': value.patchType,
            'patchPath': this.patchPath,
            'source': 1,
            'sort': value.sort,
            'suffixName': this.suffix,
            'addTime': new Date()
        };
        /** 确定等待 **/
        this.http.post(this.WEB_SERVE_URL + '/cmsPatch/addPatch', params).subscribe(data => {
            if (data['return_code'] === '000000') {
                this.isVisible = false;
                this.isOkLoading = false;
                this.fileList = [];
                this.patchTypeCheck = '0';
                this.findPatchByContent(this.contentSelect);
                this.message.create('success', `新增成功！`);
            } else {
                this.message.create('warning', data['return_msg']);
            }
        }, error => {
            this.message.create('error', `未知错误！`);
        });
    }

    // 弹出发布附件
    addPush(id, categoryId) {
        this.findModuleByCategory(categoryId);
        this.pushId = id;
        // document.getElementById('resetPush').click();
        this.isPublish = true;
    }

    // 取消发布
    handleCancelPush(): void {
        this.isPublish = false;
        this.moduleId = '';
        this.pushId = '';
        /** 隐藏弹框 **/
    }

    // 附件弹窗确定添加按钮
    handlePushOk(value: any): void {
        console.log('发布');
        console.log(this.pushId);
        console.log(this.moduleId);
        console.log(value.moduleId);
        if (this.pushId == null || this.pushId == '') {
            this.message.create('error', '请重新选择发布的内容！');
            return;
        }
        if (this.moduleId == null || this.moduleId == undefined) {
            this.moduleId = '';
        }

        // 定义附件数据
        const params = {
            'id': this.pushId,
            'status': 2,
            'moduleId': this.moduleId
        };
        /** 确定等待 **/
        this.http.post(this.WEB_SERVE_URL + '/cmsContent/updateStatusOfContent', params).subscribe(data => {
            if (data['return_code'] === '000000') {
                this.isPublish = false;
                this.isPushOkLoading = false;
                this.moduleId = '';
                this.pushId = '';
                this.getRequest();
                this.message.create('success', `发布成功！`);
            } else {
                this.message.create('warning', data['return_msg']);
            }
        }, error => {
            this.message.create('error', `未知错误！`);
        });
    }

    /** 清空模板 **/
    emptyPushForm(e: MouseEvent): void {
        e.preventDefault();
        this.pushForm.reset();
        for (const key in this.pushForm.controls) {
            this.pushForm.controls[key].markAsPristine();
            this.pushForm.controls[key].updateValueAndValidity();
        }
    }

    // 根据内容分类查询可使用的模板列表
    findModuleByCategory(categoryId) {
        this.http.get(this.WEB_SERVE_URL + '/cmsCategoryModule/getModuleByCategoryId?categoryId=' + categoryId).subscribe(data => {
            if (data['return_code'] === '000000') {
                this.selectModule = data['return_data'];
                console.log(this.selectModule);
            } else {
                this.message.create('error', data['return_msg']);
            }
        });
    }

    showDown(id): void {
        this.modalService.confirm({
            nzTitle: '是否确定下线',
            nzOkText: '是',
            nzOnOk: () => this.DownContent(id),
            nzCancelText: '否',
        });
    }

    // 下线
    DownContent(id) {
        // 定义附件数据
        const params = {
            'id': id,
            'status': 1
        };
        /** 确定等待 **/
        this.http.post(this.WEB_SERVE_URL + '/cmsContent/updateStatusOfContent', params).subscribe(data => {
            if (data['return_code'] === '000000') {
                this.getRequest();
                this.message.create('success', `下线成功！`);
            } else {
                this.message.create('warning', data['return_msg']);
            }
        }, error => {
            this.message.create('error', `未知错误！`);
        });
    }
}
