import React, { PureComponent } from "react";
import { Modal, Row, Col, Collapse, Input, Radio, notification, Button } from "antd";
import { connect } from "dva";
import { goodsVersion } from '@/utils/common';
import styles from "./index.less";
const RadioGroup = Radio.Group;
const Panel = Collapse.Panel;

class GoodsOptsModal extends PureComponent {
  constructor(props) {
    super(props);
    this.ifAgainAgg = false; // 是否重新聚合选配属性
    this.state = {
      loading: false
    };
  }
  componentWillReceiveProps(nextProps) {
    const { dispatch } = this.props;
    if ("goodsOptsParam" in nextProps) {
      const { goodsId, baseGoodsOptId } = nextProps.goodsOptsParam;
      if (nextProps.goodsOptsVisible && nextProps.goodsOptsVisible != this.props.goodsOptsVisible) {
        this.ifAgainAgg = true;
        // 先清空数据
        dispatch({
          type: "goodsOpts/goodsOpts",
          goodsOpts: []
        });
        dispatch({
          type: "goodsOpts/goodsOptsResult",
          goodsOptsResult: []
        });
        dispatch({
          type: "goodsOpts/getGoodsOpt",
          payload: {
            id: goodsId,
          }
        }).finally(() => {
          if (baseGoodsOptId) {
            dispatch({
              type: "goodsOpts/getGoodsOptsResult",
              payload: {
                ids: baseGoodsOptId,
              }
            }).finally(() => {
              const { goodsOpts, goodsOptsResult, dispatch } = this.props;
              if (goodsOptsResult) {
                const newGoodsOpts = [].concat(goodsOpts);
                newGoodsOpts.forEach(goodsOpt => {
                  const attrVals = goodsOpt.goodsAttrVals;
                  goodsOptsResult.forEach(optsResult => {
                    if (goodsOpt.id == optsResult.goodsId) {
                      const goodsOptVals = optsResult.goodsOptVals;
                      if (attrVals && goodsOptVals) {
                        attrVals.forEach(attr => {
                          goodsOptVals.forEach(optVal => {
                            if (optVal.attrValId == attr.attrValId) {
                              attr.isChecked = true;
                            }
                            if (attr.productAttrTypeCode == '04' && optVal.prodAttrStrucItemName == attr.name) {
                              attr.attrValId = optVal.attrValId;
                              attr.attrValName = optVal.attrValName;
                              attr.attrValCode = optVal.attrValCode;
                              attr.isChecked = true;
                            }
                          });
                        });
                      }
                    }
                  });
                });
                this.ifAgainAgg = true;
                dispatch({
                  type: "goodsOpts/goodsOpts",
                  goodsOpts: newGoodsOpts
                });
              }
            });
          }
        });
      }
    }
  }
  onChangeHandle(index, attrIndex, e) {
    e.preventDefault();
    console.log(index);
    const { goodsOpts } = this.props;
    goodsOpts[index].aggAttrs[attrIndex].isCheckedValue = e.target.value;
    goodsOpts[index].aggAttrs[attrIndex].isChecked = e.target.value ? true : false;
    let isAttrName = "";
    if (goodsOpts[index].aggAttrs[attrIndex].type == "04") {
      isAttrName = e.target.value;
      goodsOpts[index].aggAttrs[attrIndex].itemBomAttrVals[0] = {
        attrValId: e.target.value,
        attrValCode: e.target.value,
        attrValName: e.target.value,
        isChecked: e.target.value ? true : false
      };
    } else {
      goodsOpts[index].aggAttrs[attrIndex].itemBomAttrVals.forEach(bomAttr => {
        if (e.target.value && bomAttr.attrValId == e.target.value) {
          isAttrName = bomAttr.attrValName;
          bomAttr.isChecked = true;
        }
      });
    }
    goodsOpts[index].aggAttrs[attrIndex].isAttrName = isAttrName;
    this.props.dispatch({
      type: "goodsOpts/goodsOpts",
      goodsOpts: [].concat(goodsOpts)
    });
  }
  handleOkBtn() {
    const { dispatch, goodsOpts, goodsOptsParam } = this.props;
    this.setState({ loading: true });
    const goodsOptional = {
      goodsOptDtos: []
    };
    goodsOpts.forEach(goodsOpt => {
      const optional = {
        goodsId: goodsOpt.id,
        uniqueKey: goodsOpt.id,
        goodsOptVals: [],
        optResult: ''
      };
      let optResult = "";
      goodsOpt.aggAttrs.forEach(aggAttr => {
        if(!aggAttr.isOptionalAttr || '0' === aggAttr.isOptionalAttr) { return; };
        const goodsOptDto = {
          goodsOptId: aggAttr.id,
          prodAttrStrucItemName: aggAttr.name,
          prodAttrStrucItemId: aggAttr.prodAttrStrucItemId,
          attrValId: aggAttr.attrValId,
          attrValCode: aggAttr.attrValCode,
          attrValName: aggAttr.attrValName,
        };
        optResult += `${aggAttr.name}:`;
        aggAttr.itemBomAttrVals.forEach(bomAttr => {
          if (bomAttr.isChecked) {
            goodsOptDto.attrValName = bomAttr.attrValName;
            goodsOptDto.attrValCode = bomAttr.attrValCode;
            goodsOptDto.attrValId = bomAttr.attrValId;
            optResult += `${bomAttr.attrValName}`;
          }
        });
        optResult += ",";
        optional.goodsOptVals.push(goodsOptDto);
      });
      optional.optResult = optResult.slice(0, optResult.length - 1);
      goodsOptional.goodsOptDtos.push(optional);
    });
    const data = [];
    data.push(goodsOptional);
    dispatch({
      type: "goodsOpts/saveGoodsOpts",
      payload: data
    }).finally(() => {
      this.setState({ loading: false });
      const { optSaveReturnData } = this.props;
      if (optSaveReturnData && optSaveReturnData[0]) {
        this.props.onConfirm(optSaveReturnData[0].goodsOptDtos, goodsOptsParam.rowIndex);
      } else {
        notification.success({
          message: "商品选配",
          description: `选配失败: ${(optSaveReturnData || {}).message || ""}`,
          duration: 2
        });
      }
      this.hideModal();
    });
  }

