<!-- 表格页加上搜索条件 -->
<template>
  <div class="list-view-with-head">
    <BaseSearchForm :head-config="headConfig" @btn-click="handleBtnClick" />

    <div class="blender">
      <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="[10, 20, 50, 100]"
        :page-size="size"
        :total="totalPage"
        layout="total, sizes, prev, pager, next, jumper"></el-pagination>
    </div>

    <div class="press" style="margin-top: 24px">
      <BaseListTable
        v-loading="pressTableLoading"
        :table-config="pressTableConfig.table"
        :column-config="pressTableConfig.column"
        :table-data="pressDataList"
        @operate-event="handleOperatePress"
        :current-page="pressPage"
        :current-size="pressSize"
        :refresh-layout-key="refreshLayoutKeyPress" />

      <el-pagination
        class="mt-5 flex justify-end"
        @size-change="handlePressSizeChange"
        @current-change="handlePressPageChange"
        :current-page.sync="pressPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pressSize"
        :total="totalPagePress"
        layout="total, sizes, prev, pager, next, jumper"></el-pagination>
    </div>

    <DialogJustForm
      ref="edit-dialog"
      v-if="!!dialogConfigs"
      :dialog-visible.sync="dialogVisible"
      :configs="dialogConfigs"
      @refreshDataList="getList" />
    <!-- :bom-code="dialogBomCode" -->

    <Overlay v-if="overlayVisible" />
  </div>
</template>

<script>
import BaseListTable from "@/components/BaseListTable.vue";
import BaseSearchForm from "@/components/BaseSearchForm.vue";
import DialogJustForm from "./edit-dialog.vue";
import Overlay from "@/components/Overlay.vue";

import moment from "moment";

