<template>
  <div class="car-detail">
    <BaseListTable
      key="car-history-list"
      v-loading="tableLoading"
      :table-config="null"
      :column-config="tableConfig"
      :table-data="dataList"
      @operate-event="handleOperate"
      :refresh-layout-key="refreshLayoutKey" />

    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handlePageChange"
      :current-page.sync="listQuery.page"
      :page-sizes="[1, 5, 10, 20]"
      :page-size="listQuery.limit"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"></el-pagination>

    <DialogCarPayload
      ref="car-payload-dialog"
      v-if="!!carPayloadDialogConfigs"
      :dialog-visible.sync="carPayloadDialogVisible"
      :configs="carPayloadDialogConfigs" />
    <!-- @refreshDataList="getList" -->
  </div>
</template>

<script>
import BaseListTable from "../BaseListTable.vue";
import TableOperaionComponent from "@/components/noTemplateComponents/operationComponent";
// import StateSelect from '@/components/StateSelect.vue';
import { timeFilter } from "@/utils/filters";
import DialogCarPayload from "@/components/DialogCarPayload.vue";

export default {
  name: "CarDetailTag",
  components: { BaseListTable, DialogCarPayload },
  props: {
    orderId: {
      type: String,
      default: null,
    },
    tableLayout: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      dataList: [],
      tableConfig: [
        { type: "index", label: "序号" },
        // { prop: "createTime", label: "添加时间", filter: timeFilter },
        { prop: "code", label: "窑车号" },
        { prop: "stateDictValue", label: "状态" }, // , subcomponent: StateSelect },
        // { prop: "stateDictValue", label: "状态", filter: v => (v !== null && v !== undefined) ? ['没有数据', '正常', '判废', '过渡'][v] : '-' }, // subcomponent
        // { prop: "orderCode", label: "订单号" },
        { prop: "posCode", label: "位置" },
        { prop: "startTime", label: "开始时间", filter: timeFilter },
        { prop: "endTime", label: "结束时间", filter: timeFilter },
        {
          prop: "operations",
          name: "操作",
          fixed: "right",
          width: 90,
          subcomponent: TableOperaionComponent,
          options: [
            { name: "to-car-payload", label: "装载详情", icon: "shopping-cart-full" }, // or  el-icon-box
            // { name: "delete", label: "删除", icon: "delete", emitFull: true, promptField: "code" },
          ],
        },
      ],
      refreshLayoutKey: null,
      tableLoading: false,
      listQuery: {
        limit: 20,
        page: 1,
      },
      totalPage: 0,
      carPayloadDialogVisible: false,
      carPayloadDialogConfigs: {
        dialogWidth: "70%",
        carPayloadDialog: true,
        clickModalToClose: true,
        tableConfig: {
          table: null,
          column: [
            // 窑车的 装载详情
            { width: 56, type: "index", label: "序号" },
            { prop: "orderCode", label: "订单号" },
            { width: 80, prop: "orderCate", label: "订单子号" },
            { prop: "bomCode", label: "配方" },
            { prop: "shapeCode", label: "砖型" },
            { width: 80, prop: "qty", label: "订单数量" },
            { width: 72, prop: "goodqty", label: "合格数" },
            { width: 72, prop: "badqty", label: "废砖数" },
          ],
        },
      },
    };
  },
  watch: {
    orderId: {
      handler: function (val) {
        if (val) {
          console.log("get car list based on orderId: ", val);
          this.getAList(val);
        }
      },
      immediate: true,
    },
    tableLayout() {
      this.doLayout()
    }
  },
  // activated() {
  //   console.log("hhh");
  //   this.refreshLayoutKey = Math.random();
  // },
  methods: {
    doLayout() {
      this.refreshLayoutKey = Math.random();
    },

    handleOperate({ type, data }) {
      switch (type) {
        case "delete": {
          // 找到删除的 prompt 字段
          const deleteConfig = data.head?.options?.find((item) => item.name === "delete");
          let promptName = data.name ?? data.id;
          if (deleteConfig && "promptField" in deleteConfig) {
            promptName = data[deleteConfig.promptField];
          }
          // 确认是否删除
          return this.$confirm(`确定要删除记录 "${promptName}" 吗?`, "提示", {
            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,
                // data: [`${data.id}`],
                headers: {
                  "Content-Type": "application/json",
                },
              }).then(({ data: res }) => {
                if (res.code === 0) {
                  this.$message.success("删除成功!");

                  this.page = 1;
                  this.size = 10;
                  this.getList();
                } else {
                  this.$message({
                    message: `${res.code}: ${res.msg}`,
                    type: "error",
                    duration: 1500,
                  });
                }
              });
            })
            .catch((err) => {});
        }
        case "to-car-history": {
          return this.$router.push({
            name: "pms-carHistory",
            query: {
              code: data.code,
            },
          });
        }
        case "to-car-payload": {
          // open dialog instead of redirect to a new page
          this.openCarPayloadDialog(data);
        }
      }
    },

    openCarPayloadDialog(id) {
      this.carPayloadDialogVisible = true;
      this.$nextTick(() => {
        this.$refs["car-payload-dialog"].init(id);
      });
    },

    getAList(orderId) {
      console.log("geting car list, ", orderId);
      if (!orderId) orderId = this.orderId;

      this.tableLoading = true;
      this.$http.post("/pms/carHandle/pageHis", { ...this.listQuery, orderId }).then(({ data: res }) => {
        if (res.code === 0 && res.data) {
          if ("list" in res.data) {
            this.dataList = res.data.list;
            this.totalPage = res.data.total;
          } else console.log("没有res.data.list属性");
        } else {
          this.dataList.splice(0);
          this.totalPage = 0;
          this.$message({
            message: `${res.code}: ${res.msg}`,
            type: "error",
            duration: 1500,
          });
        }
        this.refreshLayoutKey = this.layoutTable();
        this.tableLoading = false;
      });
    },

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

    /** 导航器的操作 */
    handleSizeChange(newSize) {
      this.listQuery.page = 1;
      this.listQuery.limit = newSize;
      this.getAList();
    },

    handlePageChange(newPage) {
      this.getAList();
    },
  },
};
</script>

<style scoped></style>
