import React from "react";
import styles from "./index.css";
import { getData } from "../../api/index";
import Box from "../../components/Box/index.jsx";
import Title from "../../components/Title/index.jsx";
import { LevelList2 } from "../../components/LeveList2/index.jsx";
import EditTpl from "../../components/edit/index";

import { LevelList1 } from '../../components/LevelList1/index.jsx';
import { NumTostring } from '../../components/numTostring';
var QRCode = require('qrcode.react');

class Industry extends React.Component {
    state = {
        //商品列表 搜索 接口配置
        productListData: {
            data: {
                list: []
            }
        },
        //搜索框
        inputValue: "",
        //分类数据
        classificationListData: {
            data: {
                list: []
            }
        },
        ProductDetailsData: {
            data: {

            }
        },
        //产品轮播下标
        productSubscript: 0,
        activeItem:2
    }

    //搜索功能
    searTime = null;
    searchValue = e => {
        e.persist();
        const search = e.target.value || '';
        this.setState({
            inputValue: search
        });
        clearTimeout(this.searTime);
        this.searTime = setTimeout(() => {
            this.searchDealWith({
                search
            });
        }, 800);
    }

    //搜索函数
    searchDealWith(e = {},index) {
        const {
            match: {
                params = {}
            }
        } = this.props;
        //商品列表 搜索 接口配置 productListData
        getData({
            port: "productListData",
            ...params,
            params: {
                pageNum: 1,
                pageSize: 5000,
                ...e
            }
        }).then(res => {
            const { config, config: {
                data: {
                    list = []
                }
            } } = res;
            this.setState({ productListData: config,activeItem:index || 0});
            this.getProductDetails(list[0] || {}, 0);
            list.length && this.startProductCarousel();
        });
    }
    //分类查询
    classification = e => {
        const {
            match: {
                params = {}
            }
        } = this.props;
        getData({
            port: "classificationListData",
            ...params
        }).then(res => {
            const { config, config: {
                data: {
                    list = []
                }
            } } = res;
            this.setState({ classificationListData: config});
            this.searchDealWith({
                typeId: (list[this.state.activeItem] || {}).id || ''
            },this.state.activeItem);
        });
    }
    //获取详情
    getProductDetails = (e = {}, productSubscript) => {
        const {
            match: {
                params = {}
            }
        } = this.props;
        this.setState({ productSubscript });
        return getData({
            port: "ProductDetailsData",
            ...params,
            params: {
                ...e
            }
        }).then(res => {
            const { config } = res;
            const {data:{id = ''}} = config;
            config.data.qrcode = id?`http://wxh5.gzqlyx.com/#/pages/product/product?id=${id}`:'';
            this.setState({ ProductDetailsData: config, productSubscript });
        });
    }

    carouselTime = null;
    //start启动产品轮播
    startProductCarousel = e => {
        clearTimeout(this.carouselTime);
        const time = this.state.productListData.data.scrollTime - 0 || 0;
        time && (this.carouselTime = setTimeout(e => {
            const {
                data: {
                    list = []
                }
            } = this.state.productListData;
            const index = this.state.productSubscript < list.length - 1 ? this.state.productSubscript + 1 : 0;
            this.getProductDetails(list[index], index).then(e => {
                this.startProductCarousel();
            });
        }, time));
    }

    componentDidMount() {
        this.classification();
    }

