<template>
  <el-dialog
    class="dialog-car-payload"
    :visible="dialogVisible"
    @close="handleClose"
    :destroy-on-close="false"
    :close-on-click-modal="configs.clickModalToClose ?? true"
  >
    <!-- main content  -->
    <BaseListTable
      v-loading="tableLoading"
      :table-config="tableConfig.table"
      :column-config="tableConfig.column"
      :table-data="dataList"
      @operate-event="handleOperate"
      :current-page="page"
      :current-size="size"
      :refresh-layout-key="refreshLayoutKey"
    />

    <el-pagination
      class="mt-5 flex justify-end"
      @size-change="handleSizeChange"
      @current-change="handlePageChange"
      :current-page.sync="page"
      :page-sizes="[1, 5, 10, 20, 50, 100]"
      :page-size="size"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"
    ></el-pagination>

    <!-- footer  -->
    <div slot="footer">
      <!-- <template v-for="(operate, index) in configs.form.operations">
        <el-button v-if="showButton(operate)" :key="'operation_' + index" :type="operate.type" @click="handleBtnClick(operate)">{{
          operate.label
        }}</el-button>
      </template> -->
      <el-button @click="handleBtnClick({ name: 'cancel' })">取消</el-button>
    </div></el-dialog
  >
</template>

<script>
export default {
  name: "DialogCarPayload",
  props: {
    configs: {
      type: Object,
      default: () => ({
        clickModalToClose: true,
        forms: null,
      }),
    },
    tableConfigs: {
      type: Object,
      default: () => ({
        table: null,
        column: null
      }),
    },
    dialogVisible: {
      type: Boolean,
      default: false,
    },
    // extraParams: {
    //   type: Object,
    //   default: () => ({})
    // }
  },
  inject: ["urls"],
  data() {
    return {
      loadingStatus: false,
      page: 1,
      size: 20,
      totalPage: 0,
      dataList: [],
      tableLoading: false,
      refreshLayoutKey: "",
    };
  },
  created() {},
  mounted() {},
  methods: {
    /** 获取 列表数据 */
    getList(queryParams) {
      this.tableLoading = true;

      const params = queryParams
        ? { ...queryParams, page: this.page, limit: this.size }
        : {
            page: this.page,
            limit: this.size,
          };

      if (!queryParams && this.listQueryExtra && this.listQueryExtra.length) {
        this.listQueryExtra.map((nameOrObj) => {
          if (typeof nameOrObj === "string") params[nameOrObj] = "";
          else if (typeof nameOrObj === "object") {
            Object.keys(nameOrObj).forEach((key) => {
              params[key] = nameOrObj[key];
            });
          }
        });
      }

      // if (this.urls.pageIsPostApi) {
      // } else {
      // 默认是 get 方式请求 page
      this.$http[this.urls.pageIsPostApi ? "post" : "get"](
        this.urls.page,
        this.urls.pageIsPostApi
          ? {
              ...params,
            }
          : {
              params,
            }
      )
        .then(({ data: res }) => {
          console.log("[http response] res is: ", res);

          if (res.code === 0) {
            // page 场景:
            if ("list" in res.data) {
              /** 破碎记录的特殊需求：数据要结合单位 material + materialUnitDictValue */
              if ("attachDictValue" in this.tableConfig.column) {
                this.dataList = res.data.list.map((row) => {
                  this.tableConfig.column.attachDictValue(row, "unit", "qty", "materialUnitDictValue");
                  return row;
                });
              } else this.dataList = res.data.list;

              this.totalPage = res.data.total;
            } else if ("records" in res.data) {
              this.dataList = res.data.records.map((item) => ({
                ...item,
                id: item._id ?? item.id,
              }));
              this.totalPage = res.data.total;
            } else {
              this.dataList.splice(0);
              this.totalPage = 0;
            }
          } else {
            this.$message({
              message: `${res.code}: ${res.msg}`,
              type: "error",
              duration: 2000,
            });
          }
          this.tableLoading = false;
        })
        .catch((err) => {
          this.$message({
            message: `${err}`,
            type: "error",
            duration: 2000,
          });
          this.tableLoading = false;
        });
    },

    /** 导航器的操作 */
    handleSizeChange(val) {
      // val 是新值
      this.page = 1;
      this.size = val;
      this.getList();
    },

    handlePageChange(val) {
      // val 是新值
      this.getList();
    },

    handleBtnClick(payload) {
      console.log("btn click payload: ", payload);

      if ("name" in payload) {
        switch (payload.name) {
          case "cancel":
            this.handleClose();
            break;
          // case "reset":
          //   this.resetForm(true, true); // true means exclude id, immediate execution
          //   break;
          // case "add":
          // case "update":
          //   this.addOrUpdate(payload.name === "add" ? "POST" : "PUT");
          //   break;
        }
      } else {
        console.log("[x] 不是这么用的! 缺少name属性");
      }
    },

    handleClose() {
      this.$emit("update:dialogVisible", false);
    },
  },
};
</script>

<style scoped></style>
