import React, { PureComponent } from "react";
import { connect } from "dva";
import { Icon, Checkbox, Select, Input, Button, message, Breadcrumb, Tag, Modal } from "antd";
import styles from "./index.less";
import AmountFun from "@/components/AmountFun/index.js";
import { SpecificationMethod, _isContained, _isArrEqual, amountPrecision } from '@/utils/utils';
import { getCustomer } from "@/utils/request";
import { getGoodAndPalettePriceConAPI,saveGoodsOptsResultAPI } from "../../../../services/api";

import erroImg  from "@/assets/imgError.png";

const breadcrumbList = [
    {
        title: "首页",
        path: ''
    },
    {
        title: "维格生活馆",
        path: ''
    },
    {
        title: "沙发",
        path: ''
    }
];
class GoodsDetails extends PureComponent {
    constructor(props) {
        super(props);
        this.supplierName = "";
        this.stock = 0;
        this.state = {
            imgSrc: '',
            isHover: 0,
            buyNum: 1,
            isFollow: false,
            isNavLi: 0,
            SpecificationFlag: 0,
            mockdata: [],
            isCheckVal: [],
            isCheckName: [],
            optValShow: false,
            optSearchVal: "",
            optValSelectId: "",
            optVal: {
                baseGoodsOptValue: "",
                baseGoodsOptId: "",
                ext05: "",
                ext04: "",
                price: ""
            },
            originPrice: 0
        };
    }
    componentWillMount() {
      const { dispatch } = this.props;
      // 先清空数据
      dispatch({
        type: "commodityDetails/goodsDetail",
        goodsDetail: null
      });
      dispatch({
        type: "commodityDetails/goodsDetailProductAttr",
        goodsDetail: null
      });
      dispatch({
        type: "commodityDetails/goodsDetailImage",
        goodsDetail: null
      });
    }
    componentDidMount() {
        this.queryGoodDetails();
    }
    componentDidUpdate() {
        const { goodsDetail, dispatch, goodsDetailProductAttr } = this.props;
        // 商品规格集合
        if (goodsDetailProductAttr && goodsDetail) {
            const freeArr = goodsDetailProductAttr.polyAttrsDtoList;
            // 商品全集
            if (this.state.SpecificationFlag == 1) return;
            this.state.isFollow = goodsDetail.inFav;
            this.initPuc(goodsDetailProductAttr, goodsDetail.goodsAttrVals, 'init');
            SpecificationMethod(freeArr, goodsDetailProductAttr, e => this.defaultMethod(e));
            this.state.SpecificationFlag = 1;
        }
        if (goodsDetail && goodsDetail.description) {
            const description = this.escapeChars(goodsDetail.description);
            document.getElementById("goodsDescription").innerHTML = description;
        }
    }
     // 特殊字符处理
    escapeChars(str) {
        // 转义字符
        str = str.replace(/&lt;/g, "<");
        str = str.replace(/&gt;/g, ">");
        str = str.replace(/&quot;/g, '"');
        // 十进制
        str = str.replace(/&#34;/g, '"');
        str = str.replace(/&#39;/g, "'");
        str = str.replace(/&#60;/g, "<");
        str = str.replace(/&#62;/g, ">");
        return str;
    }
    queryGoodDetails(prodataFirst) {
        const { dispatch, location } = this.props;
        let code, id, supplier, product;
        if (location[`query`]) {
            code = location.query.code;
            id = location.query.id;
            supplier = location.query.saleOrgId;
            this.supplierName = location.query.saleOrgName;
            product = location.query.productId;
            this.stock = location.query.stock;
        } else {
            code = localStorage.getItem("goodsSku");
            id = localStorage.getItem("goodsDetailsId");
            supplier = localStorage.getItem("goodsDetailSsaleOrgId");  // 供应商
            product = localStorage.getItem("goodsDetailProductId");  // 供应商
            this.supplierName = localStorage.getItem("goodsDetailSsaleOrgName");
            this.stock = localStorage.getItem("goodsDetailStock");
        }
        // 获取商品详情详细信息
        dispatch({
            type: "commodityDetails/getGoodsDetailNew",
            payload: {
                id: prodataFirst ? prodataFirst : id,
                supplier: supplier
            }
        }).finally((res) => {
            const { goodsDetail } = this.props;
            this.setState({originPrice:goodsDetail.basePrice})
            // 获取商品详情规格
            dispatch({
                type: "commodityDetails/getGoodsDetailProductAttr",
                payload: {
                    id: id,
                    product: goodsDetail.productId
                }
            });
            // // 添加到最近浏览
            // dispatch({
            //     type: 'public/addGoodsBrowse',
            //     payload: {
            //         goodsId: id
            //     }
            // });
        });
        // 获取商品详情 图片
        dispatch({
            type: "commodityDetails/getGoodsDetailImage",
            payload: {
                id: id
            }
        });
    }
    // 面包屑
    BreadcrumbItem(datas = breadcrumbList) {
        return (
            <Breadcrumb title="" className={styles.detailsNavBox} key="BreadcrumbItem" separator={<Icon type="right" />}>
                {datas.map(data => {
                    return (
                        <Breadcrumb.Item  key={data.hash}>
                            <a href={data.path}> {data.title} </a>
                        </Breadcrumb.Item >
                    );
                })}
            </Breadcrumb>
        );
    }
    // 图片切换
    hoverHandle(imgSrc, index) {
        this.setState({
            imgSrc: imgSrc.fileUrl,
            isHover: index
        });
    }
    // 清空颜色
    clearColor() {
        this.setState({
            optVal: {}
        });
        const price = this.state.originPrice
        const { goodsDetail, dispatch } = this.props;
        const goodsDetailNew = Object.assign({}, goodsDetail, {
            baseGoodsOptId: "",
            baseGoodsOptValue: "",
            ext04: "",
            ext05:"",
            // isOptional: "",
            baseDiscountPrice: price, basePrice: price, insideAllotPrice: price,insideCostPrice: price,nationalUniformPrice: price})
        dispatch({type: "commodityDetails/updateGoodsDetail", payload: goodsDetailNew})
    }

    // 显示颜色选择窗口
    openColorDlg() {
        this.setState({
            optValShow: true
        });
    }

    // selectColor(optValSelectId) {
    //     console.log(optValSelectId.target.textContent)
    //     this.setState({
    //         optValSelectId: optValSelectId.target.textContent
    //     });
    // }

    selectColor(optValSelectId) {
        this.setState({
            optValSelectId
        });
    }

    // 获取购买数量
    buyNumChange(num) {
        this.setState({
            buyNum: num
        });
    }
    // 购物车
    addCartHandle(e) {
        const { dispatch, goodsDetail, goodsDetailProductAttr } = this.props;
        e.preventDefault();
        const orderNum = this.state.buyNum;
        if (!orderNum || orderNum < 1) {
            message.warning("请添加商品");
            return;
        }
        this._submitOrder();
        // const postData = {
        //     buyNum: buyNum,
        // };
        // dispatch({
        //     type: "cartList/addCart",
        //     payload: postData
        // });
    }

    async confirmColor(color) {
        console.log(color)
        const { goodsDetail, dispatch } = this.props;
        const params = {
            organizationId: goodsDetail.saleOrgId,
            customerId: getCustomer().id,
            goodsId: goodsDetail.id,
            orderTypeId: '01',
            paletteId: color.attrValId,
            shopId: ''
        }
        const result = await getGoodAndPalettePriceConAPI(params)
        if (result.length) {
            const optParams = [{
                goodsOptDtos: [{
                    goodsId: goodsDetail.id,
                    goodsOptVals: [color],
                    optResult: color.custDocGroupName+ ":" + color.attrValName,
                    uniqueKey: goodsDetail.id
                }]
            }]
            const opt = await saveGoodsOptsResultAPI(optParams);
            const price = result[0].price
            const goodsDetailNew = Object.assign({}, goodsDetail, {
                baseGoodsOptId: opt[0].goodsOptDtos[0].id,
                baseGoodsOptValue: color.custDocGroupName+ ":" + color.attrValName,
                ext04: "1",
                ext05: color.attrValCode,
                // isOptional: "1",
                baseDiscountPrice: price, 
                basePrice: price, 
                insideAllotPrice: price,
                insideCostPrice: price,
                nationalUniformPrice: price})
            dispatch({type: "commodityDetails/updateGoodsDetail", payload: goodsDetailNew})
        }
    }

    // 关注
    followBtn(e) {
        const { goodsDetail, dispatch } = this.props;
        e.preventDefault();
        const postData = !this.state.isFollow ? {
            customerId: getCustomer().id,
            goodsId: goodsDetail.id,
            goodsImg: goodsDetail.mainPictureFileUrl,
            isPrimaryChannel: 1,
            saleOrgId: goodsDetail.saleOrgId,
            supplierId: null
        } : {
            customer: getCustomer().id,
            id: goodsDetail.id
        };
        const url = this.state.isFollow ? "public/getDelStore" : "public/getAddStore";
        dispatch({
            type: url,
            payload: postData
        }).finally(() => {
            const { goodsDetail } = this.props;
            const message = this.state.isFollow ? "已取消关注" : "已关注";
            message.warning(message);
            this.setState({
                isFollow: !this.state.isFollow
            });
        });
    }
    // 切换详情teb
    clickActive(data) {
        this.setState({
            isNavLi: data
        });
    }
    // 初始化规格布局
    initPuc(data, goodsDetail, init) {
        const goods = [];
        for (let k = 0; k < goodsDetail.length; k++) {
            if (init == 'init') {
                goods.push(goodsDetail[k].attrValId);
            } else {
                goods.push(goodsDetail[k].id);
            }
        }
        const freeArr = data.polyAttrsDtoList;
        for (let i = 0; i < freeArr.length; i++) {
            for (let j = 0; j < freeArr[i].values.length; j++) {
                if (goods.indexOf(freeArr[i].values[j].id) != -1) {
                    freeArr[i].values[j].isChecked = true;
                } else {
                    freeArr[i].values.isChecked = false;
                }
            }
        }
        // 商品规格集合
        // 商品全集
        SpecificationMethod(freeArr, data, e => this.defaultMethod(e));
    }
    // 回调
    defaultMethod(e) {
        this.setState({
            mockdata: e.freeArr,
            data: e.data,
            isCheckVal: e.checktrue,
            isCheckName: e.checkname
        }, () => {
          this._productSelect(e.data);
        });
    }
    // 对选择的属性找对应商品（第四步）
    _productSelect(data, verify) {
        const isCheckVal = this.state.isCheckVal;
        if (!isCheckVal || !Array.isArray(isCheckVal) || isCheckVal.length < 1) return true;
        const prodata = data.goodsInfos;
        for (const prodataFirst of Object.keys(prodata)) {
        if (
            _isContained(prodata[prodataFirst], isCheckVal) &&
            _isArrEqual(prodata[prodataFirst], isCheckVal)
        ) {
            if (!verify) {
                // 生成对应的Id 根据id再去获取新的商品详情
                this.queryGoodDetails(prodataFirst);
            } else {
                return true;
            }
        }
        }
    }
    _submitOrder() {
        if (this._productSelect(this.state.data, true)) {
          this.addToShopcartfen();
        } else {
            message.warning("所选属性没有对应商品！");
        }
      }
    // 添加购物车 请求
    addToShopcartfen() {
        const { dispatch, goodsDetail } = this.props;
        const mainNum = parseFloat(this.state.buyNum || 1) * parseFloat(goodsDetail.conversionRate || 1);
        dispatch({
        type: "cartList/addCart",
        payload: {
            orderNum: this.state.buyNum || 1,
            mainNum: mainNum,
            goodsId: goodsDetail.id,
            goodsDisplayName: goodsDetail.displayName,
            goodsName: goodsDetail.name,
            goodsCode: goodsDetail.code,
            goodsImg: goodsDetail.mainPictureFileUrl,
            orderNumUnitId: goodsDetail.assistUnitId,
            orderNumUnitCode: goodsDetail.assistUnitCode,
            orderNumUnitName: goodsDetail.assistUnitName,
            orderNumUnitScale: goodsDetail.orderNumUnitScale || 0,
            mainNumUnitId: goodsDetail.basicUnitId,
            mainNumUnitCode: goodsDetail.basicUnitCode,
            mainNumUnitName: goodsDetail.basicUnitName,
            mainNumUnitScale: goodsDetail.basicUnitPrecision || 0,
            weight: goodsDetail.grossWeight, // 默认取毛重
            ...goodsDetail
        }
        }).finally(() => {
            message.warning('已加入购物车');
        });
    }
    // 点击标签 事件
    _proCategoryred(val, index, bool) {
        if (bool) {
          for (let i = 0; i < this.state.mockdata.length; i++) {
            for (let j = 0; j < this.state.mockdata[i].values.length; j++) {
              delete this.state.mockdata[i].values[j].isChecked;
              delete this.state.mockdata[i].values[j].isDisabled;
              delete this.state.mockdata[i].values[j].isDisableTrue;
            }
          }
        }
        for (let i = 0; i < val.length; i++) {
          val[i].isChecked = false;
        }
        val[index].isChecked = true;
        this.setState({ mockdata: this.state.mockdata });
        SpecificationMethod(this.state.mockdata, this.state.data, e =>
          this.defaultMethod(e)
        );
        // this._proCateSelected(this.state.mockdata, this.state.data, val[index]);
    }
    // 图片加载失败
    imgErro(e) {
      e.target.src = erroImg;
    }
    render() {
        const {
            goodsDetail,
            goodsDetailImage,
            // goodsDetailProductAttr
        } = this.props;
        const isCheckName = this.state.isCheckName;
        // 小图选中
        const styleObj = {
            borderColor: "#E14C46"
        };
        const activeStyle = {
            borderColor: "#E14C46",
            outline: "1px solid #E14C46"
        };
        const E14C46 = {
            color: '#E14C46'
        };
        const styleDetailsNavBoxLiActive = {
            borderBottom: '3px solid #E14C46',
            color: '#E14C46'
        };
        const boxShow = {
            display: 'block'
        };
        // 小图片
        const SmallImgs = () => {
            let { goodsDetailImage } = this.props;
            goodsDetailImage = goodsDetailImage && goodsDetailImage.length > 0 ? goodsDetailImage : [{
                key: 'erro',
                fileUrl: erroImg
            }];
            const temp = goodsDetailImage.map((item, index) => (
                <li className={styles.commodityDetailImgList}  key={item.key}  style={this.state.isHover == index ? styleObj : null}  onMouseOver={this.hoverHandle.bind(this, item, index)} onFocus={this.hoverHandle.bind(this, item, index)} >
                    <img src={item.fileUrl ? item.fileUrl : erroImg} alt="" className={styles.img} onError={this.imgErro.bind(this)} />
                </li>
            ));
            return temp;
        };
        // 规格
        const specsHtml = () => {
            const temp = this.state.mockdata.map((item, key) => (
                <li className={styles.titleTextList} key={item.id}>
                    <span className={styles.title}>{item.name}</span>
                    <em className={styles.symbolEm}>：</em>
                    <div className={styles.texturBox}>
                        {item.values.map((itemChild, index) => {
                            let activeClass = '';
                            if (itemChild.isChecked === true) {
                                activeClass = styles.isChecked;
                            }
                            if (itemChild.isDisabled === true) {        // 不可选项，点击后请其他已选
                                activeClass = styles.isDisabled;
                            }
                            if (itemChild.isDisableTrue === true) {     // 不可点击
                                activeClass = styles.isDisableTrue;
                            }
                            return (
                                <span className={`${styles.textur} ${activeClass}`} key={itemChild.id} onClick={itemChild.isDisableTrue === true ? '' : this._proCategoryred.bind(this, item.values, index, itemChild.isDisabled)}>
                                { itemChild.name }
                                </span>
                            );
                        })}
                    </div>
                </li>
            ));
            return temp;
        };

        return (
            <div className={styles.commodityDetailsPage}>
                {/* {this.BreadcrumbItem()} */}
                <div className={styles.clearfix}>
                    <div className={styles.commodityDetailsBox}>
                        <div className={styles.commodityDetailsBoxLeft}>
                            <div className={styles.commodityDetailImgsBox}>
                                <ul className={styles.commodityDetailImgUl}> { SmallImgs() } </ul>
                                <div className={styles.commodityDetailImgBig}>
                                    <img src={this.state.imgSrc ? this.state.imgSrc : goodsDetailImage && goodsDetailImage.length > 0 ? goodsDetailImage[0].fileUrl : erroImg} alt="" className={styles.img} style={{ width: 540, height: 540 }} onError={this.imgErro.bind(this)} />
                                </div>
                            </div>
                            <div className={styles.attentionBox}>
                                <div className={styles.attentionBtn} onClick={this.followBtn.bind(this)}>
                                    <Icon type="heart" className={styles.heartIcon}  style={this.state.isFollow ? E14C46 : null} />
                                    关注
                                </div>
                            </div>
                        </div>

                        <div className={styles.commodityDetailsBoxRight}>
                            <ul className={styles.commodityDetailsMessageUl}>
                                <li className={styles.commodityNameList}>
                                    <p className={styles.commodityNameBox}>
                                        { goodsDetail ? goodsDetail.displayName : "" }
                                    </p>
                                    <p className={styles.commodityCodeBox}>
                                        <span>商品编码：</span>
                                        <span>{ goodsDetail ? goodsDetail.code : "" }</span>
                                    </p>
                                </li>
                                <li className={styles.priceList}>
                                    <span className={styles.priceList_left} >折 扣 价: </span><span className={styles.money}>{ goodsDetail ? amountPrecision(goodsDetail.baseDiscountPrice) : "0.00" } </span>
                                    <del>原价:  { goodsDetail ? amountPrecision(goodsDetail.basePrice) : "0.00" } </del>
                                    <p style={goodsDetail && goodsDetail.promQueryResultList ? {} : { display: 'none' }}>
                                        <span className={styles.priceList_left} >促 销 : </span>
                                        <span>{goodsDetail ? goodsDetail.promQueryResultList : ''}</span>
                                    </p>
                                </li>
                                {/* { specsHtml() } */}
                                <li className={styles.titleTextList} >
                                    <span className={styles.title} >重量</span>
                                    <em className={styles.symbolEm} >：</em>
                                    <div className={styles.weightBox} >
                                        <span className={styles.contBs} > { goodsDetail ? goodsDetail.grossWeight : ""  } </span>
                                        <span className={styles.unitBs} >
                                            { goodsDetail ? goodsDetail.weightUnitName : "" }
                                        </span>
                                    </div>
                                    <span className={styles.title} >型号</span>
                                    <em className={styles.symbolEm} >：</em>
                                    <div className={styles.volumeBox}>
                                        <span className={styles.contBs} > { goodsDetail ? goodsDetail.model : "" } </span>
                                        <span className={styles.unitBs} >
                                            { goodsDetail ? goodsDetail.volumeUnitName : "" }
                                        </span>
                                    </div>
                                </li>
                                <li className={styles.titleTextList} >
                                    <span className={styles.title} >系列</span>
                                    <em className={styles.symbolEm} >：</em>
                                    <div className={styles.amountBox} >
                                        <Tag onClick={this.clearColor.bind(this)} color={this.state.optVal.baseGoodsOptId ? "" : "red"}>无</Tag>
                                        <Tag onClick={this.openColorDlg.bind(this)}>选颜色</Tag>
                                    </div>
                                </li>
                                <li className={styles.titleTextList} >
                                    <span className={styles.title} >颜色</span>
                                    <em className={styles.symbolEm} >：</em>
                                    <div className={styles.amountBox} >
                                        {this.state.optVal.baseGoodsOptValue}
                                    </div>
                                </li>                                                             
                                <li className={styles.titleTextList} >
                                    <span className={styles.title} >数量</span>
                                    <em className={styles.symbolEm} >：</em>
                                    <div className={styles.amountBox} >
                                        <AmountFun num={this.state.buyNum} onChange={this.buyNumChange.bind(this)} />
                                    </div>
                                </li>
                                <li className={styles.titleTextList} >
                                    <span className={styles.title} >规格</span>
                                    <em className={styles.symbolEm} >：</em>
                                    <div className={styles.textBox} >
                                        <span className={styles.contBs} >
                                            {/* {(goodsDetail.specification)}/{goodsDetail.basicUnitName} */}
                                            {goodsDetail ? (goodsDetail.specification) +"/"+(goodsDetail.basicUnitName) : ""}
                                        </span>
                                    </div>
                                </li>
                                <li className={styles.titleTextList} >
                                    <span className={styles.title} >订货金额</span>
                                    <em className={styles.symbolEm} >：</em>
                                    <div className={styles.textBox} >
                                        <span className={styles.priceBs} >{ goodsDetail ? amountPrecision(goodsDetail.baseDiscountPrice * this.state.buyNum) : 0.00}</span>
                                    </div>
                                </li>
                                <li className={styles.titleTextList} >
                                    <Button className={styles.shoppingCatBtn} onClick={this.addCartHandle.bind(this)} >
                                        加入购物车
                                    </Button>
                                </li>
                            </ul>
                        </div>
                    </div>
                </div>
                <div className={styles.clearfix}>
                <div className={styles.detailsNavItems} id="detailsNavBoxId">
                    <ul>
                        <li onClick={this.clickActive.bind(this, 0)} style={this.state.isNavLi == 0 ? styleDetailsNavBoxLiActive : null} >
                            <span className={styles.navBtn}>商品描述</span>
                        </li>
                        {/* <li onClick={this.clickActive.bind(this, 1)} style={this.state.isNavLi == 1 ? styleDetailsNavBoxLiActive : null} >
                            <span className={styles.navBtn}>子件清单</span>
                        </li> */}
                    </ul>
                </div>
                <div className={styles.detailsContentBox}>
                    <div id="goodsDescription" className={styles.contentBox} onClick={this.clickActive.bind(this, 0)} style={this.state.isNavLi == 0 ? boxShow : null} >
                    </div>
                    <div className={styles.contentBox} onClick={this.clickActive.bind(this, 1)} style={this.state.isNavLi == 1 ? boxShow : null} >
                        子件清单
                    </div>
                </div>
                </div>

                <Modal title="颜色选择" visible={this.state.optValShow}
                    onCancel={() => {
                        this.setState({optValShow: false})
                    }}
                    onOk={async () => {
                        if (this.state.optValSelectId) {
                            const colorSelc = goodsDetail ? goodsDetail.goodsAttrVals.find(item => item.attrValId == this.state.optValSelectId) : null
                            const optVal = Object.assign({},this.state.optVal,colorSelc,{baseGoodsOptValue: `${colorSelc.custDocGroupName}->${colorSelc.attrValName}`})
                            this.setState({
                                optVal ,
                                optValShow: false
                            })
                            this.confirmColor(optVal)
                        } else {
                            message.warning("请选择颜色")
                        }
                    }}
                    width="1000px" maskClosable={false}
                >
                    <div>
                        <Input.Search placeholder="请输入颜色编码" 
                            // defaultValue={this.state.optSearchVal}
                            onBlur={(e) => {
                                this.setState({optSearchVal: e.target.value})
                            }}
                            onSearch={(e) => {
                                this.setState({optSearchVal: e})
                            }}
                            onPressEnter={(e) => {
                                this.setState({optSearchVal: e.target.value})
                            }}
                        />
                    </div>
                    <div style={{height: "500px",width: "950px",overflow: "auto", marginTop: "10px"}}>
                        {
                            goodsDetail ? goodsDetail.goodsAttrVals.filter(item => !this.state.optSearchVal || item.attrValName.indexOf(this.state.optSearchVal) >= 0).map((item,index) => {
                                // return <Tag  color={this.state.optValSelectId == item.attrValName ? "red" : ""} className={styles.colorItem} onClick={this.selectColor.bind(this)}>{item.attrValName}</Tag>
                                return <Tag key={item.attrValId} color={this.state.optValSelectId == item.attrValId ? "red" : ""} className={styles.colorItem} onClick={() => {this.selectColor(item.attrValId)}}>{item.attrValName}</Tag>
                            }) : ""
                        }
                    </div>
                </Modal>

            </div>
        );
    }
}

// export default goodsDetail;

export default connect(state => ({
    goodsDetail: state.commodityDetails.goodsDetailNew,
    goodsDetailProductAttr: state.commodityDetails.goodsDetailProductAttr,
    goodsDetailImage: state.commodityDetails.goodsDetailImage,
}))(GoodsDetails);