  hideModal() {
    this.ifAgainAgg = false;
    this.props.dispatch({
      type: "global/goodsOptsVisible",
      payload: false
    });
  }
  // textOptHandle(index, e) {
  //   e.preventDefault();
  //   const { goodsOpts } = this.props;
  //   goodsOpts.goodsAttrVals[index].isChecked = true;
  // }
  render() {
    // 具体选配项
    const getGoodsOptsDetailHtml = (item, index) => {
      if (!item || !item.aggAttrs) return null;
      const detailHtml =  item.aggAttrs.map((aggAttr, attrIndex) => {
        if (aggAttr.isOptionalAttr !== 1) return null;
        if (aggAttr.type != '04') {
          return (
            <div>
              <p className={styles.radioAttr}>{aggAttr.name}:{aggAttr.isAttrName || ""}</p>
              <div className={styles.attrInfo}>
                <RadioGroup
                  value={aggAttr.isCheckedValue || ""}
                  onChange={this.onChangeHandle.bind(this, index, attrIndex)}
                >
                  {aggAttr.itemBomAttrVals.map(bomAttr => (
                    <Radio value={bomAttr.attrValId}>{bomAttr.attrValName}</Radio>
                  ))}
                </RadioGroup>
              </div>
            </div>
          );
        } else {
          return (
            <div className={styles.attrInfo}>
              <span className={styles.label}>{aggAttr.name}:</span>
              <Input onChange={this.onChangeHandle.bind(this, index, attrIndex)} style={{ width: "500px" }} placeholder="请输入" value={aggAttr.isCheckedValue || ""} />
            </div>
          );
        }
      });
      return detailHtml;
    };
    // 折叠板头部信息
    const collapseHeaderHtml = (item) => {
      return (
        <Row gutter={16}>
          <Col span={8}>
            <span className={styles.label}>商品编码：{item.code}</span>
          </Col>
          <Col span={8}>
            <span className={styles.label}>商品编码：{item.displayName}</span>
          </Col>
          <Col span={8}>
            <span className={styles.label}>商品版本：{goodsVersion(item.version, "text")}</span>
          </Col>
        </Row>
      );
    };
    // 商品选配
    const getGoodsOptHtml = () => {
      const { goodsOpts } = this.props;
      if (!goodsOpts || goodsOpts.length < 1) return null;
      if (this.ifAgainAgg) {
        // 先清空聚合信息
        goodsOpts.forEach(goodsOpt => goodsOpt.aggAttrs = []);
        // 对同一特征属性进行聚合
        goodsOpts.forEach(goodsOpt => {
          const goodsAttrVals = goodsOpt.goodsAttrVals;
          const aggAttrs = goodsOpt.aggAttrs || [];
          goodsAttrVals.forEach(goodsAttrVal => {
            if (!goodsAttrVal.isChecked) {
              goodsAttrVal.isChecked = goodsAttrVal.isOptionalAttr != 1 ? true : false;
            }
            let repeat = false;
            aggAttrs.forEach(aggAttr => {
              if (aggAttr.prodAttrStrucItemId === goodsAttrVal.prodAttrStrucItemId) {
                if (goodsAttrVal.isChecked) {
                  aggAttr.isCheckedValue = goodsAttrVal.attrValId || "";
                  aggAttr.isAttrName = goodsAttrVal.attrValName || "";
                }
                aggAttr.itemBomAttrVals.push({
                  attrValId: goodsAttrVal.attrValId,
                  attrValCode: goodsAttrVal.attrValCode,
                  attrValName: goodsAttrVal.attrValName,
                  isChecked: goodsAttrVal.isChecked
                });
                repeat = true;
              }
            });
            if (!repeat) {
              const newItemBomAttrVal = {
                id: goodsAttrVal.id,
                goodsId: goodsAttrVal.goodsId,
                prodAttrStrucItemId: goodsAttrVal.prodAttrStrucItemId,
                productAttrId: goodsAttrVal.productAttrId,
                type: goodsAttrVal.productAttrTypeCode,
                name: goodsAttrVal.name,
                isAttrName: goodsAttrVal.isChecked ? goodsAttrVal.attrValName : '',
                isCheckedValue: goodsAttrVal.isChecked ? goodsAttrVal.attrValId : '',
                isOptionalAttr: (goodsAttrVal.isOptionalAttr ? goodsAttrVal.isOptionalAttr : '0'), // 是否可选配
                itemBomAttrVals: [{
                  attrValId: goodsAttrVal.attrValId,
                  attrValCode: goodsAttrVal.attrValCode,
                  attrValName: goodsAttrVal.attrValName,
                  isChecked: goodsAttrVal.isChecked
                }]
              };
              aggAttrs.push(newItemBomAttrVal);
            }
          });
          goodsOpt.aggAttrs = aggAttrs;
        });
        this.ifAgainAgg = false;
      }
      if (goodsOpts.length > 1) {
        return (
          <Collapse defaultActiveKey={['1']}>
            {
              goodsOpts.map((item, index) => {
                if (item.isOptional != 1) return null;
                return (
                  <Panel header={collapseHeaderHtml(item)} key={`${index + 1}`}>
                    {getGoodsOptsDetailHtml(item, index)}
                  </Panel>
                );
             })
            }
          </Collapse>
        );
      } else {
        return (
          <div>
            {getGoodsOptsDetailHtml(goodsOpts[0], 0)}
          </div>
        );
      }
    };
    const { goodsOptsParam } = this.props;
    const { rowData } = goodsOptsParam;
    return (
      <div>
        <Modal
          title={this.props.title || "商品选配"}
          visible={this.props.goodsOptsVisible || false}
          onOk={this.handleOkBtn.bind(this)}
          onCancel={this.hideModal.bind(this)}
          width={1200}
          footer={this.props.ifFooterNul ? null : [
            <Button key="back" onClick={this.hideModal.bind(this)}>取消</Button>,
            <Button key="submit" type="primary" loading={this.state.loading} onClick={this.handleOkBtn.bind(this)}>
              确定
            </Button>
          ]}
          className={styles.modal}
        >
          <div className={styles.goodsInfoBox}>
            <p className={styles.title}>基本信息</p>
            <div className={styles.baseInfo}>
              <Row gutter={16}>
                {/* todo... */}
                <Col span={8}>
                  <span className={styles.label}>商品编码：{rowData.goodsCode}</span>
                </Col>
                <Col span={8}>
                  <span className={styles.label}>商品编码：{rowData.goodsDisplayName}</span>
                </Col>
                <Col span={8}>
                  <span className={styles.label}>商品版本：{goodsVersion(rowData.version, "text")}</span>
                </Col>
              </Row>
            </div>
          </div>
          <div className={styles.goodsInfoBox}>
            <p className={styles.title}>选配信息</p>
            <div>
              {getGoodsOptHtml()}
            </div>
          </div>
        </Modal>
      </div>
    );
  }
}
export default connect(state => ({
  ...state,
  goodsOptsVisible: state.global.goodsOptsVisible,
  goodsOpts: state.goodsOpts.goodsOpts,
  goodsOptsResult: state.goodsOpts.goodsOptsResult,
  optSaveReturnData: state.goodsOpts.optSaveReturnData
}))(GoodsOptsModal);
