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

import styles from './index.less';
import { Table, Space, Button, message } from 'antd';

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

import { connect, history } from 'umi';

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

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

interface readyType {
  pageNum: number;
  serviceCommunityList: Array<string>;
  serviceScope: string;
  providerName: string;
}

interface valuesType {
  serviceScope: string;
  serviceScopeList: Array<''>;
}

interface propsType {
  Data: { rows: Array<object>; page: { totalRow: number; curPageSize: number } };
  CommunityList: Array<''>;
  DataServices: { data: { rows: Array<{}> } };
  dispatch: any;
  location: any;
}

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

const ServiceProviderManagement = (props: propsType) => {
  const permissionArr = JSON.parse(localStorage.getItem('permission') || '');

  const [loading, setLoading] = useState(false);

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

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

  const goToDetail = (values: valuesType, e: any) => {
    if (permissionArr.indexOf('6') < 0) {
      message.error('No Permissions!!!', 3);
      return;
    }

    SaveChooseData(values);

    if (values.serviceScope === 'Accounting Service') {
      history.push(location.pathname + '/AccoutingDetail');
    } else {
      history.push(location.pathname + '/Detail');
    }
  };

  const goToEdit = (values: object, e: any) => {
    if (permissionArr.indexOf('7') < 0) {
      message.error('No Permissions!!!', 3);
      return;
    }
    SaveChooseData(values);
    history.push(location.pathname + '/Edit');
  };

  const goToCreate = () => {
    if (permissionArr.indexOf('8') < 0) {
      message.error('No Permissions!!!', 3);
      return;
    }
    SaveChooseData(null);
    history.push(location.pathname + '/Edit');
  };

  const goToServices = () => {
    history.push(location.pathname + '/Services');
  };

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

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

    {
      title: 'Contacts',
      dataIndex: 'contactPhone',
    },
    {
      title: 'Services Available',
      dataIndex: 'serviceScope',
      // render: (text: Array<''>, record: object) => {
      //   let type: string = '';
      //   if (options.length > 0) type = options[text[0]][1];
      //   return type;
      // },
    },
    { title: 'Account Status', dataIndex: 'enable' },
    {
      title: 'Actions',
      render: (text: string, record: any) => (
        <Space size="middle">
          <Button
            type="link"
            size="small"
            disabled={record.enable == 'Deregistered' ? true : false}
            onClick={goToEdit.bind(this, record)}
          >
            Edit
          </Button>
          <Button type="link" size="small" onClick={goToDetail.bind(this, record)}>
            Detail
          </Button>
        </Space>
      ),
    },
  ];

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

  // 处理服务商数据
  useEffect(() => {
    if (DataServices) {
      console.log(DataServices);
      options = DataServices.data.rows.map((v: any) => {
        return [v.serviceCode, v.serviceName];
      });
    }
  }, [DataServices]);

  // 监听路由url
  useEffect(() => {
    if (location.query) {
      readyData = {
        ...readyData,
        ...location.query,
      };
    }
    console.log(location.query);
    console.log(readyData);
    if (CommunityList && flag === false) {
      flag = true;
      setLoading(true);
      TosTosServiceProviderGet();
    }
  }, [location]);

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

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

  //页面搜索
  const CallBackTitleSearch = (comment: any) => {
    console.log(comment);
    readyData.serviceCommunityList = comment.serviceCommunityList;
    if (comment.status == undefined) {
      comment.status = '';
    }
    console.log(comment);

    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 = 'Normal';
          break;
        case 1:
          tmp[items].enable = 'Deregistered';
          break;
        case 2:
          break;
      }
    }
    return tmp;
  };

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

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

      {/* 列表组件 */}
      {
        <Table
          rowKey={'id'}
          style={{ marginTop: 16 }}
          loading={loading}
          columns={columns}
          dataSource={Data ? dataSource(Data.rows) : []}
          pagination={
            Data
              ? {
                  current: +readyData.pageNum,
                  total: Data.page.totalRow,
                  showSizeChanger: false,
                  pageSize: Data.page.curPageSize,
                }
              : {}
          }
          onChange={pageChange}
        />
      }
    </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);
