<template>
  <LocalQuery @click="handleNodeClick">
    <MomTable
      ref="MomTable"
      row-key="id"
      :query-param="queryParam"
      :query-param-item="queryParamItem"
      :columns="columns"
      :data-source="dataSource"
      :total="total"
      :page.sync="page"
      :show-util-operator="true"
      :action-buttons="tableAction"
      :row-class-name="isRedRow"
      @search="search"
      @reset="handleReset"
    >
      <div slot="statusDuration" slot-scope="text, record">
        <span
          class="cursor-pointer"
          :class="{ downRedFlag: record.downRedFlag === 'Y' }"
          >{{ record.statusDuration }}</span
        >
      </div>
      <div slot="eqpCode" slot-scope="text, record">
        <span class="eqpCodeSty" @click.stop="handleItem(record)">{{
          record.eqpCode
        }}</span>
      </div>
      <template slot="status" slot-scope="text, record">
        <span class="status-box" :class="text">{{
          formatData(orderStatusList, record.status)
        }}</span>
      </template>
    </MomTable>
    <MegaDrawer
      width="520"
      :is-show-footer="false"
      :title="$t('EPMS_REPAIR_PROGRESS')"
      :visible="drawerVisible"
      @close="handleCancel"
    >
      <div slot="main">
        <RepairProgress
          :eqp-data="eqpData"
          :order-status-list="orderStatusList"
        ></RepairProgress>
      </div>
      <template slot="footer">
        <MegaButton @click="drawerVisible = false">{{
          $t("CANCEL")
        }}</MegaButton>
      </template>
    </MegaDrawer>
  </LocalQuery>
</template>

<script>
import {
  Drawer as MegaDrawer,
  Button as MegaButton,
} from "@mega-design/ui-vue";
import ApiConstant from "@/api/ApiConstant";
import RepairProgress from "@/components/repairProgress";
import LocalQuery from "@/components/epms/LocalQuery";
import SelectSearch from "@/components/epms/SelectSearch";

