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

const FormItem = Form.Item;
@connect(state => ({
  profile: state.profile,
}))

@Form.create()

export default class ChangeOwnership extends Component {
  constructor(props,context){
    super(props,context);
    this.state = {
      confirmLoading:false,
      visible:false,
      // comId: 1,
      shareloderList: [],//受让股东
      shareloderWed:[],//增资，减资，转让股东
      dataList:[],//弹窗展示数据
      comInsGuaProject: [{
        seq:1
      }],
      val_text1:1,
      proLength:1,//有多少个保障项目

      changeDetails: {
        shareDetail:[]
      },

    }
  }

  handleChangeValue = (value,ert) =>{
    let sd = ert.props.lmb;
    this.setState({
      [`val_text${ert.props.lmb}`]: parseInt(value),
    });
  };

  Arabia_To_SimplifiedChinese = (Num) => {
    if (isNaN(Num)) { //验证输入的字符是否为数字
      //alert("请检查小写金额是否正确");
      return;
    }
    //字符处理完毕后开始转换，采用前后两部分分别转换
    let part = String(Num).split(".");
    let newchar = "";
    //小数点前进行转化
    for (let i = part[0].length - 1; i >= 0; i--) {
      if (part[0].length > 10) {
        //alert("位数过大，无法计算");
        return "";
      }//若数量超过拾亿单位，提示
      let tmpnewchar = ""
      let perchar = part[0].charAt(i);
      switch (perchar) {
        case "0":  tmpnewchar = "零" + tmpnewchar;break;
        case "1": tmpnewchar = "一" + tmpnewchar; break;
        case "2": tmpnewchar = "二" + tmpnewchar; break;
        case "3": tmpnewchar = "三" + tmpnewchar; break;
        case "4": tmpnewchar = "四" + tmpnewchar; break;
        case "5": tmpnewchar = "五" + tmpnewchar; break;
        case "6": tmpnewchar = "六" + tmpnewchar; break;
        case "7": tmpnewchar = "七" + tmpnewchar; break;
        case "8": tmpnewchar = "八" + tmpnewchar; break;
        case "9": tmpnewchar = "九" + tmpnewchar; break;
      }
      switch (part[0].length - i - 1) {
        case 0: tmpnewchar = tmpnewchar; break;
        case 1: if (perchar != 0) tmpnewchar = tmpnewchar + "十"; break;
        case 2: if (perchar != 0) tmpnewchar = tmpnewchar + "百"; break;
        case 3: if (perchar != 0) tmpnewchar = tmpnewchar + "千"; break;
        case 4: tmpnewchar = tmpnewchar + "万"; break;
        case 5: if (perchar != 0) tmpnewchar = tmpnewchar + "十"; break;
        case 6: if (perchar != 0) tmpnewchar = tmpnewchar + "百"; break;
        case 7: if (perchar != 0) tmpnewchar = tmpnewchar + "千"; break;
        case 8: tmpnewchar = tmpnewchar + "亿"; break;
        case 9: tmpnewchar = tmpnewchar + "十"; break;
      }
      newchar = tmpnewchar + newchar;
    }
    //替换所有无用汉字，直到没有此类无用的数字为止
    while (newchar.search("零零") != -1 || newchar.search("零亿") != -1 || newchar.search("亿万") != -1 || newchar.search("零万") != -1) {
      newchar = newchar.replace("零亿", "亿");
      newchar = newchar.replace("亿万", "亿");
      newchar = newchar.replace("零万", "万");
      newchar = newchar.replace("零零", "零");
    }
    //替换以“一十”开头的，为“十”
    if (newchar.indexOf("一十") == 0) {
      newchar = newchar.substr(1);
    }
    //替换以“零”结尾的，为“”
    if (newchar.lastIndexOf("零") == newchar.length - 1) {
      newchar = newchar.substr(0, newchar.length - 1);
    }
    return newchar;
  };



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

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

  shareloder = () => {
    ajax.comStockListValidsharebasic({
    }).then((data) => {
      this.setState({
        shareloderWed: data.data,
      });
    });
  };

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

  renderShareloderMore = () => {
    return this.state.shareloderWed.map((val, key) => {
      return <Option key={key} value={"s1="+val.shareholderId + ",s2=" +val.name+",s3="+val.cerNo}>{val.name} ({val.cerNo})</Option>;
    });
  };

  //增加保障项目
  addArea = ()=> {
    const protectionList = this.state.comInsGuaProject;
    const pro_val = this.state.comInsGuaProject.length + 1;
    protectionList.push({
      seq:pro_val,
    });
    this.setState({
      comInsGuaProject: protectionList,
      proLength:pro_val,
    });
  };

