import { connect } from 'dva/index';
import React, { Component, Fragment } from 'react';
import { Form,Popover,Spin } from 'antd';
import {
  sldLlineRtextAddGoods,
  failTip,
  sucTip,
  getSldEmptyH,
  sldComLanguage,
  quillEscapeToHtml,
  sldHandlePaginationData,
  dragSldTableColumn,
  list_com_page_size_5,
  getTableNum,
  getSldComShowMoreTtex, sldtbaleOpeBtnText, sldPopConfirmDiy, list_com_page_more,
} from '@/utils/utils';
import global from '@/global.less';
import SldEditFormCom from '@/components/SldEditFormCom/SldEditFormCom';
import SldUEditor from '@/components/SldUEditor';
import { Scrollbars } from 'react-custom-scrollbars';
import StandardTable from '@/components/StandardTable';
import Link from 'umi/link';
import Search from '@/components/Search/Search';

let pageSize = list_com_page_size_5;

@connect(({ product, global }) => ({
  product, global,
}))
@Form.create()
export default class AddTrack extends Component {

  constructor(props) {
    super(props);
    this.state = {
      initEditorFlag: false,//加载百度编辑器
      getEditorContentFlag: false,//获取百度编辑器内容标识
      initEditorContent: '',//百度编辑器内容
      flag: false,
      query: props.location.query,

      // 询盘跟踪记录
      params: { pageSize: pageSize },//搜索条件
      initLoading: false,
      submiting: false,
      show_foot: false,
      data: {},//列表数据
      selectedRows: [],
      selectedRowKeys: [],//selectedRows的key
      columns: [
        {
          title: '序号',
          dataIndex: 'id',
          align: 'center',
          width: 55,
          render: (text, record, index) => getTableNum(this.state.params, pageSize, index),
        },
        {
          title: `${sldComLanguage('跟踪人')}`,
          dataIndex: 'vendorName',
          align: 'center',
          width: 80,
        },
        {
          title: `${sldComLanguage('跟踪内容')}`,
          dataIndex: 'message',
          align: 'center',
          width: 100,
          render: (text) => {
            let messageText = quillEscapeToHtml(text);
            return <Fragment>
              <Popover placement="leftBottom" content={<div className={global.com_zoom}
                                                            dangerouslySetInnerHTML={{ __html: messageText }}></div>}
                       title={sldComLanguage('跟踪内容')}>
                <span style={{ cursor: 'pointer' }}>{sldComLanguage('查看')}</span>
              </Popover>
            </Fragment>;
          },
        },
        {
          title: `${sldComLanguage('跟踪时间')}`,
          dataIndex: 'createTime',
          align: 'center',
          width: 120,
        },
      ],

      search_data: [, {
        type: 'select',
        label: `${sldComLanguage('跟踪人')}`,
        name: 'vendorId',
        placeholder: `${sldComLanguage('请选择跟踪人')}`,
        sel_data: [],
        diy: true,
        sele_key: 'vendorId',
        sele_name: 'vendorName',
      },, {
        type: 'input',
        label: `${sldComLanguage('跟踪内容')}`,
        name: 'message',
        placeholder: `${sldComLanguage('请输入跟踪内容')}`,
      }],
    };
  }

  componentDidMount() {
    const { query } = this.state;
    this.setState({ initEditorFlag: true });
    this.get_vendor_list(query.store_id);
    if (query.enquiry_id != undefined && query.enquiry_id != null && query.enquiry_id != '' && query.enquiry_id > 0) {
      this.trackEnquiryRecord({ pageSize: pageSize });
    }
  }

  componentWillUnmount() {

  }

  //跟踪人列表
  get_vendor_list = (storeId) => {
    const { dispatch } = this.props;
    let { search_data } = this.state;
    dispatch({
      type: 'order/get_return_subadmin_lists',
      payload: {storeId},
      callback: (res) => {
        if (res.state == 200) {
          let tmp_data = search_data.filter(item => item.name == 'vendorId')[0];
          tmp_data.sel_data = res.data.list;
          this.setState({
            search_data,
          });
        } else {
          failTip(res.msg);
        }
      },
    });
  };

  //询盘跟踪记录
  trackEnquiryRecord = (params) => {
    const { query } = this.state;
    this.setState({ initTrackLoading: true });
    const { dispatch } = this.props;
    dispatch({
      type: 'order/get_enquiry_track_lists',
      payload: { ...params, enquiryId: query.enquiry_id },
      callback: (res) => {
        this.setState({ initTrackLoading: false });
        if (res.state == 200) {
          if ((res.data.list == null || res.data.list.length == 0) && this.state.params.current > 1) {
            params.current = params.current - 1;
            this.trackEnquiryRecord(params);
          } else {
            this.setState({
              data: res.data,
            });
          }
        }
      },
    });
  };

