/*
* 表格编辑-两列结构
* */
import React, { Component, Fragment } from 'react';
import { connect } from 'dva';
import {
  Form, Select, Icon, Button, Input, Table, Upload, InputNumber, Switch, Radio, Checkbox,
} from 'antd';
import global from '@/global.less';
import index from './index.less';
import {
  sldTsvgBotText,
  failTip,
  getSldEmptyH,
  sldBeforeUpload,
  sldCheckEmail,getLocalStorageStingVal,sldComLanguage
} from '@/utils/utils';
import { apiUrl } from '@/utils/sldconfig.js';
import styles from '@/pages/store/pc_diy/pcdecorate.less';
import SldPreviewImg from '@/components/SldPreviewImg/SldPreviewImg';
import { Scrollbars } from 'react-custom-scrollbars';

const FormItem = Form.Item;
const Option = Select.Option;
const { TextArea } = Input;

let sthis = '';
@connect(({ product, global }) => ({
  product, global,
}))
@Form.create()
export default class SldTableEdit extends Component {
  constructor(props) {
    super(props);
    sthis = this;
    const {
      form: { getFieldDecorator },
    } = props;
    const uploadButton = (
      <div>
        <Icon type="plus"/>
        <div className="ant-upload-text">{sldComLanguage('上传图片')}</div>
      </div>
    );
    this.state = {
      source: '',//来源，主要处理特殊数据用
      selectedRowKeys: [],
      cur_data: {},//当前
      data: props.data,//表格数据
      preview_img: '',//预览的图片
      preview_alt_con: '', //预览图片的title，鼠标悬浮展示的内容
      show_preview_modal: false,//预览图片modal 是否展示
      rule_data: [],
      columns: [{
        align: 'right',
        width: 200,
        dataIndex: 'label',
        render: (text, record) => {
          return <div>
            <span className={styles.table_left_con}>{text}</span>
            {record.rules != undefined && record.rules[0] != undefined && record.rules[0].required &&
            <span className={styles.table_left_require}>*</span>
            }
          </div>;
        },
      }, {
        align: 'left',
        width: 700,
        dataIndex: 'name',
        render: (text, record) => {

          let content = '';

          if (record.type == 'upload_img_upload') {
            //单独的上传组件，带预览功能
            content = <FormItem
              extra={record.extra}
              style={{ width: '100%'}}
              disabled={record.disabled != undefined ? record.disabled : false}
            >
              <Upload
                withCredentials={true}
                beforeUpload={sldBeforeUpload}
                accept={'.gif, .jpeg, .png,.jpg,'}
                name={record.upload_name}
                action={record.upload_url}
                listType="picture-card"
                fileList={record.fileList}
                onPreview={this.viewImg}
                onChange={(info) => this.uploadChange(info, record.name)}
                headers={{
                  Authorization: 'Bearer ' + getLocalStorageStingVal('sld_token')
                }}
              >
                {record.fileList.length >= 999 ? null : uploadButton}
              </Upload>
            </FormItem>;
          }else if (record.type == 'textarea') {
            content = <FormItem
              extra={record.extra}
              style={{ width: 300 }}
            >
              {getFieldDecorator(text, { initialValue: record.initialValue, rules: record.rules })(
                <TextArea maxLength={record.maxLength!=undefined&&record.maxLength?record.maxLength:99999999}
                          disabled={record.disabled != undefined ? record.disabled : false}
                          style={{ minHeight: 32, width: 300 }} rows={4}
                          placeholder={record.placeholder}/>,
              )}
            </FormItem>;
          } else if (record.type == 'button') {
            content = this.props.btn_fixed_bottom == undefined ? <Fragment>
                <Button key="submit" type="primary" loading={this.props.submiting}
                        onClick={this.sldConfirm}>
                  {sldComLanguage('保存')}
                </Button>
                {this.props.showOtherBtn != undefined &&
                <Button style={{ marginLeft: 8 }} loading={this.props.submiting_sec}
                        onClick={this.otherBtnClick}>
                  {this.props.showOtherBtn.text}
                </Button>
                }
              </Fragment>
              : null;
          }
          return content;
        },
      }],
    };
  }

