import { connect } from 'dva/index';
import React, { Component, Fragment } from 'react';
import { Form, Spin, Switch } from 'antd';
import {
  failTip,
  sucTip,
  dragSldTableColumn,
  sldHandlePaginationData,
  formItemLayoutModal,
  getTableNum,
  sldComLanguage,
  getSldCopyData,
  sldtbaleOpeBtnText,
  sldPopConfirmDiy,
  list_com_page_size_10,
  sldLlineRtextAddGoodsAddMargin, sldIconBtnBg, validatorVendorEmail,validatorVendorMobile
} from '@/utils/utils';
import global from '@/global.less';
import StandardTable from '@/components/StandardTable';
import SldModal from '@/components/SldModal/SldModal';
import Search from '@/components/Search/Search';
import Link from 'umi/link';

let pageSize = list_com_page_size_10;
@connect(({ order, common }) => ({
  order,
  common,
}))
@Form.create()
export default class ReceiveMailSetting extends Component {
  constructor(props) {
    super(props);
    this.state = {
      initLoading: false,
      submiting: false,
      show_foot: false,
      data: {},//列表数据
      selectedRows: [],
      selectedRowKeys: [],//selectedRows的key
      title: '',
      addressType: props.type,//地址类型：1-发货地址；2-收货地址
      type: 'add',
      params: { pageSize: pageSize },//搜索条件
      upload_img_info: {},//上传的图片信息
      operateData: [],//操作的数据
      addData: [
        {
          type: 'input',
          label: `${sldComLanguage('邮箱')}`,
          name: 'email',
          initialValue: '',
          placeholder: `${sldComLanguage('请输入邮箱')}`,
          rules: [{
            required: true,
            whitespace: true,
            message: `${sldComLanguage('请输入邮箱')}`,
          }, { validator: (rule, value, callback) => validatorVendorEmail(rule, value, callback) }],
        },
        {
          type: 'input',
          label: `${sldComLanguage('手机号')}`,
          name: 'phone',
          initialValue: '',
          placeholder: `${sldComLanguage('请输入手机号')}`,
          rules: [{
            required: true,
            whitespace: true,
            message: `${sldComLanguage('请输入手机号')}`,
          }, { validator: (rule, value, callback) => validatorVendorMobile(rule, value, callback) }],
        },
      ],//modal框的数据
      formValues: {},//搜索条件、
      columns: [
        {
          title: '序号',
          dataIndex: 'id',
          align: 'center',
          width: 55,
          render: (text, record, index) => getTableNum(this.state.params, pageSize, index),
        },
        {
          title: `${sldComLanguage('邮箱')}`,
          dataIndex: 'email',
          align: 'center',
          width: 80,
        },
        {
          title: `${sldComLanguage('手机号')}`,
          dataIndex: 'phone',
          align: 'center',
          width: 80,
        },
        {
          title: `${sldComLanguage('操作人')}`,
          dataIndex: 'operateName',
          align: 'center',
          width: 120,
        },
        {
          title: `${sldComLanguage('操作时间')}`,
          dataIndex: 'createTime',
          align: 'center',
          width: 120,
        },
        {
          title: `${sldComLanguage('操作')}`,
          width: 150,
          align: 'center',
          render: (text, record) => (
            // ((record.isDel == 1) ?
            //   <Fragment>
            //     {sldtbaleOpeBtnText(`${sldComLanguage('编辑')}`, () => this.editEnquiryReceiverMail(record))}{/*编辑*/}
            //     <span className={global.splitLine}></span>
            //     {sldPopConfirmDiy('leftBottom', `${sldComLanguage('询盘邮箱删除后不可恢复，是否确定删除')}`, () => this.delEnquiryReceiverMailOperation(record.id), `${sldComLanguage('确定')}`, `${sldComLanguage('取消')}`,
            //       sldtbaleOpeBtnText(`${sldComLanguage('删除')}`, () => null))}
            //   </Fragment> : '-')
            <Fragment>
              {sldtbaleOpeBtnText(`${sldComLanguage('编辑')}`, () => this.editEnquiryReceiverMail(record))}{/*编辑*/}
              <span className={global.splitLine}></span>
              {sldPopConfirmDiy('leftBottom', `${sldComLanguage('询盘邮箱删除后不可恢复，是否确定删除')}`, () => this.delEnquiryReceiverMailOperation(record.id), `${sldComLanguage('确定')}`, `${sldComLanguage('取消')}`,
                sldtbaleOpeBtnText(`${sldComLanguage('删除')}`, () => null))}
            </Fragment>
          ),
        },
      ],
      search_data: [{
        type: 'input',
        label: `${sldComLanguage('邮箱')}`,
        name: 'email',
        placeholder: `${sldComLanguage('请输入邮箱')}`,
      },{
        type: 'input',
        label: `${sldComLanguage('手机号')}`,
        name: 'phone',
        placeholder: `${sldComLanguage('请输入手机号')}`,
      }],
    };
  }

  cur_edit_id = '';//当前操作数据id
  componentDidMount() {
    this.get_list({ pageSize: pageSize });
  }