  //减少保障项目
  reduceArea = (seq) => {
    const protectionList = this.state.comInsGuaProject;
    const pro_val = this.state.comInsGuaProject.length - 1;
    protectionList.splice(seq-1,1);
    this.setState({
      comInsGuaProject: protectionList,
      proLength:pro_val,
    });
  };

  checkIdCardMoney = (rule, value, callback) => {
    if (value && !(/^[1-9]\d{1,18}$|^[1-9]\d{1,18}\.{1}\d{1,2}$/g).test(value)) {
      callback('请输入正确的金额！');
    } else {
      callback();
    }
  };

  renderList = () => {
    const {getFieldDecorator} = this.props.form;

    const formItemLayout = {
      labelCol: {
        xs: {span: 24},
        sm: {span: 7},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 12},
        md: {span: 10},
      },
    };

    const arr = this.state.comInsGuaProject.map((val,key)=> {
      return (
        <div key={key+1} className="ownershipText">
        <h3>
          <Icon type="caret-down" style={{fontSize: 12, color: '#666'}}/>
          <span>变更项{this.Arabia_To_SimplifiedChinese(key+1)}</span>
          {val.seq === 1 ? '' : <em onClick={this.reduceArea.bind(this,val.seq)}>删除</em>}
        </h3>
        <FormItem
          {...formItemLayout}
          label="变更类型"
          style={{marginTop: '25px'}}
        >
          {getFieldDecorator('stockChangeType' + (val.seq), {
            rules: [{
              required: true, message: '请选择变更类型',
            }],
          })(
            <Select placeholder="请选择" index={val.seq} onSelect={this.handleChangeValue}>
              <Option value="1" lmb={val.seq}>增资</Option>
              <Option value="2" lmb={val.seq}>减资</Option>
              <Option value="3" lmb={val.seq}>股权转让</Option>
            </Select>
          )}
        </FormItem>
        {this.state[`val_text${val.seq}`] === 1 ? (<div>
          <FormItem
            {...formItemLayout}
            label="增资股东"
            style={{marginTop: '25px'}}
          >
            {getFieldDecorator('holderName'+ (val.seq), {
              rules: [{
                required: true, message: '请选择增资股东',
              }],
            })(
              <Select placeholder="请选择">
                {this.renderShareloderMore()}
              </Select>
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="增资额"
            style={{marginTop: '25px'}}
          >
            {getFieldDecorator('amount'+ (val.seq), {
              rules: [{
                required: true, message: '请输入增资额',
              },{
                validator: this.checkIdCardMoney
              }],
            })(
              <p>
                <Input addonAfter="元" maxLength={15}/>
                <span>填写金额后，出资比例自动计算</span>
              </p>
            )}
          </FormItem>
        </div>) : (this.state[`val_text${val.seq}`] === 2 ? <div>
          <FormItem
            {...formItemLayout}
            label="减资股东"
            style={{marginTop: '25px'}}
          >
            {getFieldDecorator('holderName'+ (val.seq), {
              rules: [{
                required: true, message: '请选择减资股东',
              }],
            })(
              <Select placeholder="请选择">
                {this.renderShareloderMore()}
              </Select>
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="减资额"
            style={{marginTop: '25px'}}
          >
            {getFieldDecorator('amount'+ (val.seq), {
              rules: [{
                required: true, message: '请输入减资额',
              },{
                validator: this.checkIdCardMoney
              }],
            })(
              <p>
                <Input addonAfter="元" maxLength={15}/>
                <span>填写金额后，出资比例自动计算</span>
              </p>
            )}
          </FormItem>
        </div> : <div>
          <FormItem
            {...formItemLayout}
            label="转让股东"
          >
            {getFieldDecorator('holderName'+ (val.seq), {
              rules: [{
                required: true, message: '请选择转让股东',
              }],
            })(
              <Select placeholder="请选择">
                {this.renderShareloderMore()}
              </Select>
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="转让额"
            style={{marginBottom:0}}
          >
            {getFieldDecorator('amount'+ (val.seq), {
              rules: [{
                required: true, message: '请输入转让额',
              },{
                validator: this.checkIdCardMoney
              }],
            })(
              <p>
                <Input addonAfter="元"  maxLength={15}/>
                <span>填写金额后，出资比例自动计算</span>
              </p>
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label="受让股东"
          >
            {getFieldDecorator('transId'+ (val.seq), {
              rules: [{
                required: true, message: '请选择受让股东',
              }],
            })(
              <Select placeholder="请选择">
                {this.renderShareloder()}
              </Select>
            )}
          </FormItem>
        </div>)}
      </div>)
    });
    return arr;
  };

  handleAdd = () => {
    let s = this.state.count;
    this.setState({
      count: (this.state.count++),
    })
  };

  handleOk = (e) => {
    this.setState({ confirmLoading: true });
    ajax.saveComStockChangeShare({"shareDetail":this.state.changeDetails}).then(() => {
      // message.success("提交成功");
      this.setState({ visible: false, confirmLoading: false });
      this.props.close();
    },() => {
      this.setState({ confirmLoading: false });
      // message.error(data.msg);
    });

  };
  handleCancel = (e) => {
    this.setState({
      visible: false,
    });
  };

  sdfsdfsd = (num) => {
    let arryss = [];
    arryss = num.split(",");
    let map =[];
    for(let i=0;i<arryss.length;i++){
      map.push(arryss[i].substring(0,arryss[i].indexOf("=")),arryss[i].substring(arryss[i].indexOf("=")+1,arryss[i].length));
    }
    return map;
  };

  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if(!err){
        values.shareDetail = [];
        for(let i=1;i<=this.state.proLength;i++){
          let sd = this.sdfsdfsd(values[`holderName${i}`]);
          let df = [];
          if(values[`transId${i}`]){
            df = this.sdfsdfsd(values[`transId${i}`])[1];
          }else{
            df = 0;
          }
          values.shareDetail.push({
            stockChangeType:values[`stockChangeType${i}`],
            amount:values[`amount${i}`],
            holderId:sd[1],
            holderName:sd[3],
            holderNo:sd[5],
            transId:df,
          });
          delete values[`stockChangeType${i}`];
          delete values[`amount${i}`];
          delete values[`holderName${i}`];
          if(values[`transId${i}`]){
            delete values[`transId${i}`];
          }
        }
        let flag = false;
        values.shareDetail.forEach((val, key)=>{
          if(val.stockChangeType === "3" && val.transId === val.holderId){
            flag = true;
          }
        });
        if(flag){
          message.warning("股东不可以把股权转让给自己");
          return;
        }

        values.shareDetail = JSON.stringify(values.shareDetail);
        ajax.comStockChangeSharePreview({...values}).then((data) => {
          //设置转让后的比例
          const json = JSON.parse(values.shareDetail);
          data.data.forEach(rec => {
            if(json[0].holderId === rec.shareholderId){
              json[0].prop = rec.contributionProp;
            }
          });
          this.setState({
            dataList:data.data,
            visible:true,
            changeDetails: JSON.stringify(json)
          });
        },() => {
          // message.error(data.msg);
        })
      }
    })
  };

  //表格渲染
  renderListOn = () => {
    const columns = [
      {
        title: '股东',
        dataIndex:'shareholderId',
        key:'shareholderId',
        render: (text, record) => (
          <div>
            <p style={{marginBottom:0}}>{record.name}</p>
            <p style={{marginBottom:0}}>{record.cerNo}</p>
          </div>
        )
      },
      {
        title: '出资额',
        dataIndex: 'contributionAmount',
        key: 'contributionAmount',
      },
      {
        title: '所占比例',
        dataIndex: 'contributionProp',
        key: 'contributionProp',
        render: (text, record) => (
          <div>
            <p>{record.contributionPropStr}</p>
          </div>
        )
      }
    ];

    let tmp = this.state.dataList.map((val,i) => {
      const param = val;
      param.key = i+1;
      return param;
    });

    return (
      <Table
        style={{ marginTop:'16px' }}
        dataSource={tmp}
        columns={columns}
        pagination={false}
      />
    );
  };

  render() {


    return (
      <div className="ChangeOwnership">
        <h2>
          <span>股权变更</span>
          <Icon type="exclamation-circle" style={{ fontSize: 14, color: '#d9d9d9',background:'none', }}/>
          <em>填写信息以工商局登记信息为准</em>
        </h2>
        <Button  onClick={()=>{
            // this.props.history.push(`/enterprise/reported/shareholder`);
            this.props.close();
          }}
          >返回</Button>
        <div className="change_person">
          <Form
            onSubmit={this.handleSubmit}
            style={{marginTop: 24}}
          >
            {this.renderList()}
          </Form>
        </div>
        <div className="renderAdd">
          <p onClick={this.addArea}>
            <Icon type="plus" style={{ fontSize:14,color:'rgba(0,0,0,.43)' }}/>
            <span>新增</span>
          </p>
        </div>
        <Button type="primary" style={{ display:'block',margin:'0 auto' }} htmlType="submit" onClick={this.handleSubmit}>预览股权结构</Button>

        <Modal
          title="股权结构预览"
          visible={this.state.visible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
          okText="确认无误"
          confirmLoading={this.state.confirmLoading}
          cancelText="返回修改"
          width="700px"
        >
          <Alert message="请认真核对各股东的出资额、出资比例是否与工商局登记信息一致。确认后将生成股东变更记录，变更记录不可修改！" type="success" showIcon />
          {this.renderListOn()}
        </Modal>
      </div>
    );
  }
}
