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

import styles from './index.less';
import { Form, Input, Spin, Table, Space, Button } from 'antd';
import { LoadingOutlined } from '@ant-design/icons';

import { urlEncode, filterObj, filterObjbyTg, RA } from '@/utils/method';

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

import TitleSearch from '../../../components/TitleSearch/TitleSearch';
import { TosSecurityGuarderGet } from '@/services/tos';

const module = 'User';
// 服务范围数据
let options: Array<[]> = [];

// 筛选参数
let readyData: any = {
  pageNum: 1,
  serviceCommunityList: [],
  serviceScope: '',
  providerName: '',
};
// 节流阀
let flag = false;

const ServiceProviderManagement = (props: any) => {
  const [loading, setLoading] = useState(false);

  const { dispatch, location, Data, CommunityList, DataServices } = props;

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

  const goToDetail = (values: any, e: any) => {
    SaveChooseData(values);
    history.push(location.pathname + '/Detail');
  };
  const goToCreate = () => {
    SaveChooseData(null);
    history.push(location.pathname + '/Edit');
  };
  const goToEdit = (values: any, e: any) => {
    SaveChooseData(values);
    history.push(location.pathname + '/Edit');
  };
  const goToServices = () => {
    history.push(location.pathname + '/Services');
  };

  const columns = [
    { title: 'Service Provider', dataIndex: 'providerName' },
    { title: 'contact Name', dataIndex: 'contactName' },

    {
      title: 'Contacts',
      dataIndex: 'contactPhone',
    },
    {
      title: 'Services Available',
      dataIndex: 'serviceScopeList',
      render: (text: any, record: any) => {
        let str: string = '';
        text.forEach((v: string, i: number) => {
          str += i === text.length - 1 ? v : v + ',';
        });
        return str;
      },
    },
    { title: 'Account Status', dataIndex: 'enable' },
    {
      title: 'Actions',
      render: (text: any, record: any) => (
        <Space size="middle">
          <a onClick={goToDetail.bind(this, record)}>Detail</a>
          <a onClick={goToEdit.bind(this, record)}>edit</a>
        </Space>
      ),
    },
  ];

  // 拿取服务商列表
  useEffect(() => {
    RA(43, {}, module, dispatch);
  }, []);

  useEffect(() => {
    if (DataServices) {
      options = DataServices.data.serviceScopeList.map((v: string, i: number) => {
        return [i, v];
      });
    }
  }, [DataServices]);

  // 请求
  const TosTosServiceProviderGet = () => {
    if (readyData.serviceCommunityList.length === 0) {
      readyData.serviceCommunityList = CommunityList;
    }
    dispatch({
      type: 'ServiceProvider/TosTosServiceProviderGet',
      playload: { ...readyData },
    });
  };

  // 监听路由url
  useEffect(() => {
    if (location.query) {
      readyData = {
        ...readyData,
        ...location.query,
      };
    }

    if (CommunityList && flag === false) {
      flag = true;
      setLoading(true);
      TosTosServiceProviderGet();
    }
  }, [location]);

  // 监听小区数据
  useEffect(() => {
    if (CommunityList && flag === false) {
      flag = true;
      setLoading(true);
      TosTosServiceProviderGet();
    }
  }, [CommunityList]);

  // 数据核查
  useEffect(() => {
    if (Data != null) {
      flag = false;
      setLoading(false);
    }
  }, [Data]);

  //页面搜索
  const CallBackTitleSearch = (comment: any) => {
    readyData.serviceCommunityList = comment.serviceCommunityList;
    history.push(
      location.pathname +
        urlEncode(
          filterObj({
            providerName: comment.providerName,
            serviceScope: comment.status,
            pageNum: 1,
          }),
        ),
    );
  };

  // 切换页码
  const pageChange = (values: any) => {
    let tmp = filterObjbyTg(location.query, ['providerName', 'serviceScope']);
    tmp['pageNum'] = values.current;
    history.push(location.pathname + urlEncode(tmp));
  };

  // 数据处理
  const dataSource = (values: any) => {
    let tmp = values;
    for (let items in tmp) {
      switch (tmp[items].enable) {
        case 0:
          tmp[items].enable = 'unregistered';
          break;
        case 1:
          tmp[items].enable = 'registered';
          break;
        case 2:
          break;
      }
    }
    for (let items in tmp) {
      for (let items1 in tmp[items].serviceScopeList) {
        switch (tmp[items].serviceScopeList[items1]) {
          case '0':
            tmp[items].serviceScopeList[items1] = '保安';
            break;
          case '1':
            tmp[items].serviceScopeList[items1] = '会计';
            break;
          case '2':
            tmp[items].serviceScopeList[items1] = '维修';
            break;
          case '3':
            tmp[items].serviceScopeList[items1] = '清洁';
            break;
        }
      }
    }
    return tmp;
  };

  // table组件配置
  const pagination = {
    current: readyData.pageNum,
    total: Data !== null ? Data.page.totalRow : null,
    showSizeChanger: false,
  };

  return (
    <div className={styles.base}>
      {/* 头部组件 */}
      <TitleSearch
        listkey={['providerName']}
        list={['Service Provider']}
        status={[
          {
            name: ['status', '服务范围'],
            data: [[null, '全部'], ...options],
          },
        ]}
        community={'serviceCommunityList'}
        onSubmit={CallBackTitleSearch}
        defaultValue={{
          providerName: readyData.providerName,
          status: readyData.serviceScope ? parseInt(readyData.serviceScope) : undefined,
        }}
        checklist={
          readyData.serviceCommunityList.length !== 0 ? readyData.serviceCommunityList : null
        }
      />

      {/* 内容组件 */}
      <div className={styles.box2}>
        <button className={styles.buttonAdd2} onClick={goToServices}>
          Avail Services
        </button>
        <button className={styles.buttonAdd} onClick={goToCreate}>
          Create New
        </button>
      </div>

      {/* 列表组件 */}
      <Spin spinning={Data != null ? false : true}>
        <Table
          size="small"
          rowKey={'id'}
          style={{ marginTop: 16 }}
          loading={loading}
          columns={columns}
          dataSource={Data != null ? dataSource(Data.rows) : null}
          pagination={Data != null ? pagination : {}}
          onChange={pageChange}
        />
      </Spin>
    </div>
  );
};

function mapStateToProps(state: any) {
  const { Data } = state.ServiceProvider;
  const { DataProvider, DataServices } = state.User;
  const { CommunityList } = state.Init;
  return {
    Data,
    DataProvider,
    CommunityList,
    DataServices,
  };
}

export default connect(mapStateToProps)(ServiceProviderManagement);
