import { connect } from 'dva/index';
import React, { Component, Fragment } from 'react';
import { Form, Spin, Switch } from 'antd';
import {
  sldIconBtn,
  failTip,
  sucTip,
  getSldEmptyH,
  dragSldTableColumn,
  sldHandlePaginationData,
  formItemLayoutModal,
  getTableNum,
  sldComLanguage,
  getSldCopyData,
  sldtbaleOpeBtnText,
  sldPopConfirmDiy,
  mobile_reg,
  showMoreHelpTip,
  list_com_page_size_10,
  validatorNumbe,
  list_com_page_more,
  getSldComShowMoreTtex,
  sldLlineRtextAddGoods, 
  sldLlineRtextAddGoodsAddMargin,
} 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, global }) => ({
  order,
  common,
  global
}))
@Form.create()
export default class EnquiryLists 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',
      currentSite: props.global.currentSite,
      contactType: props.global.contactType,
      params: { pageSize: pageSize },//搜索条件
      upload_img_info: {},//上传的图片信息
      operateData: [],//操作的数据
      addData: [{
        type: 'input',
        label: `${sldComLanguage('姓名')}`,
        name: 'name',
        // extra: `${sldComLanguage('最多输入6个字')}`,
        initialValue: '',
      }, {
        type: 'input',
        label: `${sldComLanguage('邮箱')}`,
        name: 'email',
        initialValue: '',
      },
        {
          type: 'input',
          label: `${sldComLanguage('手机号')}`,
          name: 'phone',
          initialValue: '',
        },
        {
          type: 'input',
          label: `${sldComLanguage('国家/地区')}`,
          name: 'country',
          initialValue: '',
        },
        {
          type: 'input',
          label: `${sldComLanguage('公司')}`,
          name: 'company',
          initialValue: '',
        },
        {
          type: 'input',
          label: `${sldComLanguage('店铺')}`,
          name: 'storeName',
          initialValue: '',
        },
        {
          type: 'textarea',
          label: `${sldComLanguage('内容')}`,
          name: 'message',
          initialValue: '',
        },
        {
          type: 'input',
          label: `${sldComLanguage('IP')}`,
          name: 'ip',
          initialValue: '',
        },
        // {
        //   type: 'input',
        //   label: `${sldComLanguage('地区')}`,
        //   name: 'region',
        //   initialValue: '',
        // },
        {
          type: 'input',
          label: `${sldComLanguage('发送时间')}`,
          name: 'createTime',
          initialValue: '',
        },
        {
          type: 'input',
          label: `${sldComLanguage('询盘状态')}`,
          name: 'status',
          initialValue: '',
        },
        {
          type: 'input',
          label: `${sldComLanguage('询盘有效性')}`,
          name: 'validStatusStr',
          initialValue: '',
        },
        {
          type: 'input',
          label: `${sldComLanguage('询盘类型')}`,
          name: 'itemType',
          initialValue: '',
        },
        {
          type: 'textarea',
          label: `${sldComLanguage('询盘来源')}`,
          name: 'pageUrl',
          initialValue: '',
        },
        {
          type: 'input',
          label: `${sldComLanguage('跟踪人')}`,
          name: 'vendorName',
          initialValue: '',
        },
        {
          type: 'input',
          label: `${sldComLanguage('最近操作人')}`,
          name: 'lastUsername',
          initialValue: '',
        },
        {
          type: 'input',
          label: `${sldComLanguage('最后更新时间')}`,
          name: 'lastTime',
          initialValue: '',
        },
      ],//modal框的数据
      //询盘回复
      replayData: [
        {
          type: 'textarea',
          label: `${sldComLanguage('跟踪内容')}`,
          name: 'message',
          initialValue: '',
          extra: `${sldComLanguage('询盘跟踪内容最多500字')}`,
          placeholder: `${sldComLanguage('请输入询盘跟踪内容')}`,
          rules: [{
            required: true,
            message: `${sldComLanguage('跟踪内容必填')}`,
          }],
          maxLength: 500,
        },
      ],
      //询盘分配
      assignData: [
        {
          type: 'select',
          label: `${sldComLanguage('跟踪人')}`,
          name: 'vendorId',
          placeholder: `${sldComLanguage('请选择跟踪人')}`,
          sel_data: [],
          sele_key: 'vendorId',
          sele_name: 'vendorName',
          diy: true,
          rules: [{
            required: true,
            message: `${sldComLanguage('跟踪人必选')}`,
          }],
        },
      ],
      formValues: {},//搜索条件、
      columns: [
        {
          title: '序号',
          dataIndex: 'id',
          align: 'center',
          width: 55,
          render: (text, record, index) => getTableNum(this.state.params, pageSize, index),
        },
        {
          title: `${sldComLanguage('店铺')}`,
          dataIndex: 'storeName',
          align: 'center',
          width: 100,
          render: (text) => {
            return (text != null)?text:"平台";
          },
        },
        {
          title: `${sldComLanguage('姓名')}`,
          dataIndex: 'name',
          align: 'center',
          width: 100,
        },
        {
          title: `${sldComLanguage('邮箱')}`,
          dataIndex: 'email',
          align: 'center',
          width: 80,
        },
        {
          title: `${sldComLanguage('国家/地区')}`,
          dataIndex: 'country',
          align: 'center',
          width: 80,
        },
        {
          title: `${sldComLanguage('手机号')}`,
          dataIndex: 'phone',
          align: 'center',
          width: 80,
          render: (text, record, index) => {
            if(text == ""){
              return "-";
            }
            return record.phoneCode + '-' + text;
          },
        },
        {
          title: `${sldComLanguage('公司')}`,
          dataIndex: 'company',
          align: 'center',
          width: 100,
        },
        {
          title: `${sldComLanguage('内容')}`,
          dataIndex: 'message',
          align: 'center',
          width: 100,
          render: (text) => {
            return getSldComShowMoreTtex(text, 20, 300);
          },
        },
        {
          title: `${sldComLanguage('发送时间')}`,
          dataIndex: 'createTime',
          align: 'center',
          width: 120,
        },
        {
          title: `${sldComLanguage('询盘状态')}`,
          dataIndex: 'status',
          align: 'center',
          width: 120,
        },
        {
          title: `${sldComLanguage('询盘有效性')}`,
          dataIndex: 'validStatusStr',
          align: 'center',
          width: 120,
        },
        {
          title: `${sldComLanguage('询盘类型')}`,
          dataIndex: 'itemType',
          align: 'center',
          width: 120,
        },
        {
          title: `${sldComLanguage('询盘来源')}`,
          dataIndex: 'pageUrl',
          align: 'center',
          width: 120,
          render: (text, record, index) => (
            <Fragment>
              <Fragment><a href={record.pageUrl} target='_blank' style={{textDecoration:'underline'}}>联系我们</a></Fragment>
            </Fragment>
          ),
        },
        {
          title: `${sldComLanguage('跟踪人')}`,
          dataIndex: 'vendorName',
          align: 'center',
          width: 80,
        },
        {
          title: `${sldComLanguage('最近操作人')}`,
          dataIndex: 'lastUsername',
          align: 'center',
          width: 120,
        },
        {
          title: `${sldComLanguage('最后操作时间')}`,
          dataIndex: 'lastTime',
          align: 'center',
          width: 120,
        },
        {
          title: `${sldComLanguage('操作')}`,
          width: 150,
          align: 'center',
          fixed: 'right',
          render: (text, record) => (
            <Fragment>
              {sldtbaleOpeBtnText(`${sldComLanguage('详情')}`, () => this.detailEnquiry(record))}
              <span className={global.splitLine}></span>
              <Link to={{
                pathname: '/manage_order/enquiry_track_to_add',
                query: {
                  enquiry_id: record.id,
                  store_id: record.storeId
                },
              }}>
                {sldtbaleOpeBtnText(`${sldComLanguage('跟踪')}`)}
              </Link>
              {/* 只有管理员才可以操作 */}
              {/*{(record.isDel == 1) ?*/}
              {/*  <Fragment>*/}
              {/*    <span className={global.splitLine}></span>*/}
              {/*    {sldtbaleOpeBtnText(`${sldComLanguage('分配')}`, () => this.assignEnquiry(record))}*/}
              {/*    {(record.validStatus == 1)? <Fragment>*/}
              {/*      {sldPopConfirmDiy('leftBottom', `${sldComLanguage('标记为有效询盘，是否确定')}`, () => this.cancleMakeEnquiryGarbageOperation(record.id), `${sldComLanguage('确定')}`, `${sldComLanguage('取消')}`,*/}
              {/*        sldtbaleOpeBtnText(`${sldComLanguage('标为有效')}`, () => null))}*/}
              {/*    </Fragment> : <Fragment>*/}
              {/*      {sldPopConfirmDiy('leftBottom', `${sldComLanguage('标记为无效询盘，是否确定')}`, () => this.makeEnquiryGarbageOperation(record.id), `${sldComLanguage('确定')}`, `${sldComLanguage('取消')}`,*/}
              {/*        sldtbaleOpeBtnText(`${sldComLanguage('标为无效')}`, () => null))}*/}
              {/*    </Fragment>}*/}
              {/*    <span className={global.splitLine}></span>*/}
              {/*    {sldPopConfirmDiy('leftBottom', `${sldComLanguage('询盘删除后不可恢复，是否确定删除')}`, () => this.delEnquiryOperation(record.id), `${sldComLanguage('确定')}`, `${sldComLanguage('取消')}`,*/}
              {/*      sldtbaleOpeBtnText(`${sldComLanguage('删除')}`, () => null))}*/}
              {/*  </Fragment> : ''*/}
              {/*}*/}
              <span className={global.splitLine}></span>
              {sldtbaleOpeBtnText(`${sldComLanguage('分配')}`, () => this.assignEnquiry(record))}
              {(record.validStatus == 1)? <Fragment>
                {sldPopConfirmDiy('leftBottom', `${sldComLanguage('标记为有效询盘，是否确定')}`, () => this.cancleMakeEnquiryGarbageOperation(record.id), `${sldComLanguage('确定')}`, `${sldComLanguage('取消')}`,
                  sldtbaleOpeBtnText(`${sldComLanguage('标为有效')}`, () => null))}
              </Fragment> : <Fragment>
                {sldPopConfirmDiy('leftBottom', `${sldComLanguage('标记为无效询盘，是否确定')}`, () => this.makeEnquiryGarbageOperation(record.id), `${sldComLanguage('确定')}`, `${sldComLanguage('取消')}`,
                  sldtbaleOpeBtnText(`${sldComLanguage('标为无效')}`, () => null))}
              </Fragment>}
              <span className={global.splitLine}></span>
              {sldPopConfirmDiy('leftBottom', `${sldComLanguage('询盘删除后不可恢复，是否确定删除')}`, () => this.delEnquiryOperation(record.id), `${sldComLanguage('确定')}`, `${sldComLanguage('取消')}`,
                sldtbaleOpeBtnText(`${sldComLanguage('删除')}`, () => null))}
            </Fragment>
          ),
        },
      ],
      search_data: [{
        type: 'input',
        label: `${sldComLanguage('姓名')}`,
        name: 'name',
        placeholder: `${sldComLanguage('请输入姓名')}`,
      }, 
      {
        type: 'input',
        label: `${sldComLanguage('手机号')}`,
        name: 'phone',
        hide: props.global.contactType === 'email',
        placeholder: `${sldComLanguage('请输入手机号')}`,
      },
      {
        type: 'input',
        label: `${sldComLanguage('邮箱')}`,
        name: 'email',
        hide: props.global.contactType === 'mobile',
        placeholder: `${sldComLanguage('请输入邮箱')}`,
      },{
        type: 'select',
        label: `${sldComLanguage('询盘有效性')}`,
        name: 'validStatus',
        placeholder: `${sldComLanguage('请选择询盘有效性')}`,
        sel_data: [
          { key: '', name: `${sldComLanguage('全部')}` },
          { key: '0', name: `${sldComLanguage('有效')}` },
          { key: '1', name: `${sldComLanguage('无效')}` },
        ],
      },
        {
          type: 'select',
          label: `${sldComLanguage('店铺')}`,
          name: 'storeId',
          placeholder: `${sldComLanguage('请选择店铺')}`,
          sel_data: [],
          sele_key: 'storeId',
          sele_name: 'storeName',
          diy: true,
        },],

    };
  }

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

  //获取用户数据列表
  get_vendor_list = (record) => {
    const { dispatch } = this.props;
    let { assignData } = this.state;
    dispatch({
      type: 'order/get_return_subadmin_lists',
      payload: {storeId: record.storeId},
      callback: (res) => {
        if (res.state == 200) {
          let tmp_data = assignData.filter(item => item.name == 'vendorId')[0];
          tmp_data.sel_data = res.data.list;
          let { operateData, addressType } = this.state;
          operateData = getSldCopyData(assignData);
          for (let i in operateData) {
            operateData[i].initialValue = record[operateData[i].name];
          }
          this.cur_edit_id = record.id;//当前操作数据id
          this.setState({
            assignData,
            type: 'assign',
            title: `${sldComLanguage('询盘分配')}`,
            operateData,
            modalVisible: true,
            show_foot: true,
          });
        } else {
          failTip(res.msg);
        }
      },
    });
  };

  //获取店铺
  get_store_list = (params = {}) => {
    const { dispatch } = this.props;
    let { search_data } = this.state;
    dispatch({
      type: 'order/get_init_store_lists',
      payload: {},
      callback: (res) => {
        if (res.state == 200) {
          let tmp_data = search_data.filter(item => item.name == 'storeId')[0];
          tmp_data.sel_data = res.data.list;
          this.setState({
            search_data,
          });
        } else {
          failTip(res.msg);
        }
      },
    });
  };




  //询盘详情
  detailEnquiry = (val) => {
    let { addData, operateData, addressType } = this.state;
    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: 'detail',
      title: `${sldComLanguage('询盘详情')}`,
      operateData,
      modalVisible: true,
      show_foot: false,
    });//询盘详情
  };

  //询盘跟踪
  trackEnquiry = (val) => {
    if (val.vendorId != null) {
      let { replayData, operateData, addressType } = this.state;
      operateData = getSldCopyData(replayData);
      this.cur_edit_id = val.id;//当前操作数据id
      this.setState({
        type: 'track',
        title: `${sldComLanguage('询盘跟踪')}`,
        operateData,
        modalVisible: true,
        show_foot: true,
      });//询盘跟踪
    } else {
      failTip('请先将该询盘分配跟踪人，然后在填写跟踪记录');
    }
  };

  //询盘跟踪记录
  trackEnquiryRecord = (val) => {
    this.setState({ initTrackLoading: true });
    const { dispatch } = this.props;
    dispatch({
      type: 'order/get_enquiry_track_lists',
      payload: {
        enquiryId: val.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();
          } else {
            this.setState({
              dataTrack: res.data,
            });
          }
        }
      },
    });
  };

  //询盘跟踪操作
  trackEnquiryOperation = (params) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'order/enquiry_track',
      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 });
      },
    });
  };

  //询盘分配按钮
  assignEnquiry = (val) => {
    this.get_vendor_list(val);
  };

  //询盘分配操作
  assignEnquiryOperation = (params) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'order/enquiry_assign',
      payload: {
        enquiryId: params.enquiryId,
        vendorId: params.vendorId,
      },
      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 });
      },
    });
  };

  //询盘删除操作
  delEnquiryOperation = (val) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'order/enquiry_del',
      payload: {
        enquiryId: val,
      },
      callback: (res) => {
        if (res.state == 200) {
          sucTip(res.msg);
          this.setState({
              params: {
                current:1
              }
          });
          this.get_list({ pageSize: pageSize });
        } else {
          failTip(res.msg);
        }
      },
    });

  };

  //标记垃圾询盘操作
  makeEnquiryGarbageOperation = (val) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'order/enquiry_make_garbage',
      payload: {
        enquiryId: val,
      },
      callback: (res) => {
        if (res.state == 200) {
          sucTip(res.msg);
          this.setState({
            params: {
              current:1
            }
          });
          this.get_list({ pageSize: pageSize });
        } else {
          failTip(res.msg);
        }
      },
    });
  };

  //取消标记垃圾询盘操作
  cancleMakeEnquiryGarbageOperation = (val) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'order/enquiry_cancle_make_garbage',
      payload: {
        enquiryId: val,
      },
      callback: (res) => {
        if (res.state == 200) {
          sucTip(res.msg);
          this.setState({
            params: {
              current:1
            }
          });
          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_return_enquiry_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 == 'track') {
      let data = {
        enquiryId: _this.cur_edit_id,
        message: val.message,
      };
      _this.trackEnquiryOperation(data);
    }

    if (type == 'assign') {
      let data = {
        enquiryId: _this.cur_edit_id,
        vendorId: val.vendorId,
      };
      _this.assignEnquiryOperation(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 { contactType, currentSite, selectedRows, search_data, columns, initLoading, data, submiting, operateData, modalVisible, title, show_foot } = this.state;
    const renderSerchData = search_data.filter(item => !item.hide)
    return (
      <div className={global.common_page} style={{ flex: 1 }}>
        {sldLlineRtextAddGoodsAddMargin('#69A2F2', `${sldComLanguage('询盘管理')}`, 0, 0, 10)}
        <div className={global.tableListForm}>
          <Search search_data={renderSerchData}
                  seaSubmit={(data) => this.search(data)} seaReset={() => this.seaReset()}
          />
        </div>

        <Spin spinning={initLoading}>
          <div className={global.self_enquiry_list_wrap}>
          {/*标准表格-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*/}
          </div>
        </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>

    );
  }
}
