import { ref, h } from "vue";
import { message } from "@/utils/message";
import { ElMessageBox } from "element-plus";
import {
  getConfigTypeList,
  getConfigSetInfo,
  SetConfigData
} from "@/api/modules/system";
import { addDialog } from "@/components/ReDialog";
export function useData() {
  const formRef = ref();
  const formData = ref({})
  const loading = ref(true);
  const activeId = ref(0)
  const tableList = ref([]);
  const formLabel = ref([])
  const isShow = ref(false);
  const onSearch = async () => {
    loading.value = true;
    const { data, code } = await getConfigTypeList({});
    if (code) {
      tableList.value = data
      activeId.value = data[0].id
      getInfo(activeId.value)
    }
    loading.value = false;
  };
  const getInfo = async (id) => {
    const { data, code } = await getConfigSetInfo({ type: id })
    if (code) {
      formLabel.value = code ? data : []
      if (data && data.length) {
        data.forEach(ele => {
          formData.value[ele.key_title] = ele.key_value
        })
      }
    }
    console.log(formData.value)
  }
  const tabClick = (event) => {
    const { name } = event.props
    getInfo(name)
  }
  const saveConfig = async () => {
    ElMessageBox.confirm(
      `该操作将覆盖之前的数据，是否继续？`,
      "提示",
      {
        type: "warning"
      }
    )
      .then(async () => {
        const { code, msg } = await SetConfigData({
          ...formData.value,
          type: activeId.value
        })
        if (code) {
          message("操作成功", { type: "success" });
          getInfo(activeId.value)
        } else {
          message(msg, { type: "error" });
        }
      })
      .catch(() => { });
  }
  return {
    onSearch,
    isShow,
    tableList,
    loading,
    activeId,
    formLabel,
    formData,
    tabClick,
    saveConfig
  };
}
