"use strict";
import React, { useState, useEffect } from "react";
import * as commonUtils from "../../utils/commonUtils";
import * as formUtils from "../../utils/formUtils";

import { Checkbox } from "antd";

const { Group } = Checkbox;
/**
 * commonProps 独立配置
 * showSearch : 是否可输入搜索，默认否 openSearch
 * requestFunc : 外部传进网络请求方法，只能接受返回数组[] ,切记
 * url : 如需网络获取选择列表，需提供url
 * params ： 网络请求参数
 *
 * list : 默认选择列表
 * key :  对象key对应字段，即返回的value
 * text :  对象name对应字段，即显示的name
 * showName :  对象name对应字段，即显示的name
 * specialReturn : 特殊返回函数,进行特殊处理，如不止需要返回选中 value时，可通过此方法返回,返回为数组或对象，结合antd的API，自行注意
 *
 *
 * uiOptions 为antd中Select自带属性,参考antd中API
 *
 * bs:func 传值，不能被转json后
 */
const displayName = "CheckboxCommon";
const CheckboxCommon = props => {
  const {
    onChange,
    name,
    value,
    schema: { commonProps = {} },
    options: uiOptions
  } = props;

  const {
    requestFunc,
    url,
    params,
    list,
    key = "key",
    text = "preName",
    okPath // 支持请求指向数据
  } = commonProps;

  const [state, set] = useState(null);

  useEffect(() => {
    if (list) setList(list);
    // 需要网络请求
    else if (url && requestFunc) {
      post("");
    }
  }, []);

  const post = async () => {
    // 组装请求参数
    requestFunc(url, params, okPath).then(req => {
      setList(commonUtils.getFirstList(req));
    });
  };

  const setList = data => {
    let list = formUtils.getCPDicList(data, key, text);
    list && set(list);
  };

  const handleChange = value => {
    onChange(name, value?.length ? value : null);
  };

  return (
    state && (
      <Group
        style={{ width: "100%" }}
        value={Array.isArray(value) ? value : []}
        options={state}
        onChange={handleChange}
        {...uiOptions}
      />
    )
  );
};

export default CheckboxCommon;