export default {
  components: {
    MegaDrawer,
    MegaButton,
    RepairProgress,
    LocalQuery,
  },
  data() {
    return {
      tableAction: [
        // 待确认
        (h, { record }) =>
          this.hasAuth("EPMS:REPAIR_EQP:CONFIRM") &&
          record.status === "WAIT_CONFIRM" && (
            <a-button
              title={this.$t("EPMS_RESULT_CONFIRM")}
              type="link"
              onClick={() => this.eqpConfirm(record)}
            >
              {this.$t("EPMS_RESULT_CONFIRM")}
            </a-button>
          ),
        // 待维修
        (h, { record }) =>
          this.hasAuth("EPMS:REPAIR_EQP:FIXED") &&
          record.status === "WAIT_REPAIR" &&
          record.redFlag === "Y" && (
            <span
              class="cursor-pointer"
              style="color: #FF0000"
              title={this.$t("EPMS_ANEW") + this.$t("EPMS_FIX")}
              onClick={() => this.eqpFix(record)}
            >
              {this.$t("EPMS_ANEW") + this.$t("EPMS_FIX")}
            </span>
          ),
        (h, { record }) =>
          (this.hasAuth("EPMS:REPAIR_EQP:FIXED") && !record.redFlag) ||
          record.redFlag === "" ||
          (record.status === "WAIT_REPAIR" && record.redFlag === "N" && (
            <a-button
              title={this.$t("EPMS_FIX")}
              type="link"
              onClick={() => this.eqpFix(record)}
            >
              {this.$t("EPMS_FIX")}
            </a-button>
          )),
        (h, { record }) =>
          this.hasAuth("EPMS:REPAIR_EQP:TRANSFER_ORDER") &&
          record.status === "WAIT_REPAIR" && (
            <a-button
              title={this.$t("TRANSFER_ORDER")}
              type="link"
              onClick={() => this.handleTransferOrder(record)}
            >
              {this.$t("TRANSFER_ORDER")}
            </a-button>
          ),
        // 待派工
        (h, { record }) =>
          this.hasAuth("EPMS:DISPATCH:DISPATCH") &&
          record.status === "WAIT_ASSIGN" && (
            <a-button
              title={this.$t("APP_DISPATCH_MGMT")}
              type="link"
              onClick={() => this.dispatch(record)}
            >
              {this.$t("APP_DISPATCH_MGMT")}
            </a-button>
          ),
        // 待接单
        (h, { record }) =>
          this.hasAuth("EPMS:REPAIR_EQP:RECEIVE") &&
          record.status === "WAIT_ACCEPT" && (
            <a-button
              class={"text_decoration"}
              title={this.$t("EPMS_ORDER_RECEIVING")}
              type="link"
              onClick={() => this.receive(record)}
            >
              {this.$t("EPMS_ORDER_RECEIVING")}
            </a-button>
          ),
        // 待叫修
        (h, { record }) =>
          this.hasAuth("EPMS:FAULT_REPAIR:REPAIR") &&
          record.status === "WAIT_CALL" &&
          record.canRepair === "Y" && (
            <a-button
              title={this.$t("EPMS_CALL_REPAIR")}
              type="link"
              onClick={() => this.handleRepair(record)}
            >
              {this.$t("EPMS_CALL_REPAIR")}
            </a-button>
          ),
      ],
      loading: false, // 表格loading
      // 查询的表单的配置项
      queryParam: {
        repairTicketCode: "",
        eqpCodeLike: "",
        eqpIdList: "",
      },
      columns: [
        {
          dataIndex: "eqpCode", // 设备编码
          title: () => this.$t("EPMS_EQP_CODE"),
          width: 180,
          ellipsis: true,
          scopedSlots: { customRender: "eqpCode" },
        },
        {
          dataIndex: "eqpName", // 设备名称
          sorter: false,
          ellipsis: true,
          title: () => this.$t("EQP_NAME"),
          width: 180,
        },
        {
          dataIndex: "location", // 位置
          title: () => this.$t("POSITION"),
          ellipsis: true,
          width: 350,
        },
        {
          dataIndex: "statusStartTime", // 宕机开始时间
          ellipsis: true,
          title: () => `${this.$t("DOWNTIME")}${this.$t("START_TIME")}`,
          width: 180,
        },
        {
          dataIndex: "statusDuration", // 宕机持续时间
          ellipsis: true,
          title: () => `${this.$t("DOWNTIME")}${this.$t("DURATION")}`,
          width: 150,
          scopedSlots: { customRender: "statusDuration" },
        },
        {
          dataIndex: "repairTicketCode", // 工单编码
          ellipsis: true,
          title: () => this.$t("EPMS_WORK_ORDER_CODE"),
          width: 200,
        },
        {
          dataIndex: "status", // 叫修工单状态
          title: () => this.$t("REPAIR_ORDER_STATUS"),
          ellipsis: true,
          width: 150,
          scopedSlots: { customRender: "status" },
        },
        {
          dataIndex: "callUser", // 申请人
          ellipsis: true,
          sorter: false,
          title: () => this.$t("APPLICANT"),
          width: 100,
        },
        {
          dataIndex: "repairUser", // 维修人
          ellipsis: true,
          sorter: false,
          title: () => this.$t("EPMS_REPAIR_PERSONNEL"),
          width: 100,
        },
        {
          dataIndex: "repairTime", // 维修时间
          ellipsis: true,
          title: () => this.$t("APPLICATION_TIME"),
          width: 180,
        },
        {
          dataIndex: "repairDuration", // 维修耗时
          ellipsis: true,
          title: () => this.$t("REPAIR_TIME_CONSUM"),
          width: 180,
        },
      ],
      total: 0,
      page: 1,
      orderStatusList: [],
      // selectedRowKeys: [], // 选中行 key 数据
      // selectedRows: [], // 选中行 数据
      dataSource: [],
      drawerVisible: false,
      eqpData: {
        repairTicketLogList: [],
      },
      repairTicketLogList: [],
      // 左侧树
      fabId: "",
      areaId: "",
      lineId: "",
      isReset: false, // 是否重置SelectSearch组件value
    };
  },
  computed: {
    // 表格搜索配置
    queryParamItem() {
      return this.$observable("queryParamItem", {
        repairTicketCode: {
          label: () => this.$t("EPMS_WORK_ORDER_CODE"),
          placeholder: () => this.$t("ENTER_WORKORDER_CODE_KEYWORD"),
        },
        eqpCodeLike: {
          label: () => this.$t("EPMS_EQP_CODE"),
          placeholder: () => this.$t("ENTER_EQP_CODE_KEYWORD"),
        },
        eqpIdList: {
          itemType: "custom",
          label: () => this.$t("EQP_NAME"),
          customRender: () => {
            return (
              <SelectSearch
                isReset={this.isReset}
                queryListKey="eqpName"
                requestApi={"/api/epm/eam/eqp/search"}
                option-label={"eqpName"}
                placeholder={this.$t("PLACESELECT") + this.$t("EQP_NAME")}
                needDisabled={false}
                onChange={this.onSelectSearchChange}
              ></SelectSearch>
            );
          },
        },
      });
    },
    // 多选
    // rowSelection() {
    //   return {
    //     selectedRowKeys: this.selectedRowKeys,
    //     onChange: (selectedRowKeys, selectedRows) => {
    //       this.selectedRowKeys = selectedRowKeys;
    //       if (this.selectedRowKeys.length) {
    //         this.selectedRows = uniqBy(this.selectedRows.concat(selectedRows));
    //       } else {
    //         this.selectedRows = selectedRows;
    //       }
    //     },
    //   };
    // },
  },
  created() {
    const aa = ["c", "b", "a", "a"];
    this.init();
  },
  methods: {
    onSelectSearchChange(e, list, chooseList) {
      this.isReset = false;
      this.queryParam.eqpIdList = list.join(",");
    },
    isRedRow(record) {
      let tempStr = "cursor-pointer";
      if (record.redFlag === "Y") {
        tempStr += " redFlag";
      }
      return tempStr;
    },
    init() {
      // 工单状态字典
      this.$axios
        .get(
          `${ApiConstant.PREFIX_CORE}/api/sys/dict-data/DIC:EPM:REPAIR_STATUS`
        )
        .then((res) => {
          this.orderStatusList = res.data.data;
        }); // 是否
    },
    formatData(data, status) {
      const result = data.find((item) => item.value === status.toString());
      return result ? result.label : "";
    },
    handleReset() {
      this.isReset = true;
      this.$refs.MomTable?.search();
    },
    // 点击节点查询数据
    handleNodeClick(info) {
      this.fabId = info.fabId;
      this.areaId = info.areaId;
      this.lineId = info.lineId;
      this.$refs.MomTable?.query();
    },
    search(params) {
      const tempArr = [];
      const { fabId, areaId, lineId } = this;
      const { repairTicketCode } = this.queryParam;
      if (fabId) {
        tempArr.push("production-farm");
      }
      if (areaId) {
        tempArr.push("production-area");
      }
      if (lineId) {
        tempArr.push("production-line");
      }
      if (repairTicketCode) {
        tempArr.push("work-order");
      }
      if (tempArr.length > 0) {
        const sendData = {
          parentFuncKey: "ERM2040-condition",
          funcKeys: tempArr,
          type: "USE",
          clientCode: ApiConstant.clientCode,
        };
        this.handleFuncUseRate(sendData);
      }
      const data = {
        ...params,
        searchType: "ALL_OPERATOR", // 待维修
        fabIdList: fabId,
        areaIdList: areaId,
        lineIdList: lineId,
      };
      this.loading = true;
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/epm/erm/repair-ticket/search`, {
          params: data,
        })
        .then((res) => {
          this.dataSource = res.data.data.records;
          this.total = res.data.data.total;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    eqpConfirm({ id, eqpId }) {
      const params = {
        funcKeys: ["confirmation-results"],
        type: "JUMP",
        clientCode: ApiConstant.clientCode,
      };
      this.handleFuncUseRate(params);
      this.$router.push({
        path: "/eam/repair_management/fault_repair/result_confirm/confirm",
        query: {
          id,
          eqpId,
          from: "toDo",
        },
      });
    },
    eqpFix({ id, eqpId }) {
      const params = {
        funcKeys: ["trouble-shooting"],
        type: "JUMP",
        clientCode: ApiConstant.clientCode,
      };
      this.handleFuncUseRate(params);
      this.$router.push({
        path: "/eam/repair_management/fault_repair/eqp_repair/fixed",
        query: {
          id,
          eqpId,
          from: "toDo",
        },
      });
    },
    // 转单
    handleTransferOrder({ id, eqpId }) {
      const params = {
        funcKeys: ["trouble-shooting"],
        type: "JUMP",
        clientCode: ApiConstant.clientCode,
      };
      this.handleFuncUseRate(params);
      this.$router.push({
        path: "/eam/repair_management/fault_repair/eqp_repair/transfer_order",
        query: {
          id,
          eqpId,
          from: "toDo",
        },
      });
    },
    dispatch({ id }) {
      const params = {
        funcKeys: ["repair-order"],
        type: "JUMP",
        clientCode: ApiConstant.clientCode,
      };
      // this.handleFuncUseRate(params);
      this.$router.push({
        path: "/eam/repair_management/fault_repair/dispatch/dispatch",
        query: {
          id,
          from: "toDo",
        },
      });
    },
    receive({ id, eqpId }) {
      const params = {
        funcKeys: ["repair-order"],
        type: "JUMP",
        clientCode: ApiConstant.clientCode,
      };
      this.handleFuncUseRate(params);
      this.$router.push({
        path: "/eam/repair_management/fault_repair/order_receiving_management/receive",
        query: {
          id,
          eqpId,
          from: "toDo",
        },
      });
    },
    handleRepair({ eqpId }) {
      const params = {
        funcKeys: ["trouble-repair"],
        type: "JUMP",
        clientCode: ApiConstant.clientCode,
      };
      this.handleFuncUseRate(params);
      this.$router.push({
        path: "/eam/repair_management/fault_repair/fault_repair/repair",
        query: {
          id: eqpId,
          from: "toDo",
        },
      });
    },
    handleItem({ id }) {
      this.$axios
        .get(
          `${ApiConstant.PREFIX_CORE}/api/epm/erm/repair-ticket/repair-process/${id}`
        )
        .then((res) => {
          this.eqpData = { ...res?.data?.data };
        });
      this.drawerVisible = true;
    },
    handleCancel() {
      this.drawerVisible = false;
    },
    // 页面埋点
    handleFuncUseRate(data) {
      this.$axios
        .put(`${ApiConstant.PREFIX_CORE}/api/epm/eam/use`, data)
        .then(() => {});
    },
  },
};
</script>
<style lang="less" scoped>
@import "@/assets/css/fault_repair.less";
@import "@/assets/css/status_epms.less";
</style>