export default {
  name: "ListViewWithHead",
  components: { BaseSearchForm, BaseListTable, DialogJustForm, Overlay },
  props: {
    tableConfig: {
      type: Object,
      default: () => ({
        /** 列配置, 即 props **/ column: [],
        /** 表格整体配置 */ table: undefined,
      }),
    },
    pressTableConfig: {
      type: Object,
      default: () => ({
        /** 列配置, 即 props **/ column: [],
        /** 表格整体配置 */ table: undefined,
      }),
    },
    headConfig: {
      type: Object,
      default: () => ({}),
    },
    /** 请求page接口的时候有些字段是必填的，没有会报500，把相关字段名传入这个prop: */
    listQueryExtra: {
      type: Array,
      default: () => ["key"],
    },
    initDataWhenLoad: { type: Boolean, default: true },
    /** dialog configs 或许可以从 tableConfig 计算出来 computed... */
    dialogConfigs: {
      type: Object,
      default: () => null,
    },
  },
  activated() {
    this.refreshLayoutKey = this.layoutTable();
  },
  data() {
    return {
      dialogVisible: false,
      topBtnConfig: null,
      totalPage: 100,
      page: 1,
      size: 20, // 默认20
      dataList: [],
      totalPagePress: 100,
      pressPage: 1,
      pressSize: 20, // 默认20
      pressDataList: [],
      tableLoading: false,
      refreshLayoutKey: null,
      pressTableLoading: false,
      refreshLayoutKeyPress: null,
      dialogBomCode: "",
      overlayVisible: false,
      cachedSearchCondition: {},
    };
  },
  inject: ["urls"],
  mounted() {
    this.initDataWhenLoad && this.getList();
    this.initDataWhenLoad && this.getList(null, "press");
  },
  methods: {
    /** 获取 列表数据 */
    getList(queryParams, type = "blender") {
      if (!type || type === "blender") this.tableLoading = true;
      if (type === "press") this.pressTableLoading = true;

      let page = type === "blender" ? this.page : this.pressPage;
      let size = type === "blender" ? this.size : this.pressSize;

      const params = queryParams
        ? { ...queryParams, page, limit: size }
        : {
            page,
            limit: 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];
            });
          }
        });
      }

      let url = type === "blender" ? this.urls.page : this.urls.pressPage;

      this.$http[this.urls.pageIsPostApi ? "post" : "get"](
        url,
        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) {
              if (type === "blender") {
                this.dataList = res.data.list;
                this.totalPage = res.data.total;
              } else if (type === "press") {
                this.pressDataList = res.data.list;
                this.totalPagePress = res.data.total;
              }
            }
          } else {
            this.$message({
              message: `${res.code}: ${res.msg}`,
              type: "error",
              duration: 2000,
            });
          }
          if (type === "blender") this.tableLoading = false;
          else this.pressTableLoading = false;
        })
        .catch((err) => {
          this.$message({
            message: `${err}`,
            type: "error",
            duration: 2000,
          });
          if (type === "blender") this.tableLoading = false;
          else this.pressTableLoading = false;
        });
    },

    layoutTable() {
      return Math.random();
    },

    handleOperatePress({ type, data, toRouter }) {
      console.log("payload", type, data);
      switch (type) {
        case "detach": {
          // 下发订单
          this.$confirm(`确定下发订单吗?`, "提示", {
            confirmButtonText: "确认",
            cancelButtonText: "我再想想",
            type: "warning",
          }).then(() => {
            this.overlayVisible = true;
            return this.$http
              .post(this.urls.pressDetach, data /* { id: data } */, {
                headers: { "Content-Type": "application/json" },
              })
              .then(({ data: res }) => {
                this.overlayVisible = false;
                if (res.code === 0) {
                  this.$message({
                    message: `下发成功`,
                    type: "success",
                    duration: 1500,
                    onClose: () => {
                      this.getList(this.cachedSearchCondition, "press");
                    },
                  });
                } else {
                  this.$message({
                    message: `${res.code}: ${res.msg}`,
                    type: "error",
                    duration: 1500,
                  });
                }
              });
          });
        }
      }
    },

    /** 处理 表格操作 */
    handleOperate({ type, data, toRouter }) {
      console.log("payload", type, data);
      // 编辑、删除、跳转路由、打开弹窗（动态component）都可以在配置里加上 url
      // payload: { type: string, data: string | number | object }
      switch (type) {
        case "delete": {
          let hintMsg = "name" in data ? `确定要删除记录 "${data.name}" 吗?` : "确定删除该记录?";

          let currenPageListLength = this.dataList.length;
          // 确认是否删除
          return this.$confirm(hintMsg, "提示", {
            confirmButtonText: "确认",
            cancelButtonText: "我再想想",
            type: "warning",
          })
            .then(() => {
              // this.$http.delete(this.urls.base + `/${data}`).then((res) => {
              this.$http({
                url: this.urls.base,
                method: "DELETE",
                data: [`${data.id}`],
              }).then(({ data: res }) => {
                if (res.code === 0) {
                  this.$message.success("删除成功!");

                  // this.page = 1;
                  // this.size = 10;
                  if (currenPageListLength == 1) this.page = this.page > 1 ? this.page - 1 : 1;
                  this.getList();
                } else {
                  this.$message({
                    message: `${res.code}: ${res.msg}`,
                    type: "error",
                    duration: 1500,
                  });
                }
              });
            })
            .catch((err) => {});
        }
        case "edit": {
          this.openDialog(data); /** data is ==> id */
          break;
        }
        case "view":
        case "view-detail-action": {
          this.openDialog(data, true);
          break;
        }
        case "view-batch": {
          this.$router.push({
            name: toRouter,
            query: {
              id: data, // 混料订单id
            },
          });
          break;
        }
        case "detach":
        case "pause-blender":
        case "start-blender": {
          // 下发订单
          this.$confirm(
            `确定${type === "detach" ? "下发" : type === "pause-blender" ? "暂停" : "开始"}该订单吗?`,
            "提示",
            {
              confirmButtonText: "确认",
              cancelButtonText: "我再想想",
              type: "warning",
            }
          ).then(() => {
            this.overlayVisible = true;
            const realUrl =
              type === "detach"
                ? this.urls.detach
                : type === "pause-blender"
                ? this.urls.pauseBlender
                : this.urls.startBlender;
            return this.$http
              .post(realUrl, data /* { id: data } */, { headers: { "Content-Type": "application/json" } })
              .then(({ data: res }) => {
                if (res.code === 0) {
                  this.$message({
                    message: `${
                      type === "detach" ? "下发" : type === "pause-blender" ? "暂停" : "开始"
                    }成功`,
                    type: "success",
                    duration: 1500,
                    onClose: () => {
                      this.getList();
                    },
                  });
                } else {
                  this.$message({
                    message: `${res.code}: ${res.msg}`,
                    type: "error",
                    duration: 1500,
                  });
                }
                this.overlayVisible = false;
              });
          });
        }
      }
    },

    handleBtnClick({ btnName, payload }) {
      console.log("[search] form handleBtnClick", btnName, payload);
      switch (btnName) {
        case "新增":
          this.openDialog();
          break;
        case "查询": {
          /** 处理 payload 里的数据 */
          if (typeof payload === "object") {
            // BaseSearchForm 给这个组件传递了数据
            Object.assign(this.cachedSearchCondition, payload);
            if ("timerange" in payload) {
              if (!!payload.timerange) {
                const [startTime, endTime] = payload["timerange"];
                this.cachedSearchCondition.startTime = moment(startTime).format("YYYY-MM-DDTHH:mm:ss");
                this.cachedSearchCondition.endTime = moment(endTime).format("YYYY-MM-DDTHH:mm:ss");
              } else {
                delete this.cachedSearchCondition.startTime;
                delete this.cachedSearchCondition.endTime;
              }
              delete this.cachedSearchCondition.timerange;
            }
          }

          /** 处理 listQueryExtra 里的数据 */
          this.listQueryExtra?.map((cond) => {
            if (typeof cond === "string") {
              if (!!payload[cond]) {
                this.cachedSearchCondition[cond] = payload[cond];
              } else {
                this.cachedSearchCondition[cond] = "";
              }
            } else if (typeof cond === "object") {
              Object.keys(cond).forEach((key) => {
                this.cachedSearchCondition[key] = cond[key];
              });
            }
          });
          console.log("查询", this.cachedSearchCondition);
          this.getList(this.cachedSearchCondition);
          this.getList(this.cachedSearchCondition, "press");
          break;
        }
      }
    },

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

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

    /** 导航器的操作 */
    handlePressSizeChange(val) {
      // val 是新值
      this.pressPage = 1;
      this.pressSize = val;
      this.getList(this.cachedSearchCondition, "press");
    },

    handlePressPageChange(val) {
      // val 是新值
      this.getList(this.cachedSearchCondition, "press");
    },

    /** 打开对话框 */
    openDialog(row_data) {
      this.dialogVisible = true;

      // if ("bomCode" in row_data) {
      //   const { bomCode } = row_data;
      //   this.dialogBomCode = bomCode;
      // }

      this.$nextTick(() => {
        this.$refs["edit-dialog"].init(row_data);
      });
    },
  },
};
</script>

<style scoped>
.list-view-with-head {
  background: white;
  /* height: 100%; */
  min-height: inherit;
  border-radius: 6px;
  padding: 16px;
  box-shadow: 0 0 1.125px 0.125px rgba(0, 0, 0, 0.125);
}
</style>
