import React, { useState, useEffect, useRef } from 'react';
import styles from './Services.less';
import { Form, message } from 'antd';
import { connect } from 'umi';

import Line from '../../../components/Line/Line';
import TagSelect from '../../../components/TagSelect/index';
import { RA, Clear } from '@/utils/method';
import TitleBack from '@/components/TitleBack/TitleBack';

const module = 'User';
interface DataType {
  serviceName: string;
  id: string;
}
const Services = (props: any) => {
  const { dispatch, DataServices, Result } = props;
  const formRef = useRef(null as any);
  const [DataList, setDataList] = useState(Object);

  useEffect(() => {
    RA(43, {}, module, dispatch);
  }, []);

  useEffect(() => {
    if (DataServices != null) {
      console.log(DataServices);
      setDataList(DataServices.data.rows);
      let tmp = DataServices.data.rows.map(
        (v: { serviceName: string; deleted: number }, i: number) => {
          return v.deleted !== 1 && v.serviceName;
        },
      );
      console.log(tmp);
      formRef.current['setFieldsValue']({ serviceName: tmp });
    }
  }, [DataServices]);

  // 添加服务范围
  const Add = (values: string, index?: number) => {
    RA(
      44,
      {
        serviceName: values,
        id: index ? DataList[index].id : null,
      },
      module,
      dispatch,
    );
  };

  // 删除服务范围
  const Remove = (values: string) => {
    DataList.forEach((obj: DataType) => {
      if (obj.serviceName === values) {
        RA(
          53,
          {
            id: obj.id,
          },
          module,
          dispatch,
        );
      }
    });
  };

  useEffect(() => {
    console.log(Result);
    if (Result) {
      if (Result.error_code !== '0000') {
        message.error('Failed: binding service provider!!!');
      } else {
        message.success('Operate Success!!!');
      }
      Clear(module + '/ClearResult', dispatch);
      RA(43, {}, module, dispatch);
    }
  }, [Result]);

  return (
    <div className={styles.base}>
      <TitleBack title={'Services Available Management'}></TitleBack>

      {DataServices !== null ? (
        <Form ref={formRef} name="basic">
          <div className={styles.title}>General Service Provider :</div>
          <Form.Item label="Available Services" name="serviceName">
            <TagSelect onAdd={Add} onRemove={Remove} />
          </Form.Item>
          <Line />
        </Form>
      ) : null}
    </div>
  );
};

function mapStateToProps(state: any) {
  const { DataServices, Result } = state.User;
  return {
    DataServices,
    Result,
  };
}
export default connect(mapStateToProps)(Services);
