<template>
  <div>
    <mega-table-query-filter
      :query-param="queryParam"
      :query-param-item="queryParamItem"
      @query="handleQuery"
      @reset="handleReset"
    />
    <MomTable
      :key="tableKey"
      ref="MomTable"
      row-key="id"
      :columns="columns"
      :data-source="dataSource"
      :total="total"
      :page.sync="page"
      :show-util-operator="false"
      :init-call="false"
      :auto-adaptive-width="false"
      :mega-extend="{
        rowIndex: false,
        rowAction: false,
      }"
      @search="search"
    >
      <div slot="toolbar" class="button-top-table">
        <a-tabs
          v-model="curStatus"
          default-active-key="prod"
          @change="callback"
        >
          <a-tab-pane
            v-for="item in tabList"
            :key="item.status"
            :tab="item.name"
          ></a-tab-pane>
        </a-tabs>
      </div>
      <div slot="statusName" slot-scope="text, record">
        <div
          class="status-text"
          :style="{
            color: record.statusColor,
            border: `1px solid ${record.statusColor}`,
          }"
        >
          <div
            class="status-bg"
            :style="{
              background: record.statusColor,
            }"
          ></div>
          {{ text }}
        </div>
      </div>
    </MomTable>
  </div>
</template>

<script>
import moment from "moment";
import ApiConstant from "@/api/ApiConstant";