    componentWillUnmount() {
        //组件销毁
        clearTimeout(this.carouselTime);
    }
    //进入内页
    goLink = (e,i)=>{
        //处理path  替换 页面 与 pId
        let {match:{
            path,
            url
        }} = this.props;
        url = url.split("/");
        path = path.split("/").map((x,i)=>{
            const iu = url[i];
            if(i == 1){
                return "detail";
            }
            const k = x.indexOf(":"),
                    j = x.indexOf("?");
                if (k != -1) {
                    x = x.substring(k + 1, j);
                }
                if (x == 'pId') {
                   return iu+"-"+e.id;
                }
                return iu;
        }).join("/");
        return path;  
    }
    LevelList2Click(e){
        const {data:{minTitle = [],firmId}} = this.state.ProductDetailsData;
        if((minTitle[e] || {}).key === 'umsCompanyInfo'){
            this.props.history.push(this.goLink({id:firmId}));
        }
    }
    render() {
        const { productSubscript, classificationListData, productListData, inputValue, ProductDetailsData, ProductDetailsData: { data: DetailsData } ,activeItem=0} = this.state,
            p_list = (((productListData || {}).data || {}).list || []);
        const PovertyAlleviationArticle = {
            data: {
                list: (DetailsData.minTitle || []).map(x=>{
                    return {
                        title:x.name,
                        name:DetailsData[x.key]
                    }
                }),
                a:['brandName', 'spec', 'qualityGuaranteePeriod', 'placeOfProduction', 'umsCompanyInfo'].map((x, i) => {
                    const name = DetailsData[x];
                    if (name) {
                        return {
                            title: DetailsData[`minTitle${i + 1}`],
                            name
                        }
                    }
                }).filter(x => {
                    if (x) return x;
                })
            }
        };
        return (
            <div className={styles.Box}>
                <div className={styles.Left}>
                    <Box no={true} style={{ height: "100%" }} className={styles.LeftBox}>
                        <EditTpl
                            style={{
                                bottom: "auto"
                            }}
                            data={productListData}
                            upData={productListData => this.setState({ productListData })}></EditTpl>
                        <div className={styles.searchBox}>
                            <i className={`iconfont icon-sousuo ${styles.iconSearch}`}></i>
                            <input placeholder="输入名称" className={styles.searchText} onChange={e => this.searchValue(e)} />
                        </div>
                        {!inputValue ? <LevelList1 activeItem={activeItem} style={{ position: "relative", flex: "none" }} data={classificationListData} active={({ id },index) => this.searchDealWith({ typeId: id },index)} ></LevelList1> : ''}
                        {p_list.length ? <ul className={styles.ulList}>
                            {p_list.map((x, i) => {
                                return (<li key={i} onClick={e => this.getProductDetails(x, i)}>
                                    <div className={`${styles.ulListItem} ${productSubscript == i ? styles.hover : ''}`}>
                                        <div className={styles.img} style={{ backgroundImage: `url(${x.pic}?imageMogr2/quality/60/thumbnail/100x100)` }}></div>
                                        <h3>{x.name}</h3>
                                        <div className={"level-line"}></div>
                                        <div className={styles.itemText}>
                                            {x.brandName ? <span>品牌：{x.brandName || ''}</span> : ''}
                                            {x.price ? <span key={x.spec}>规格：{x.spec || ''}</span> : ''}
                                        </div>
                                        {x.umsCompanyInfo ? <div className={styles.itemText}>
                                            <span key={x.qualityGuaranteePeriod}>{x.qualityGuaranteePeriod?`保质期：${x.qualityGuaranteePeriod}`:'参考包装'}</span>
                                        </div> : ''}
                                    </div>
                                </li>)
                            })}
                        </ul> : <div className={styles.NoData}>没有数据</div>}
                    </Box>
                </div>
                <Box className={styles.Right} no={true}>
                    <EditTpl data={ProductDetailsData} upData={ProductDetailsData => this.setState({ ProductDetailsData })}></EditTpl>
                    <div className={styles.RightBox}>
                        <Box style={{ height: "58%", display: "flex" }}>
                            <div className={styles.productImges} style={{ backgroundImage: `url(${DetailsData.pic})` }}></div>
                            <div className={styles.productHref}>
                                {DetailsData.qrcode && <QRCode value={DetailsData.qrcode} style={{width:"10vw",height:"10vw"}} ></QRCode>}
                                
                                <div className={styles.retailPrice}>{DetailsData.retailPriceTitle}</div>
                                <div className={styles.NumTostring}><span style={{fontSize:"40px"}}>{DetailsData.priceIcon}{DetailsData.price || '暂无售价'}</span></div>
                                <div className={styles.retailPrice}>{(DetailsData.buyUrls || []).length?DetailsData.PurchaseLinkTitle:''}</div>
                                <div className={styles.BuyLink}>
                                    {(DetailsData.buyUrls || []).map((x, i) => {
                                        return (
                                            <a target={"_blank"} href={x.shopUrl} key={i}>
                                                <img src={x.shopImg} />
                                            </a>)
                                    })}
                                </div>
                            </div>
                        </Box>
                        <br />
                        <Title>{DetailsData.name}</Title>
                        <br />
                        <LevelList2 active={(...e)=>this.LevelList2Click(...e)} data={PovertyAlleviationArticle}></LevelList2>
                        <br />
                        <Box no={true} style={{ flex: 1 }}>
                            <Title>{DetailsData.IntroductionTitle}</Title>
                            <div className={styles.IntroductionInfo} dangerouslySetInnerHTML={{__html:DetailsData.description}}></div>
                        </Box>
                    </div>
                </Box>
            </div>
        )
    }
}
export {
    Industry
}
export default Industry