import { reactive, onMounted, ref, ElMessage, ElMessageBox, http, getGroupUrl, RegularVerification, verification, PaginationProps } from "@/utils/importUsed";
import { useRoute } from "vue-router";
import router from "@/router";

// 表单实例
const ruleFormRef = ref()
export function usePriRecursionStartTable() {
  // 接口列表实例
  let UrlList = reactive(null)
  // 获取当前板块接口列表
  onMounted(async () => {
    const route = useRoute();
    form.listId = Number(route.query.listId);

    UrlList = await getGroupUrl(["prizeSet"]);
    onSearch(ruleFormRef.value);
    listIdQuery();
    databaseIdQuery();

  });
  let form = reactive({
    tableEnName: "", //查询表
    listId: null,

  });
  const dataList = ref([]);
  const loading = ref(false);
  const dialogAddVisible = ref(false);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      type: "selection",
      width: 55,
      align: "left",
      hide: ({ checkList }) => !checkList.includes("勾选列")
    },
    {
      label: "序号",
      type: "index",
      width: 70,
      hide: ({ checkList }) => !checkList.includes("序号列")
    },
    {
      label: "ID",
      prop: "id",
      minWidth: 200
    },
    {
      label: "查询表",
      prop: "tableEnName",
      minWidth: 200
    },
    {
      label: "数据库",
      prop: "databaseId",
      width: 200,
      formatter: ({ databaseId }) => {
        return databaseIdOptionList.value.find(item => item.id == databaseId).title
      },
    },

    {
      label: "操作",
      fixed: "right",
      width: 200,
      slot: "operation"
    }
  ];
  // 当前页数量切换
  function handleSizeChange(val: number) {
    if (typeof val === "number") {
      pagination.pageSize = val;
      onSearch(ruleFormRef.value);
    }
  }
  // 当前页码切换
  function handleCurrentChange(val: number) {
    console.log(`current page: ${val}`);
    if (typeof val === "number") {
      pagination.currentPage = val;
      onSearch(ruleFormRef.value);
    }
  }
  // 选择表格项
  function handleSelectionChange(val) {
    console.log(`SelectionChange: ${val}`);
    onSearch(ruleFormRef.value);
  }
  // 搜索列表
  async function onSearch(formEl) {
    // 表单校验拦截
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
      if (valid) {
        //表单校验成功回调
        console.log('submit!')
        // 状态调整为加载中
        loading.value = true;
        // 调用接口（需动态生成接口）
        const { status, msg, data }: any = await http.Request({
          method: UrlList.prizeSet.prigetPriRecursionStartTableList.method,
          url: UrlList.prizeSet.prigetPriRecursionStartTableList.url,
          params: {
            ...form,
            pageSize: pagination.pageSize,
            pageNum: pagination.currentPage
          }
        });
        dataList.value = data.records;
        pagination.total = data.total;
        setTimeout(() => {
          loading.value = false;
        }, 500);
      } else {
        //表单校验失败回调
        ElMessage({
          message: "请输入完整信息",
          type: "error"
        });
      }
    })
  }

  // 配置ID选项数据
  const listIdOptionList = ref([]);
  //获取配置ID数据
  async function listIdQuery() {
    const { status, data }: any = await http.Request({ method: UrlList.prizeSet.prigetPriListDic.method, url: UrlList.prizeSet.prigetPriListDic.url, params: {} });
    if (status === 1) {
      listIdOptionList.value = data.records;
    }
  }

  //获取查询库数据
  const databaseIdOptionList = ref([]);
  const databaseIdQuery = async () => {
    const { status, data }: any = await http.Request({ method: UrlList.prizeSet.prigetPriDatabaseSetDic.method, url: UrlList.prizeSet.prigetPriDatabaseSetDic.url, params: {} });
    if (status === 1) {
      databaseIdOptionList.value = data.records;
    }
  };



  //跳转到递归开始条件字段
  function linkToPriRecursionStartField(row) {
    router.push({ path: '../../pri/priRecursionStartField/index', query: { objectTableId: row.id } });
  }
  //跳转到递归开始条件字段
  function linkToPriRecursionStartReturnField(row) {
    router.push({ path: '../../pri/priRecursionStartReturnField/index', query: { objectTableId: row.id } });
  }

  // 删除
  function handleDelete(row) {
    ElMessageBox.confirm(
      `是否删除该递归开始条件对象表? `,
      "提示",
      {
        confirmButtonText: "删除",
        cancelButtonText: "取消",
        type: "warning"
      }
    ).then(async () => {
      const { status, msg }: any = await http.Request({ method: UrlList.prizeSet.prideletePriRecursionStartTable.method, url: UrlList.prizeSet.prideletePriRecursionStartTable.url, params: String(row.id) });
      if (status === 1) {
        ElMessage({
          message: "删除成功",
          type: "success"
        });
        onSearch(ruleFormRef.value);
      } else {
        ElMessageBox.alert(msg, "提示", {
          confirmButtonText: "关闭",
          type: "warning"
        });
      };
    })
  }

  // 新增
  const addVisible = ref(false);
  function handleAdd() {
    addVisible.value = true;
  };

  // 修改
  const editUpdatePriRecursionStartTableVisible = ref(false);
  const editUpdatePriRecursionStartTableFormData = ref({});
  function handleUpdatePriRecursionStartTable(row) {
    editUpdatePriRecursionStartTableVisible.value = true;
    // 表格数据赋值
    editUpdatePriRecursionStartTableFormData.value = row;
  };

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    onSearch,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange,
    ruleFormRef,

    handleAdd,
    addVisible,
    handleUpdatePriRecursionStartTable,
    editUpdatePriRecursionStartTableVisible,
    editUpdatePriRecursionStartTableFormData,
    handleDelete,
    linkToPriRecursionStartField,
    linkToPriRecursionStartReturnField,
    listIdOptionList,

  };
}