export default {
  data() {
    return {
      loading: false, // 表格loading
      confirmLoading: false,
      tableKey: new Date().getTime(),
      tabList: [
        { name: "产量", status: "prod" },
        { name: "机况", status: "status" },
        { name: "参数", status: "param" },
        { name: "能源", status: "power" },
      ],
      // 查询的表单的配置项
      queryParam: {
        dateArr: "",
        timeArr: "",
        eqpId: "",
      },
      queryParamItem: {
        lineId: {
          itemType: "select",
          label: () => this.$t("PRODUCTION_LINE"),
          mode: "multiple",
          labelWidth: 60,
          options: [],
          optionsProps: {
            label: "lineName",
            value: "id",
          },
        },
        dateArr: {
          itemType: "date",
          label: () => this.$t("DATE"),
        },
        timeArr: {
          itemType: "custom",
          label: () => `${this.$t("TIME")}`,
          customRender: () => {
            return (
              <div>
                <a-time-picker v-model={this.startTime} />
                <span>~</span>
                <a-time-picker
                  disabledHours={this.getDisabledHours}
                  v-model={this.endTime}
                />
              </div>
            );
          },
        },
        eqpId: {
          itemType: "custom",
          label: () => `${this.$t("EQP_NAME")}`,
          customRender: () => {
            return (
              <SelectSearch
                ref={"SelectSearch"}
                show-multiple={false}
                option-label={"eqpName"}
                get-default={false}
                onDefaultValue={this.onGetEqpDefaultValue}
                requestApi={"/api/epm/eam/eqp/search"}
                onChange={this.onSelectSearchChange}
              />
            );
          },
        },
        fabId: {
          itemType: "select",
          label: () => this.$t("FAC_SHOP"),
          mode: "multiple",
          labelWidth: 60,
          options: [],
          optionsProps: {
            label: "fabName",
            value: "id",
          },
          on: {
            change: () => {
              if (this.queryParam.fabId && this.queryParam.fabId.length > 0) {
                this.getArea();
              }
            },
          },
        },
        areaId: {
          itemType: "select",
          label: () => this.$t("FAC_AREA"),
          mode: "multiple",
          labelWidth: 60,
          options: [],
          optionsProps: {
            label: "areaName",
            value: "id",
          },
          on: {
            change: () => {
              if (this.queryParam.areaId && this.queryParam.areaId.length > 0) {
                this.getLine();
              }
            },
          },
        },
      },
      eqpDefaultValue: null,
      fabIdList: [],
      areaIdList: [],
      columns: [],
      params: {
        page: 1,
        size: 10,
      },
      columnsA: [
        {
          dataIndex: "eqpCode", // 设备编码
          title: () => this.$t("EPMS_EQP_CODE"),
          sorter: false,
          ellipsis: true,
          width: 200,
        },
        {
          dataIndex: "eqpName", // 设备名称
          title: () => this.$t("EQP_NAME"),
          sorter: false,
          ellipsis: true,
          width: 400,
        },
        {
          dataIndex: "totalOutput", // 实际总产量
          title: () => this.$t("ACTUAL_TOTAL"),
          sorter: true,
          ellipsis: true,
          width: 200,
        },
        {
          dataIndex: "goodOutput", // 良品产出
          title: () => this.$t("GOOD_PRODUCT_OUTPUT"),
          sorter: true,
          ellipsis: true,
          width: 200,
        },
        {
          dataIndex: "ngOutput", // 不良品产出
          title: () => this.$t("DEFECTIVE_PRODUCT_OUTPUT"),
          sorter: true,
          ellipsis: true,
          width: 200,
        },
        {
          dataIndex: "reportTime", // 上报时间
          title: () => this.$t("REPORTING_TIME"),
          sorter: true,
          ellipsis: true,
        },
      ],
      columnsB: [
        {
          dataIndex: "eqpCode", // 设备编码
          title: () => this.$t("EPMS_EQP_CODE"),
          sorter: false,
          ellipsis: true,
          width: 200,
        },
        {
          dataIndex: "eqpName", // 设备名称
          title: () => this.$t("EQP_NAME"),
          sorter: false,
          ellipsis: true,
          width: 400,
        },
        {
          dataIndex: "statusName", // 状态
          title: () => this.$t("STATUS"),
          sorter: true,
          ellipsis: true,
          scopedSlots: { customRender: "statusName" },
          width: 400,
        },
        {
          dataIndex: "reportTime", // 上报时间
          title: () => this.$t("REPORTING_TIME"),
          sorter: true,
          ellipsis: true,
        },
      ],
      columnsC: [
        {
          dataIndex: "eqpCode", // 设备编码
          title: () => this.$t("EPMS_EQP_CODE"),
          sorter: false,
          ellipsis: true,
          width: 200,
        },
        {
          dataIndex: "eqpName", // 设备名称
          title: () => this.$t("EQP_NAME"),
          sorter: false,
          ellipsis: true,
          width: 400,
        },
        {
          dataIndex: "paramKey", // 参数编码
          title: () => this.$t("EPMS_PARAMETER_CODE"),
          sorter: false,
          ellipsis: true,
          width: 200,
        },
        {
          dataIndex: "paramName", // 参数名称
          title: () => this.$t("PARAMETER_NAME"),
          sorter: false,
          ellipsis: true,
          width: 200,
        },
        {
          dataIndex: "paramValue", // 参数值
          title: () => this.$t("PARAMETER_VALUE"),
          sorter: false,
          ellipsis: true,
          width: 200,
        },
        {
          dataIndex: "reportTime", // 上报时间
          title: () => this.$t("REPORTING_TIME"),
          sorter: true,
          ellipsis: true,
        },
      ],
      columnsD: [
        {
          dataIndex: "eqpCode", // 设备编码
          title: () => this.$t("EPMS_EQP_CODE"),
          sorter: false,
          ellipsis: true,
        },
        {
          dataIndex: "eqpName", // 设备名称
          title: () => this.$t("EQP_NAME"),
          sorter: false,
          ellipsis: true,
        },
        {
          dataIndex: "paramKey", // 参数编码
          title: () => this.$t("EPMS_PARAMETER_CODE"),
          sorter: false,
          ellipsis: true,
        },
        {
          dataIndex: "paramName", // 参数名称
          title: () => this.$t("PARAMETER_NAME"),
          sorter: false,
          ellipsis: true,
        },
        {
          dataIndex: "paramValue", // 参数值
          title: () => this.$t("PARAMETER_VALUE"),
          sorter: false,
          ellipsis: true,
        },
        {
          dataIndex: "reportTime", // 上报时间
          title: () => this.$t("REPORTING_TIME"),
          sorter: true,
          ellipsis: true,
        },
      ],
      total: 0,
      page: 1,
      dataSource: [],
      curStatus: "prod",
      startTime: "",
      endTime: "",
    };
  },
  created() {
    this.columns = [...this.columnsA];
    this.queryParam.dateArr = moment(new Date()).format("YYYY-MM-DD");
    this.startTime = moment(`${this.queryParam.dateArr} 00:00:00`); //
    this.endTime = moment(`${this.queryParam.dateArr} 23:59:59`);
  },
  mounted() {
    this.init();
    // this.search();
  },
  methods: {
    init() {
      return Promise.all([
        this.$axios.get(
          `${ApiConstant.PREFIX_CORE}/api/mdm/fac-fab/list-by-factory-code`
        ),
      ]).then(([facRes]) => {
        const { data } = facRes.data;
        this.queryParamItem.fabId.options = facRes.data.data || [];
        if (data && data.length > 0) {
          data.forEach((item) => {
            this.fabIdList.push(item.id);
          });
          this.getAreaByFab();
        }
      });
    },
    callback(e) {
      this.curStatus = e;
      let columns = [];
      if (this.curStatus === "prod") {
        columns = [...this.columnsA];
      } else if (this.curStatus === "status") {
        columns = [...this.columnsB];
      } else if (this.curStatus === "param") {
        columns = [...this.columnsC];
      } else if (this.curStatus === "power") {
        columns = [...this.columnsD];
      }
      this.columns = columns;
      this.tableKey = new Date().getTime();
      this.search();
    },
    onSelectSearchChange(e, info) {
      this.queryParam.eqpId = e;
    },
    onGetEqpDefaultValue(e) {
      this.eqpDefaultValue = e.id;
      this.search();
    },
    // 获取区域
    getAreaByFab() {
      const params = {
        fabIdList: this.fabIdList.join(","),
      };
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/mdm/fac-area/list`, { params })
        .then((res) => {
          const { data } = res.data;
          if (data && data.length > 0) {
            this.queryParamItem.areaId.options = res.data.data || [];
            data.forEach((item) => {
              this.areaIdList.push(item.id);
            });
            this.getLineByArea();
          }
        });
    },
    // 获取产线
    getLineByArea() {
      const params = {
        areaIdList: this.areaIdList.join(","),
      };
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/mdm/fac-line/list-by-area-code`, {
          params,
        })
        .then((res) => {
          this.queryParamItem.lineId.options = res.data.data || [];
        });
    },
    // 获取区域
    getArea() {
      const params = {
        fabIdList: this.queryParam.fabId.join(","),
      };
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/mdm/fac-area/list`, { params })
        .then((res) => {
          this.queryParamItem.areaId.options = res.data.data || [];
        });
    },
    // 获取产线
    getLine() {
      const params = {
        areaIdList: this.queryParam.areaId.join(","),
      };
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/mdm/fac-line/list-by-area-code`, {
          params,
        })
        .then((res) => {
          this.queryParamItem.lineId.options = res.data.data || [];
        });
    },
    formatData(data, status) {
      const result = data.find((item) => item.value === status.toString());
      return result ? result.label : "";
    },
    // 查询
    handleQuery() {
      this.page = 1;
      this.$refs.MomTable?.query();
    },
    // 重置
    handleReset() {
      this.$refs.SelectSearch?.reset();
      // this.queryParam.fabId = [];
      // this.queryParam.areaId = [];
      // this.queryParam.lineId = [];
      // this.queryParamItem.fabId.options = [];
      // this.queryParamItem.areaId.options = [];
      // this.queryParamItem.lineId.options = [];
      this.queryParam.eqpId = "";
      this.params.page = 1;
      this.queryParam.dateArr = moment(new Date()).format("YYYY-MM-DD");
      this.startTime = moment(`${this.queryParam.dateArr} 00:00:00`); //
      this.endTime = moment(`${this.queryParam.dateArr} 23:59:59`);
      this.init();
      this.dataSource = [];
    },
    search() {
      this.selectedRowKeys = [];
      this.selectedRows = [];
      this.loading = true;
      let url = "";
      if (this.curStatus === "prod") {
        url = "/api/epm/iot/data-collect-log/search-prod";
      } else if (this.curStatus === "status") {
        url = "/api/epm/iot/data-collect-log/search-status";
      } else if (this.curStatus === "param") {
        url = "/api/epm/iot/data-collect-log/search-param";
      } else if (this.curStatus === "power") {
        url = "/api/epm/iot/data-collect-log/search-power";
      }
      const { page, size } = this.params;
      const { eqpId, dateArr, sortColumn, sortRule } = this.queryParam;
      if (
        (!eqpId && !this.eqpDefaultValue) ||
        !this.endTime ||
        !this.startTime ||
        !this.queryParam.dateArr
      )
        return;
      const startTime = dateArr
        ? `${moment(new Date(dateArr)).format("YYYY-MM-DD")} ${moment(
            this.startTime
          ).format("HH:mm:ss")}`
        : "";
      const endTime = dateArr
        ? `${moment(new Date(dateArr)).format("YYYY-MM-DD")} ${moment(
            this.endTime
          ).format("HH:mm:ss")}`
        : "";
      const params1 = {
        page,
        size,
        sortColumn,
        sortRule,
        // fabIdList: fabId.length > 0 ? fabId.join(",") : "",
        // areaIdList: areaId.length > 0 ? areaId.join(",") : "",
        // lineIdList: lineId.length > 0 ? lineId.join(",") : "",
        eqpId: eqpId || this.eqpDefaultValue,
        startTime,
        endTime,
      };
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}${url}`, {
          params: { ...params1 },
        })
        .then((res) => {
          this.dataSource = res.data.data.records;
          this.total = res.data.data.total;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
  },
};
</script>
<style lang="less" scoped>
/deep/ .el-upload__input {
  display: none !important;
}
/deep/ .error-type .ant-form-item-children {
  display: flex;
}
.tips-icon {
  width: 50px;
  text-align: center;
  font-size: 20px;
  color: #ff9041;
}
.status-bg {
  position: absolute;
  width: 100%;
  height: 100%;
  opacity: 0.2;
  left: 0;
  top: 0;
  border-radius: 4px;
}
.status-text {
  padding: 4px 24px;
  position: relative;
  display: inline-block;
  z-index: 1;
  border-radius: 4px;
}
</style>