  first_flag = false;

  componentDidMount() {
    this.props.dispatch({
      type: 'global/getLayoutCollapsed',
    });
  }

  componentWillReceiveProps(nextProps, nextContext) {
    this.setState({ data: nextProps.data });
  }



  //预览图片
  viewImg = (file) => {
    this.setState({
      preview_img: file.url || file.thumbUrl,
      show_preview_modal: true,
    });
  };

  //关闭预览图片
  closeViewModal = () => {
    this.setState({
      show_preview_modal: false,
    });
  };

  uploadChange = (info, name) => {
    let { data } = this.state;
    if (info.file.status != undefined && info.file.status != 'error') {
      for (let i in data) {
        if (data[i].name == name) {
          data[i].fileList = info.fileList;
          data[i].img_succ_info = (info.file.response != undefined && info.fileList.length > 0 && info.file.response.data != undefined) ? info.file.response.data : [];
        }
      }
    }
    this.setState({ data });
  };




  //确定事件
  sldConfirm = (e) => {
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const { rule_data, data } = this.state;
        if (this.props.need_data != undefined && this.props.need_data) {
          this.props.handleSubmit(values, this.state.data);
        } else {

          //修改了审批规则
          // if (rule_data.length > 0) {
          // 	rule_data.map(item => {
          // 		delete item.data_index
          // 	})
          // 	values.approval_rules = JSON.stringify(rule_data)
          // } else {
          //修改审批规则
          let rule_arr = [];
          data.map((item, index) => {
            if (item.name == 'approval_rules') {
              if (rule_data.length > 0) {
                rule_data.map(item => {
                  delete item.data_index;
                });
              }
              rule_arr = rule_data.concat(item.initialValue);
              for (let i = 0; i < rule_arr.length; i++) {
                if (rule_arr[i].amount == '' && rule_arr[i].employeeId == '') {

                  rule_arr.splice(i, 1);
                  i = i - 1;
                }
              }
              let arr = JSON.stringify(rule_arr);
              values.approval_rules = arr;
            }
          });
          // }
          this.props.handleSubmit(values);
        }
      }
    });
  };

  otherBtnClick = (e) => {
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!values.notification_email_test_address) {
        failTip(`${sldComLanguage('请输入测试邮件')}`);
        return false;
      } else {
        //正则验证邮箱
        if (sldCheckEmail(values.notification_email_test_address)) {
          this.props.showOtherBtn.callback(values.notification_email_test_address);
        } else {
          failTip(`${sldComLanguage('请输入正确的邮箱')}`);
          return false;
        }
      }

    });
  };


  render() {
    const { columns, data, preview_img, show_preview_modal, modal_width, preview_alt_con } = this.state;
    const { scroll_h } = this.props;
    return <div className={index.sld_table_edit}>
      <Scrollbars
        autoHeight
        autoHeightMin={50}
        autoHeightMax={scroll_h != undefined ? document.body.clientHeight - scroll_h : document.body.clientHeight - 170}>
        <Form
          layout="horizontal"
        >
          <Table
            showHeader={false}
            columns={columns}
            dataSource={data}
            rowKey={record => record.name}
            bordered
            pagination={false}
          />
        </Form>
      </Scrollbars>
      {this.props.btn_fixed_bottom != undefined && this.props.btn_fixed_bottom &&
      <Fragment>
        {getSldEmptyH(50)}
        <div className={global.m_diy_bottom_wrap}
             style={{ position: 'fixed', left: this.props.global.collapsed ? 90 : 160 }}>
          <Button className={global.btn_fixed_bottom} key="submit" style={{
            width: 80, height: 32, borderRadius: 3,
          }}
                  type="primary" loading={this.props.submiting}
                  onClick={this.sldConfirm}>
            {sldComLanguage('保存')}
          </Button>
        </div>
      </Fragment>
      }
      {/*图片预览-start*/}
      <SldPreviewImg img={preview_img} show_preview_modal={show_preview_modal} modal_width={modal_width}
                     preview_alt_con={preview_alt_con} closePreviewModal={() => this.closeViewModal()}/>
      {/*图片预览-end*/}
    </div>;
  }
}


