import React, { useState, useEffect } from 'react';

import styles from './index.less';
import { Spin, Result, message, Upload, Button, Table, Space } from 'antd';
import { UploadOutlined, LoadingOutlined } from '@ant-design/icons';

import { Link, useIntl, connect, Dispatch, history } from 'umi';

import TitleSearch from '../../../components/TitleSearch/TitleSearch';


import { timestampToTime } from '../../../utils/time';
import { PAGE, RA, URLCLEAR, getCookie, DataClear, URL, filterObjbyTg, urlEncode, filterObj } from '@/utils/method';
import PageData from '@/models/Common/PageData';

const module = "User"
const module2 = "History"
const module3 = "PageData"
const Users = (props: any) => {

  const { formatMessage } = useIntl();

  const { dispatch, location, Data, CommunityList, pageData, history_url } = props;

  const SA = (values: any) => { dispatch({ type: 'User/SA', playload: values }) };

  const nameofowner = formatMessage({ id: 'R.charge.input.nameofowner' })
  const inputProject = formatMessage({ id: 'R.charge.input.project' })
  const username = formatMessage({ id: 'R.charge.username' })
  const project = formatMessage({ id: 'R.charge.project' })
  const unit = formatMessage({ id: 'R.charge.unit' })
  const status = formatMessage({ id: 'R.charge.status' })
  const submissionTime = formatMessage({ id: 'R.charge.submissionTime' })
  const actions = formatMessage({ id: 'R.charge.actions' })
  const search = formatMessage({ id: 'R.charge.search' })
  const addaccount = formatMessage({ id: 'R.charge.addaccount' })
  const paymentsetting = formatMessage({ id: 'R.charge.paymentsetting' })

  // const string2mean = [[0, "未注册"], [1, "注册"], [2, "注销"]]
  const string2mean = [[0, "Unregistered"], [1, "Registered"], [2, "Deregistered"]]

  const [curString, setCurString] = useState({ defaultCurrent: 1 })
  const [loading, setLoading] = useState(false)
  const [fileUploading, setFileUploading] = useState(false)

  const [compent, setCompent] = useState({ loading: false, fileUploading: false })
  const [pageStart, setPageStart] = useState(false)

  const [TestData, setTestData] = useState({})
  // 存储当前页码
  const [pageNum, setPageNum] = useState(1)
  // 存储小区筛选条件
  const [readyData, setReadyData] = useState(null as any)

  // 表格模块
  const columns = [
    { title: username, dataIndex: 'owerName', },
    { title: project, dataIndex: 'communityName', },
    // { title: project, dataIndex: 'unit', },
    // { title: unit, dataIndex: 'living', },
    { title: unit, render: (text: any, record: any) => (<div>{record.buildingNumber + "#" + record.floorNumber + "—" + record.roomNumber}</div>) },
    { title: status, dataIndex: 'enable', render: (text: any, record: any) => (<div>{string2mean[text][1]}</div>) },
    { title: submissionTime, render: (text: any, record: any) => (<div>{timestampToTime(record.createTime.time)}</div>) },
    {
      title: actions,
      render: (text: any, record: any) => (
        <Space size="middle">
          <a onClick={goToEdit.bind(this, record)} disabled={record.enable == 2 ? true : false}>Edit</a>
          <a onClick={goToDetail.bind(this, record)}>Detail</a>
        </Space>
      ),
    },
  ];

  // 上传的模块
  const propsUpload = {
    name: 'file',
    action: () => { return "http://47.74.233.180:8651/tos/excel/upload?userId=" + getCookie("id") },
    beforeUpload: (file: any) => {
      if (file.type !== "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") {
        message.error(`${file.name}  file format is incorrect!`);
      }
      return file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
    },
    onChange(info: any) {
      if (info.file.status == 'uploading') {
        setFileUploading(true)
      }
      if (info.file.status === 'done') {
        if (info.file.response.error_code == "0000") {
          history.push(location.pathname + "/Result")
        } else {
          history.push(location.pathname + "/ResultFailed")
          message.error(`${info.file.name} file upload failed.` + 'failed count is ' + info.file.response.data.count);
          setFileUploading(false)
        }
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} file upload failed.`);
        setFileUploading(false)
      }
    },
    showUploadList: false,
  }

  // 判断数据是否回来
  useEffect(() => {
    if (Data != null) {
      setLoading(false)
    }
  }, [Data])

  useEffect(() => {
    if (location.query.owerName) {
      setTestData({
        OwnerName: location.query.owerName
      })
    }
    setPageNum(parseInt(location.query.pageNum) || 1)

    setLoading(true)

    //获取数据
    RA(12, {
      owerName: location.query.owerName !== undefined ? (location.query.owerName) : null,
      communityArray: (readyData === null || readyData.length === 0) ? CommunityList : readyData,
      pageNum: location.query.pageNum || 1
    }, module, dispatch);

  }, [location])

  const goToDetail = (values: any, e: any) => {
    SA(values)
    PAGE(readyData, module3, dispatch)//保存页面参数
    history.push(location.pathname + '/Detail')
  }
  const goToEdit = (values: any, e: any) => {
    SA(values)
    PAGE(readyData, module3, dispatch)
    URL({ pathname: location.pathname + '/Edit', status: 1 }, module2, dispatch)
    history.push(location.pathname + '/Edit')
  }

  const goToAdd = () => {
    URL({ pathname: location.pathname + '/Add', status: 1 }, module2, dispatch)
    history.push(location.pathname + '/Add')
  }

  // LIFE用户管理页面的搜索按钮
  const CallBackTitleSearch = (comment: any) => {

    // 将筛选条件存储起来
    setReadyData(comment.serviceCommunityList)
    setPageNum(1)

    /*页面跳转*/
    if (comment.OwnerName) {
      history.push(location.pathname + urlEncode(filterObj({
        owerName: comment.OwnerName,
        pageNum: 1,
      })))
    } else {
      history.push(location.pathname + urlEncode(filterObj({
        pageNum: 1,
      })))
    }

  }

  const pageChange = (values: any) => {
    // 将当前页码存储起来
    setPageNum(values.current)

    /*页面跳转*/
    var tmp = filterObjbyTg(location.query, [])
    tmp["pageNum"] = values.current
    location.query.owerName ? tmp["owerName"] = location.query.owerName : null
    history.push(location.pathname + urlEncode(tmp))
  }

  return (
    <div className={styles.base}>
      {/* 头部组件 */}
      <TitleSearch
        listkey={["OwnerName"]}
        list={["Owner Name"]}
        community={"serviceCommunityList"}
        onSubmit={CallBackTitleSearch}
        defaultValue={TestData}
        checklist={pageData}
      />

      {/* 内容组件 */}
      <div className={styles.box2}>
        <button className={styles.buttonAdd2} onClick={goToAdd}>Create New Owner</button>
        <div className={styles.buttonAdd} >
          <Upload {...propsUpload}>
            <Button icon={compent.fileUploading ? null : <UploadOutlined />}>
              {compent.fileUploading ?
                <>
                  <Spin indicator={<LoadingOutlined style={{ fontSize: 16 }} spin />} />
                       Uploading
                  </>
                : "Batch Upload"}
            </Button>
          </Upload>
        </div>
      </div>

      {/* 列表组件 */}
      <Table
        rowKey={"id"}
        loading={loading}
        style={{ marginTop: 16 }}
        dataSource={Data != null ? Data.data.list : []}
        columns={columns}
        pagination={Data != null ? { current: pageNum, total: Data.data.page.totalRow, showSizeChanger: false, pageSize: Data.data.page.curPageSize } : {}}
        onChange={pageChange} />

    </div>
  );
};


function mapStateToProps(state: any) {

  const { sourceData, DataSave, Data, } = state.User;
  const { history_url } = state.History;
  const { pageData } = state.PageData;
  const { token } = state.login;
  const { CommunityList } = state.Init;
  return {
    Data,
    DataSave,
    sourceData,
    pageData,
    history_url,
    // token
    CommunityList,
  };
}



export default connect(mapStateToProps)(Users);

