import React, { Component } from "react";
import { connect } from "dva";
import { Button, Table, Modal, Icon, Select, Input, message } from "antd";
import "./less/report.less";
const Option = Select.Option;
import * as ajax from "../../../services/api";


export default class Shareholder extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      // comId: 1,
      shareloderList: [], //所有股东
      shareloderListMore: [
        {
          key: "0",
          shareholderId: "", //股东id
          cerNo: "", //证件号码
          contributionAmount: "", //出资额
          contributionMode: "", //出资方式
          contributionProp: "" //所占比例
        }
      ],
      count: 1,
      moneyPropList: [], //出资方
      val_null: "",
      val_input: "", //出资额
      val_select: "" //出资方式
    };
  }

  componentDidMount() {
    this.shareloderList();
    this.moneyPropList();
  }

  shareloderList = () => {
    ajax.comStockBasicHolderList({
      }).then(data => {
        console.log("123445", data.data);
        this.setState({
          shareloderList: data.data
        });
      });
  };

  moneyPropList = () => {
    ajax.publicCommonDictGetDictByCodeTypes({ codeTypes: "contributionMode" }).then(data => {
      if (data.data) {
        this.setState({
          moneyPropList: data.data.contributionMode
        });
      }
    });
  };

  handleChangeGu = (value, index) => {
    let { shareloderListMore, shareloderList } = this.state;
    //选择股东后设置证件号
    // shareloderListMore = shareloderListMore.map((val, i) => {
    //   if (index === i) {
    //     val.cerNo = value;
    //   }
    //   return val;
    // });
    for(let s=0;s<this.state.shareloderList.length;s++){
      if(value === shareloderList[s].shareholderId){
        shareloderListMore[index].cerNo = shareloderList[s].cerNo;
      }
    }
    //已选择股东id列表
    let selected = shareloderListMore.map(val1 => {
      return val1.cerNo;
    });
    //选择股东后就禁选股东
    shareloderList = shareloderList.map(val => {
      if (selected.indexOf(val.shareholderId) !== -1) {
        val.disabled = true;
      } else {
        val.disabled = false;
      }
      return val;
    });
    shareloderListMore[index]["shareholderId"] = value;
    this.setState({ shareloderListMore, shareloderList });
  };

  handleChangeChuZi = (value, index) => {
    let { shareloderListMore } = this.state;
    shareloderListMore[index]["contributionMode"] = value;
    this.setState({ shareloderListMore });
  };

  renderShareloder = () => {
    return this.state.shareloderList.map((val, key) => {
      return (
        <Option
          disabled={val.disabled}
          key={key}
          value={val.shareholderId + ""}
        >
          {val.name} ({val.cerNo})
        </Option>
      );
    });
  };

  renderMoneyProp = () => {
    return this.state.moneyPropList.map((val, key) => {
      return (
        <Option key={key} value={val.codeValue + ""}>
          {val.label}
        </Option>
      );
    });
  };

  //出资额失去焦点事件
  inputOnBlur = wer => {
    console.log("wer", wer);
    let wed = this.state.val_input;
    const { shareloderListMore } = this.state;
    let sdf = true;
    shareloderListMore[wer].contributionAmount = wed;
    this.setState({
      shareloderListMore: [...shareloderListMore],
      val_input: ""
    });
    for (let i = 0; i < shareloderListMore.length; i++) {
      if (shareloderListMore[i].cerNo === "") {
        sdf = false;
        message.error("请先选择股东！");
      }
    }
    let sumNumber = 0;
    if (sdf) {
      for (let j = 0; j < shareloderListMore.length; j++) {
        sumNumber += parseInt(shareloderListMore[j].contributionAmount);
        // alert(sumNumber);
      }
      for (let s = 0; s < shareloderListMore.length; s++) {
        shareloderListMore[s].contributionProp = (
          shareloderListMore[s].contributionAmount /
          sumNumber *
          100
        ).toFixed(2);
      }
      this.setState({
        shareloderListMore: [...shareloderListMore]
      });
    }
  };

  onChangeAmount = (e, index) => {
    console.log("e", e.target.value);
    let { shareloderListMore } = this.state;
    let sumNumber = 0;
    for (let j = 0; j < shareloderListMore.length; j++) {
      if (index === j) {
        sumNumber += parseInt(e.target.value);
      } else {
        sumNumber += parseInt(shareloderListMore[j].contributionAmount);
      }
    }
    shareloderListMore = shareloderListMore.map((val, i) => {
      if (index === i) {
        val.contributionAmount = e.target.value;
      }
      console.log(val.contributionAmount, sumNumber);
      val.contributionProp = (val.contributionAmount / sumNumber * 100).toFixed(
        2
      );
      return val;
    });
    this.setState({ shareloderListMore });
  };

  // handleSelect = (ert) =>{
  //   alert(ert);
  // };

  //表格渲染
  renderList = () => {
    const columns = [
      {
        title: "股东",
        dataIndex: "name",
        render: (text, record, index) => (
          <Select
            style={{ width: 300 }}
            placeholder="请选择"
            onChange={val => {
              this.handleChangeGu(val, index);
            }}
          >
            {this.renderShareloder()}
          </Select>
        )
      },
      {
        title: "证件号",
        dataIndex: "cerNo",
        render: (text, record) => <Input value={record.cerNo} disabled />
      },
      {
        title: "出资额(元)",
        dataIndex: "contributionAmount",
        render: (text, record, index) => (
          <Input
            defaultValue={record.contributionAmount}
            onChange={e => {
              this.onChangeAmount(e, index);
            }}
          />
        )
      },
      // {
      //   title: "出资方式",
      //   dataIndex: "contributionMode",
      //   render: (text, record, index) => (
      //     <Select
      //       placeholder="请选择"
      //       style={{ width: 120 }}
      //       onChange={val => {
      //         this.handleChangeChuZi(val, index);
      //       }}
      //     >
      //       {this.renderMoneyProp()}
      //     </Select>
      //   )
      // },
      {
        title: "所占比例",
        dataIndex: "contributionProp",
        render: (text, record) => (
          <Input value={record.contributionProp} addonAfter="%" disabled />
        )
      },
      {
        title: "操作",
        render: (text, record, index) => (
          <div>
            <span
              style={{ color: "#108EE9", cursor: "pointer" }}
              onClick={() => {
                this.onDelete(index);
              }}
            >
              删除
            </span>
          </div>
        )
      }
    ];

    // const tmp = this.state.shareloderListMore.map((val, i) => {
    //   const param = val;
    //   return param;
    // });

    return (
      <Table
        style={{ marginTop: "16px" }}
        dataSource={this.state.shareloderListMore}
        columns={columns}
        pagination={false}
      />
    );
  };

  handleAdd = () => {
    let { count, shareloderListMore } = this.state;
    // console.log(shareloderListMore);
    let isValidSubmit = true;
    shareloderListMore.forEach(val => {
      // console.log(val);
      if(val.cerNo === "" || val.cerNo === null){
        message.warning("请选择股东确定身份！");
        isValidSubmit = false; return false;
      }
      if(!(/^[1-9]\d{1,18}$|^[1-9]\d{1,18}\.{1}\d{1,2}$/g).test(val.contributionAmount)){
        message.warning("请输入正确的出资额，数字最大18位整数，2位小数");
        isValidSubmit = false; return false;
      }
      // if(val.contributionMode === "" || val.contributionMode === null){
      //   message.warning("请输入正确的出资方式");
      //   isValidSubmit = false; return false;
      // }
      // console.log(isValidSubmit);
    });

    if (isValidSubmit) {
      const newData = {
        key: Math.random(),
        cerNo: "",
        shareholderId:'',
        contributionAmount: "",
        contributionMode: "",
        contributionProp: ""
      };
      shareloderListMore = [...shareloderListMore, newData];
      this.setState({
        shareloderListMore,
        count: count + 1
      });
    }
  };

  returnnewList = (shareloderListMore, key) => {
    shareloderListMore.splice(key, 1);
    return shareloderListMore;
  };

  onDelete = key => {
    let { shareloderList } = this.state;
    let shareloderListMore = this.state.shareloderListMore.slice();
    //已选择股东id列表
    let selected = shareloderListMore.map(val1 => {
      return val1.cerNo;
    });
    //选择股东后就禁选股东
    shareloderList = shareloderList.map(val => {
      if (selected.indexOf(val.shareholderId) !== -1) {
        val.disabled = true;
      } else {
        val.disabled = false;
      }

      if (val.shareholderId === shareloderListMore[key].cerNo) {
        val.disabled = false;
      }
      return val;
    });

    shareloderListMore = this.returnnewList(shareloderListMore, key);
    let sumNumber = 0;
    for (let j = 0; j < shareloderListMore.length; j++) {
      sumNumber += parseInt(shareloderListMore[j].contributionAmount);
    }
    shareloderListMore = shareloderListMore.map((val, i) => {
      val.contributionProp = (val.contributionAmount / sumNumber * 100).toFixed(
        2
      );
      return val;
    });

    this.setState(
      {
        shareloderList
      },
      () => {
        this.setState({
          shareloderListMore
        });
      }
    );
  };

  handleSubmit = () =>{
    console.log('123456',this.state.shareloderListMore);
    //校验表单的每一行数据，如果不符合正则那么就提示错误
    let isValidSubmit = true;
    if(this.state.shareloderListMore.length === 0){
      message.warning("请选择股东信息");
      return;
    }
    this.state.shareloderListMore.forEach(val =>{
        // console.log(val);
        if(val.cerNo === "" || val.cerNo === null){
          message.warning("请选择股东确定身份！");
          isValidSubmit = false; return false;
        }
        if(!(/^[1-9]\d{1,18}$|^[1-9]\d{1,18}\.{1}\d{1,2}$/g).test(val.contributionAmount)){
          message.warning("请输入正确的出资额，数字最大9位整数，2位小数");
          isValidSubmit = false; return false;
        }
        // if(val.contributionMode === "" || val.contributionMode === null){
        //   message.warning("请输入正确的出资方式");
        //   isValidSubmit = false; return false;
        // }
        // console.log(isValidSubmit);
    });
    // console.log(">>>>>>>>>>>>>>>>>>",isValidSubmit);
    if(isValidSubmit){
      ajax.comStockInitShare({shareDetail: JSON.stringify(this.state.shareloderListMore)}).then(() => {
        // message.success('提交成功！');
        this.props.sublime();
      });
    }
  };

  render() {
    return (
      <div className="initializa">
        <h2>
          <span>股权初始化</span>
          <Icon
            type="exclamation-circle"
            style={{ fontSize: 14, color: "#d9d9d9" }}
          />
          <em>填写信息以工商局登记信息为准</em>
        </h2>
        {this.renderList()}
        <div className="renderAdd">
          <p onClick={this.handleAdd}>
            <Icon
              type="plus"
              style={{ fontSize: 14, color: "rgba(0,0,0,.43)" }}
            />
            <span>新增</span>
          </p>
        </div>
        <div className="initia_footer">
          <Button onClick={()=>{
            // this.props.history.push(`/enterprise/reported`);
            // this.props.history.push(`/enterprise/reported/shareholder`);
            this.props.close();
          }}
          >返回</Button>
          <Button type="primary" style={{ marginLeft: "8px" }} onClick={this.handleSubmit}>
            提交
          </Button>
        </div>
      </div>
    );
  }
}
