import { tpl, tbodyTpl } from './couponTpl';
import PageTable from '@core/component/pageTable';
import sendHttp,{fetch} from '@core/component/httpClient';
import ShortPagination from '@core/component/shortPagination';
import Message from '@core/component/message';
import Validator from '@core/component/validator';
import { Messager } from '@core/component/msgDistribute';
import LinkTool from '../../linkTool';
import domain from '@core/util/domain';
import DefaultDatasM from '@core/component/form/DefaultDatasM';
const Coupon = (($) => {
    const DefaultConfig = {
        tpl,
        tbodyTpl
    };
    class Coupon {
        constructor(config) {
            this._config = this._getConfig(config);
            this.el = this._config.node;
            this.$el = $(this.el);
            let html = template.render(this._config.tpl, this._config);
            this.$el.html(html);
            this.pageTable = new PageTable({
                node: this.$el.find('.J_table')[0],
                className: "cd-mytable",
                theadRenderer: ['券putKey', '券名称', '券信息', '适用范围'],
                itemRenderer: this._config.tbodyTpl,
                pageSize: 6,
                loading: true,
                columnWidth: ["49%", "17%", "17%", "17%"],
                fixedThead: true,
                frontEndPaging: false,
                pagination: ShortPagination,
                onDomReady: ($node) => {
                    console.log("onDomReady:");
                },
                onPageChange: (data) => {
                    this.queryData(data.selected);
                },
                onDomUpdate: this._config.onDomUpdate
            })
            this.queryData();
            this._addEvent();
        }
        
        getParentLinkObj(){
            if(this._config && this._config.getParentLinkObj){
                return this._config.getParentLinkObj();
            }
            return null;
        }
        
        checkNeedTip(){
            let result = true;
            let linkObj = this.getParentLinkObj();
            if(linkObj && linkObj.link == '' && linkObj.linkType == 1 && linkObj.originalData == ''){
                result = false;
            }
            return result;
        }
        
        async queryData() {
            const { isFansCoupon } = this._config;
            let { platformId, shopType } = this._config.env;
            (shopType === 3 || shopType === 4) && (shopType = 0); 
            (shopType === 5) && (shopType = 3); 
            let data;
            const url = `${domain.backend}/mshop/coupon/listCoupon`;
            if(window.page_data.isSDKM){
                data = DefaultDatasM.linkTool.listCoupon;
            }
            else{
                let linkObj = this._config.linkObj;
                const originalData = linkObj.originalData;
                const arrCoupon = this._config.selected.coupon;
                data = await fetch({
                    url,
                    data: {
                        putKey: originalData,   
                        selectKeys: this._config.selected && Array.isArray(arrCoupon)? arrCoupon.join(','): '',  
                        shopType,
                        platformId,
                        couponType: isFansCoupon ? 2 : 1
                    },
                    dataType: 'jsonp',
                });
            }
            if (data.result === true) {
                let linkObj = this._config.linkObj;
                if(linkObj){
                    let needTip = false;    
                    if(linkObj.linkType == LinkTool.Type.Coupon){
                        const originalData = linkObj.originalData;
                        if (originalData && data.data.list.every(item => item.current === false)) {
                            const ruleId = originalData;
                            const { platformId, shopType } = this._config.env;
                            const systemId = (shopType === 1 ? 2 : 1);
                            const appType = (platformId === 0 ? 1 : 2);
                            const list = (await Promise.all(ruleId.split(',').map(v => getCouponInfo(v, systemId, appType)))).filter(v => v !== null);
                            data.data.list = [...list, ...data.data.list];
                            needTip = true;
                        }
                    }
                    this.refreshList(data.data.list);
                    if(linkObj.linkType == LinkTool.Type.Coupon && needTip && this.checkNeedTip()){
                        if (linkObj.linkType !== 1 && $(`[${this._config.linkAttr}]:checked`, this.$el).length === 0) {
                            Message.error('上次保存的优惠券已失效或活动已过期，请重新选择。');
                            Messager.trigger('linkChange', { link: '', linkType: 1, originalData: '' });
                        }
                    }
                }
            } else {
                Message.error(data.msg);
            }
        }
        
        _addEvent() {
            let _this = this;
            
            this.linkChangeKey = Messager.on('linkChange', (req, res) => {
                if(res.isFromClick || window.page_data.isSDKM){
                    this.$el.find('[' + _this._config.linkAttr + ']').each(function() {
                        let val = $(this).attr('data-original-data');
                        if (val === res.originalData) {
                            this.checked = true;
                        } else {
                            this.checked = false;
                        }
                    })
                }
            })
            
            this.$el.on('change.coupon', '[' + _this._config.linkAttr + ']', function() {
                let link = $(this).attr(_this._config.linkAttr);
                let linkType = LinkTool.Type.Coupon;
                let originalData = $(this).attr(_this._config.originalDataAttr);
                Messager.trigger('linkChange', { link, linkType, originalData, isFromClick: true});
            })
            
            this.$el.on('click.coupon', 'table tbody tr', function() {
                $(this).find('input[type=radio]').trigger('change');
            })
            
            this.$el.on('click.coupon', '.J_ok', function() {
                Messager.trigger('confirm');
            })
            
            this.$el.on('dblclick.coupon', 'table tbody tr', function() {
                Messager.trigger('confirm');
            })
            
            this.$el.on('click.coupon', '.J_cancel', function() {
                Messager.trigger('cancel');
            })
            this.$el.on('click.coupon', '.J_search', search.bind(this));
            this.$el.on('submit.coupon', '.J_searchFrom', () => {
                search.call(this);
                return false;
            });
            this.$el.on('click.coupon', '.J_restore', async() => {
                this.$el.find('.J_roleId').val('');
                this.queryData();
            });
            async function search() {
                const ruleId = this.$el.find('.J_roleId').val().replace(/，/g, ',').trim();
                if(ruleId){
                    const { platformId, shopType } = this._config.env;
                    const systemId = (shopType === 1 ? 2 : 1);
                    const appType = (platformId === 0 ? 1 : 2);
                    const list = (await Promise.all(ruleId.split(',').map(v => getCouponInfo(v, systemId, appType)))).filter(v => v !== null);
                    if (list.length === 0) {
                        Message.error(`putKey为${ruleId}的优惠券已失效或活动已过期！`);
                    }
                    this.refreshList(list);
                }
            }
        }
        refreshList(data) {
            if (data.length === 0) return;
            this.pageTable.update({
                loading: false,
                dataProvider: data,
            })
        }
        
        _getConfig(config) {
            return $.extend(true, {}, DefaultConfig, config);
        }
        
        dispose() {
            Messager.off(this.linkChangeKey);
            this.$el.off('linkChange.coupon').off('change.coupon').off('click.coupon').off('dblclick.coupon');
        }
    }
    
    async function getCouponInfo(putKey, systemId = 1, appType = 1) {
        const getCustomInfo = (putKey) => {
            return fetch({
                url: `${domain.fMall}/couponActiveAll/getAllInfo`,      
                dataType: 'jsonp',
                data: {
                    ruleId: putKey,
                }
            })
        }
        const getUrlInfo = (originData, systemId, appType) => {
            return fetch({
                url: `${domain.backend}/mshop/coupon/getCouponLink`,
                dataType: 'jsonp',
                data: {
                    originData,
                    systemId,
                    appType,
                }
            })
        }
        const joinResult = await Promise.all([getCustomInfo(putKey), getUrlInfo(putKey, systemId, appType)]);
        let [customInfo, urlInfo] = joinResult;
        let result = {};
        if (customInfo.success === true && customInfo.data.length > 0) {
            let list = customInfo.data.filter(v => v.success === true);
            list = list.map((v) => {
                let result = v.couponBatchAllList[0];
                result.putKey = v.putKey;
                return result;
            })
            list = list.map((v) => {
                v.label = `满${v.quota}减${v.discount}`;
                v.name = v.couponTitle;
                return v;
            })
            if (!list[0] || list[0].activeYn !== 1 || list[0].yn !== 1 || list[0].activityEndTime < Date.now()) {
                return null;
            }
            result = list[0];
        }
        if (urlInfo && urlInfo.success === true && urlInfo.data) {
            result.link = urlInfo.data.link;
        }
        return result;
    }
    return Coupon;
})($);
export default Coupon;