  //新增询盘邮箱接收按钮
  addEnquiryReceiverMail = (val) => {
    let { addData, operateData, addressType } = this.state;
    operateData = getSldCopyData(addData);
    this.setState({
      type: 'addEnquiryReceiverMail',
      title: `${sldComLanguage('添加询盘接收邮箱')}`,
      operateData,
      modalVisible: true,
      show_foot: true,
    });
  };

  //编辑询盘邮箱接收按钮
  editEnquiryReceiverMail = (val) => {
    let { addData } = this.state;
    let operateData = getSldCopyData(addData);
    for (let i in operateData) {
      operateData[i].initialValue = val[operateData[i].name];
    }
    this.cur_edit_id = val.id;//当前操作数据id
    this.setState({
      type: 'editEnquiryReceiverMail',
      title: `${sldComLanguage('编辑询盘接收邮箱')}`,
      operateData,
      modalVisible: true,
      show_foot: true,
    });
  };

  //询盘邮箱接收操作按钮
  addEnquiryOperation = (params) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'order/enquiry_receiver_mail_setting_add',
      payload: {
        email: params.email,
        phone: params.phone,
      },
      callback: (res) => {
        if (res.state == 200) {
          sucTip(res.msg);
          this.setState({
            modalVisible: false,
            show_foot: false,
          });//询盘分配
          this.get_list({ pageSize: pageSize });
        } else {
          failTip(res.msg);
        }
        this.setState({ submiting: false });
      },
    });
  };

  //编辑询盘邮箱
  editEnquiryOperation = (params) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'order/enquiry_receiver_mail_setting_edit',
      payload:params,
      callback: (res) => {
        if (res.state == 200) {
          sucTip(res.msg);
          this.setState({
            modalVisible: false,
            show_foot: false,
          });//询盘分配
          this.get_list({ pageSize: pageSize });
        } else {
          failTip(res.msg);
        }
        this.setState({ submiting: false });
      },
    });
  };

  //询盘邮箱删除操作
  delEnquiryReceiverMailOperation = (val) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'order/enquiry_receiver_mail_setting_del',
      payload: {
        id: val,
      },
      callback: (res) => {
        if (res.state == 200) {
          sucTip(res.msg);
          this.get_list({ pageSize: pageSize });
        } else {
          failTip(res.msg);
        }
      },
    });
  };

  //获取数据列表
  get_list = (params) => {
    this.setState({ initLoading: true });
    const { dispatch } = this.props;
    const { addressType } = this.state;
    dispatch({
      type: 'order/get_enquiry_receiver_mail_setting_lists',
      payload: { ...params, type: addressType },
      callback: (res) => {
        this.setState({ initLoading: 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.get_list(params);
          } else {
            this.setState({
              data: res.data,
            });
          }
        }
      },
    });
  };

  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.get_list(params);
    }
  };


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

  sldHandleCancle = () => {
    this.setState({ modalVisible: false });
    this.setState({ submiting: false });
  };

  sldHandleConfirm = (val) => {
    const { addressType, type } = this.state;
    const { dispatch } = this.props;
    let _this = this;
    _this.setState({ submiting: true });

    if (type == 'addEnquiryReceiverMail') {
      let data = {
        email: val.email,
        phone: val.phone,
      };
      _this.addEnquiryOperation(data);
    }

    if(type == 'editEnquiryReceiverMail'){
      let data = {
        id:_this.cur_edit_id,
        email: val.email,
        phone: val.phone,
      };
      _this.editEnquiryOperation(data);
    }
  };


  //搜索框内容的变化
  sldSearChange = (val) => {
    this.setState({
      search_con: val.target.value,
    });
  };

  //清空搜索内容
  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.get_list({ pageSize: pageSize, ...values });
  };
  //搜索重置事件
  seaReset = () => {
    //搜索条件置为空
    this.setState({
      formValues: {},
      params: { pageSize: pageSize },
    });
    this.get_list({ pageSize: pageSize });
  };

  render() {
    const { selectedRows, search_data, columns, initLoading, data, submiting, operateData, modalVisible, title, show_foot } = this.state;
    return (
      <div className={global.common_page} style={{ flex: 1 }}>

        <div className={global.flex_com_space_between} style={{ marginBottom: 10 }}>
          {sldLlineRtextAddGoodsAddMargin('#69A2F2', `${sldComLanguage('设置询盘接收邮箱')}`, 0, 0, 10)}
          {sldIconBtnBg(() => this.addEnquiryReceiverMail(), 'ziyuan23', `${sldComLanguage('添加询盘接收邮箱')}`, '#fff', 7, 0, 15, 15, 3)}
        </div>

        <div style={{ position: 'relative' }}>
          <div className={global.tableListForm}>
            <Search search_data={search_data}
                    seaSubmit={(data) => this.search(data)} seaReset={() => this.seaReset()}
            />
          </div>

          <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>
          {/*新增/编辑对话框-start*/}
          <SldModal
            title={title}
            submiting={submiting}
            width={500}
            modalVisible={modalVisible}
            sldHandleConfirm={(val) => this.sldHandleConfirm(val)}
            sldHandleCancle={this.sldHandleCancle}
            formItemLayoutModal={formItemLayoutModal}
            content={operateData}
            show_foot={show_foot}
          />
          {/*新增/编辑对话框-end*/}
        </div>
      </div>

    );
  }
}
