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 usePriList() {
  // 接口列表实例
  let UrlList = reactive(null)
  // 获取当前板块接口列表
  onMounted(async () => {
    const route = useRoute();
    form.projectId = Number(route.query.projectId);

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

  });
  let form = reactive({
    projectId: null, //项目
    prizeName: "", //奖励名称
    conditionMode: "", //条件模式
    prizeContent: "", //奖励内容
  });
  const dataList = ref([]);
  const loading = ref(false);
  const dialogAddVisible = ref(false);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 20,
    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: "kind",
      minWidth: 200,
      formatter: ({ kind }) => {
        var obj = kindOptionList.find(item => item.id == kind);
        return obj ? obj.label : ''
      },
    },
    {
      label: "奖励名称",
      prop: "prizeName",
      minWidth: 200
    },
    {
      label: "奖励比例",
      prop: "prizePercent",
      minWidth: 200
    },
    {
      label: "奖励固定金额",
      prop: "prizeAmount",
      minWidth: 200
    },
    {
      label: "条件模式",
      prop: "conditionMode",
      minWidth: 200
    },
    {
      label: "是否递归",
      prop: "recursionFlag",
      minWidth: 200
    },
    {
      label: "奖励内容",
      prop: "prizeContent",
      minWidth: 200
    },
    {
      label: "入参字段",
      prop: "requestParamField",
      minWidth: 200
    },

    {
      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.prigetPriListList.method,
          url: UrlList.prizeSet.prigetPriListList.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"
        });
      }
    })
  }
  // 项目选项数据
  const projectIdOptionList = ref([]);
  //获取项目数据
  async function projectIdQuery() {
    const { status, data }: any = await http.Request({ method: UrlList.prizeSet.prigetPriProjectDic.method, url: UrlList.prizeSet.prigetPriProjectDic.url, params: {} });
    if (status === 1) {
      projectIdOptionList.value = data.records;
    }
  }
  // 条件模式选项数据
  const conditionModeOptionList = [
    { id: 'all', label: '全部满足' },
    { id: 'one', label: '一个满足' },
    { id: 'two', label: '两个满足' },
    { id: 'three', label: '三个满足' },
  ]
  // 奖励内容选项数据
  const prizeContentOptionList = [
    { id: 'cash', label: '现金' },
    { id: 'recyc', label: '循环资格' },
    { id: 'coupon', label: '机具券' },
    { id: 'reserve', label: '额度' },
  ]
  // 奖励分类
  const kindOptionList = [
    { id: 'pos', label: '机具奖励' },
    { id: 'order', label: '订单奖励' },
    { id: 'reserve', label: '额度返还' },
  ]



  //跳转到奖励条件
  function linkToPriCondition(row) {
    router.push({ path: '../../pri/priCondition/index', query: { listId: row.id } });
  }
  //跳转到递归配置
  function linkToPriLoopSet(row) {
    router.push({ path: '../../pri/priLoopSet/index', query: { listId: row.id } });
  }
  //跳转到奖励记录
  function linkToPriRecord(row) {
    router.push({ path: '../../pri/priRecord/index', query: { listId: row.id } });
  }
  //跳转到奖励发放日志
  function linkToPriLog(row) {
    router.push({ path: '../../pri/priLog/index', query: { listId: row.id } });
  }
  //跳转到奖励入库表
  function linkToPriPrizeInTable(row) {
    router.push({ path: '../../pri/priPrizeInTable/index', query: { listId: row.id } });
  }
  //跳转到奖励金额设置
  function linkToPriListAmountSet(row) {
    router.push({ path: '../../pri/PriListAmountSet/index', query: { listId: row.id } });
  }
  //跳转到递归开始条件对象表
  function linkToPriRecursionStartTable(row) {
    router.push({ path: '../../pri/priRecursionStartTable/index', query: { listId: row.id } });
  }
  //跳转到递归停止条件对象表
  function linkToPriRecursionEndTable(row) {
    router.push({ path: '../../pri/priRecursionEndTable/index', query: { listId: row.id } });
  }

  // 删除
  function handleDelete(row) {
    ElMessageBox.confirm(
      `是否删除该奖励配置? `,
      "提示",
      {
        confirmButtonText: "删除",
        cancelButtonText: "取消",
        type: "warning"
      }
    ).then(async () => {
      const { status, msg }: any = await http.Request({ method: UrlList.prizeSet.prideletePriList.method, url: UrlList.prizeSet.prideletePriList.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 editUpdatePriListVisible = ref(false);
  const editUpdatePriListFormData = ref({});
  function handleUpdatePriList(row) {
    editUpdatePriListVisible.value = true;
    // 表格数据赋值
    editUpdatePriListFormData.value = row;
  };

  return {
    form,
    loading,
    columns,
    dataList,
    pagination,
    onSearch,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange,
    ruleFormRef,
    projectIdQuery,
    projectIdOptionList,
    conditionModeOptionList,
    prizeContentOptionList,

    handleAdd,
    addVisible,
    handleUpdatePriList,
    editUpdatePriListVisible,
    editUpdatePriListFormData,
    handleDelete,
    linkToPriCondition,
    linkToPriLoopSet,
    linkToPriRecord,
    linkToPriLog,
    linkToPriPrizeInTable,
    linkToPriListAmountSet,
    linkToPriRecursionStartTable,
    linkToPriRecursionEndTable,

  };
}