  handleSaveAllData = () => {
    this.setState({ getEditorContentFlag: true });
  };

  //获取编辑器内容
  getEditorContent = (con) => {
    this.saveData(con);
    this.setState({ getEditorContentFlag: false });
  };

    //询盘跟踪操作
  saveData = (editorCon) => {
    let _this = this;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const { dispatch } = this.props;
        values.message = editorCon;
        const { query } = this.state;
        values.enquiryId = query.enquiry_id;
        dispatch({
          type: 'order/enquiry_track',
          payload: values,
          callback: (res) => {
            if (res.state == 200) {
              sucTip(res.msg);
              // this.trackEnquiryRecord({ pageSize: pageSize });
              _this.props.history.goBack();
            } else {
              failTip(res.msg);
            }
          },
        });
      }
    });
  };


  //清空搜索内容
  sldSearClear = () => {
    this.setState({
      search_con: '',
    });
    this.sldSearch('');
  };

  //搜索事件
  search = (data) => {
    const values = { ...data };
    for (let i in values) {
      if (values[i] == '') {
        delete values[i];
      }
    }
    this.setState({
      formValues: values,
      params: { pageSize: pageSize }
    });
    this.trackEnquiryRecord({ pageSize: pageSize, ...values });
  };

  //搜索重置事件
  seaReset = () => {
    //搜索条件置为空
    this.setState({
      formValues: {},
      params: { pageSize: pageSize }
    });
    this.trackEnquiryRecord({ pageSize: pageSize });
  };


  handleSelectRows = (rows, rowkeys) => {
    this.setState({
      selectedRows: rows,
      selectedRowKeys: rowkeys,
    });
  };

  handleTablePagination = (pagination, filtersArg, sorter, type = 'main') => {
    const { formValues } = this.state;
    if (type == 'main') {
      const params = sldHandlePaginationData(pagination, filtersArg, sorter, formValues);
      pageSize = params.pageSize;
      this.setState({ params });
      this.trackEnquiryRecord(params);
    }
  };

  //表格拖动
  resizeTable = (index, size, type, data) => {
    let datas = dragSldTableColumn(index, size, data);
    this.setState({ [type]: datas });
  };

  render() {
    const { search_data, initEditorFlag, getEditorContentFlag, initEditorContent, initLoading, data, columns, selectedRows } = this.state;
    return (
      <div className={global.common_page_20}
           style={{ display: 'flex', flexDirection: 'column', justifyContent: 'flex-start' }}>
        {sldLlineRtextAddGoods('#69A2F2', `${sldComLanguage('跟踪记录')}`)}
        <div className={global.tableListForm}>
          <Search search_data={search_data}
                  seaSubmit={(data) => this.search(data)} seaReset={() => this.seaReset()}
          />
        </div>
        {getSldEmptyH(10)}

        <Spin spinning={initLoading}>
          {/*标准表格-start*/}
          <StandardTable
            selectedRows={selectedRows}
            data={data}
            rowKey={'id'}
            isCheck={false}
            columns={columns}
            onSelectRow={this.handleSelectRows}
            onChange={(pagination, filtersArg, sorter) => this.handleTablePagination(pagination, filtersArg, sorter, 'main')}
            onSldHandleSeleRow={this.onSldHandleSeleRow}
            resizeTable={(index, size) => this.resizeTable(index, size, 'columns', columns)}
            isColumnResize={true}
          />
          {/*标准表格-end*/}

        </Spin>

        <Scrollbars
          autoHeight
          autoHeightMin={100}
          autoHeightMax={document.body.clientHeight - 140}
        >
          <div className={global.tableListFormAdd}>
            <div style={{ display: 'flex', flexDirection: 'column' }}>
              <Form onSubmit={() => this.handleSaveAllData()} layout="inline">
                {getSldEmptyH(25)}
                {sldLlineRtextAddGoods('#69A2F2', `${sldComLanguage('跟踪内容')}`)}
                <div className={global.goods_sku_tab} style={{ marginTop: 20, position: 'relative' }}>
                  {initEditorFlag &&
                  <SldUEditor id={'agreement'} getContentFlag={getEditorContentFlag}
                              getEditorContent={this.getEditorContent} initEditorContent={initEditorContent}/>
                  }
                </div>

                <div className={global.m_diy_bottom_wrap}
                     style={{ position: 'fixed', left: this.props.global.collapsed ? 90 : 160 }}>
                  <div onClick={() => this.props.history.goBack()} className={global.add_goods_bottom_btn}>
                    {sldComLanguage('返回')}
                  </div>

                  <div onClick={() => this.handleSaveAllData()}
                       className={`${global.add_goods_bottom_btn} ${global.add_goods_bottom_btn_sel}`}>
                    {sldComLanguage('保存并返回')}
                  </div>
                </div>
              </Form>
            </div>
          </div>
        </Scrollbars>
      </div>
    );
  }
}
