<template>
  <div class="box-main">
    <LocalQuery @click="handleNodeClick">
      <MomTable
        ref="MomTable"
        row-key="id"
        :row-selection="rowSelection"
        :query-param="queryParam"
        :query-param-item="queryParamItem"
        :columns="columns"
        :data-source="dataSource"
        :total="total"
        :page.sync="page"
        :show-util-operator="true"
        :action-buttons="tableAction"
        :custom-row="customRow"
        :row-class-name="isRedRow"
        :mega-extend="{
          rowIndex: false,
        }"
        @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="toolbar" class="button-top-table">
          <a-button
            v-if="hasAuth('EPMS:DISPATCH:BATCH_DISPATCH')"
            :disabled="selectedRowKeys.length === 0"
            :class="{ btn_disabled: selectedRowKeys.length === 0 }"
            @click="handleBatchDispatch"
          >
            <i class="iconfont icon-paigong"></i>
            {{ $t("BATCH_DISPATCH") }}
          </a-button>
          <!-- <div class="table-top-text">
            * {{ $t("RECEIVE_ORDER_COUNT") }}：{{ total }}
          </div> -->
        </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>
    </LocalQuery>
    <MegaDrawer
      width="520"
      :is-show-footer="isBatchDispatch"
      :title="
        isBatchDispatch ? $t('BATCH_DISPATCH') : $t('EPMS_REPAIR_PROGRESS')
      "
      :visible="drawerVisible"
      @close="handleCancel"
    >
      <div v-if="!isBatchDispatch" slot="main">
        <div class="eqp_view_top flex items-center">
          <span>{{ $t("EQP_STATUS") }}</span>
          <div
            class="eqp_status flex items-center justify-center"
            :style="{
              background: `${eqpdata.statusColor}`,
            }"
          >
            {{ eqpdata.statusName }}
          </div>
        </div>
        <a-timeline>
          <a-timeline-item>
            <svg-icon
              slot="dot"
              icon-class="down_01"
              style="width: 20px; height: 20px"
            />
            <span class="timeline_title">{{ $t("DOWNTIME") }}</span>
            <div class="timeline_item">
              {{ $t("DOWNTIME") }}{{ $t("START_TIME") }}:
              {{ eqpdata.statusStartTime }}
            </div>
            <div class="timeline_item">
              {{ $t("DOWNTIME") }}{{ $t("DURATION") }}:
              {{ eqpdata.statusDuration }}
            </div>
            <div class="timeline_box"></div>
          </a-timeline-item>
          <a-timeline-item
            v-for="(item, index) in eqpdata.repairTicketLogList"
            :key="index"
          >
            <svg-icon
              slot="dot"
              :icon-class="
                eqpdata.repairTicketLogList.length === index + 1
                  ? item.repairTicketStatus + '_active'
                  : item.repairTicketStatus
              "
              style="width: 20px; height: 20px"
            />
            <span
              class="timeline_title"
              :class="{
                active: eqpdata.repairTicketLogList.length === index + 1,
              }"
              >{{ formatData(orderStatusList, item.repairTicketStatus) }}</span
            >
            <!-- 待结单 -->
            <div
              v-if="item.repairTicketStatus === 'WAIT_ACCEPT'"
              class="timeline_item"
            >
              <template v-if="item.operateType === 'SWITCH_OUT'">
                设备人员
                <span>{{ item.operateUser }}</span>
                已于
                <span>{{ item.operateTime }}</span>
                转单到
                <span>{{ item.nextOperateUser }}</span>
                ，请尽快接单
              </template>
              <template v-else-if="item.type === 'AUTO_CALL'">
                系统
                <span>{{ item.operateUser }}</span>
                已于
                <span>{{ item.operateTime }}</span>
                生成叫修工单，请尽快派单
              </template>
              <template v-else>
                设备人员
                <span>{{ item.operateUser }}</span>
                已于
                <span>{{ item.operateTime }}</span>
                生成叫修工单
              </template>
            </div>
            <!-- 待派工 -->
            <div
              v-if="item.repairTicketStatus === 'WAIT_ASSIGN'"
              class="timeline_item"
            >
              <template v-if="item.type === 'AUTO_CALL'">系统</template>
              <template v-else>
                申请人员
                <span>{{ item.operateUser }}</span>
              </template>
              已于
              <span>{{ item.operateTime }}</span>
              生成叫修工单，请尽快派单
            </div>
            <!-- 维修中 开始 -->
            <div
              v-if="item.repairTicketStatus === 'WAIT_REPAIR'"
              class="timeline_item"
            >
              设备人员
              <span>{{ item.operateUser }}</span>
              已于
              <span>{{ item.operateTime }}</span>
              <template v-if="item.operateType === 'ACCEPT'">
                接单，正在维修
              </template>
              <template v-else-if="item.operateType === 'EPMS_NO_PASS'"
                >确认驳回</template
              >
              <template v-else>开始维修设备</template>
            </div>
            <!-- 待确认 开始 -->
            <div
              v-if="item.repairTicketStatus === 'WAIT_CONFIRM'"
              class="timeline_item"
            >
              设备人员
              <span>{{ item.operateUser }}</span>
              已于
              <span>{{ item.operateTime }}</span>
              完成维修，请尽快确认
            </div>
            <!-- 待确认 开始 -->
            <div
              v-if="item.repairTicketStatus === 'FINISHED'"
              class="timeline_item"
            >
              设备人员
              <span>{{ item.operateUser }}</span>
              已于
              <span>{{ item.operateTime }}</span>
              <template v-if="item.operateType === 'REPAIR'">确认通过</template>
              <template v-else>完成维修</template>
            </div>
            <div class="timeline_box"></div>
          </a-timeline-item>
        </a-timeline>
      </div>
      <a-form-model
        v-else
        slot="main"
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
      >
        <a-form-model-item
          :label="$t('EPMS_REPAIR_PERSONNEL')"
          prop="planRepairUser"
          allow-clear
        >
          <SelectUser
            ref="selectRoleRef"
            v-model="form.planRepairUser"
            :multiple="false"
            :default-selected-rows="selectUser"
            show-key="name"
            style="position: relative"
            @confirm="getReturnData"
          />
        </a-form-model-item>
      </a-form-model>
      <template slot="footer">
        <MegaButton
          type="primary"
          :loading="confirmLoading"
          @click="handleSave"
          >{{ $t("SAVE") }}</MegaButton
        >
        <MegaButton @click="drawerVisible = false">{{
          $t("CANCEL")
        }}</MegaButton>
      </template>
    </MegaDrawer>
  </div>
</template>

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

export default {
  components: { MegaDrawer, MegaButton, SelectUser, LocalQuery },
  data() {
    return {
      loading: false, // 表格loading
      confirmLoading: false,
      tableAction: [
        (h, { record }) =>
          this.hasAuth("EPMS:DISPATCH:DISPATCH") && (
            <a-button
              title={this.$t("APP_DISPATCH_MGMT")}
              type="link"
              onClick={() => this.receive(record)}
            >
              {this.$t("APP_DISPATCH_MGMT")}
            </a-button>
          ),
      ],
      // 查询的表单的配置项
      queryParam: {
        repairTicketCode: "",
        eqpCodeLike: "",
        eqpIdList: "",
      },
      columns: [
        {
          dataIndex: "eqpCode", // 设备编码
          title: () => this.$t("EPMS_EQP_CODE"),
          ellipsis: true,
          width: 180,
          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", // 宕机持续时间
          title: () => `${this.$t("DOWNTIME")}${this.$t("DURATION")}`,
          ellipsis: true,
          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: "callTime", // 申请时间
          ellipsis: true,
          title: () => this.$t("APPLICATION_TIME"),
          width: 180,
        },
      ],
      total: 0,
      page: 1,
      orderStatusList: [],
      // selectedRowKeys: [], // 选中行 key 数据
      // selectedRows: [], // 选中行 数据
      dataSource: [],
      drawerVisible: false,
      eqpdata: {
        repairTicketLogList: [],
      },
      selectedRowKeys: [], // 选中行 key 数据
      selectedRows: [], // 选中行 数据
      form: {
        planRepairUser: "",
        repairTicketIdList: [],
      },
      // 当前树节点下的负责人
      selectUser: [
        {
          id: "",
          name: "",
          tel: "",
        },
      ],
      isBatchDispatch: false,
      // 左侧树
      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="id"
                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;
          }
        },
      };
    },
    rules() {
      return {
        planRepairUser: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
      };
    },
    // 多选
    // 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() {
    this.init();
  },
  methods: {
    onSelectSearchChange(e, list, chooseList) {
      this.isReset = false;
      this.queryParam.eqpIdList = list.join(",");
    },
    customRow(record) {
      return {
        on: {
          click: (event) => {
            this.receive(record);
          },
        },
      };
    },
    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: "ERM2020-condition",
          funcKeys: tempArr,
          type: "USE",
          clientCode: ApiConstant.clientCode,
        };
        // this.handleFuncUseRate(sendData);
      }
      const data = {
        ...params,
        searchType: "WAIT_ASSIGN", // 待派工
        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;
        });
    },
    receive({ 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,
        },
      });
    },
    handleBatchDispatch() {
      if (this.selectedRowKeys.length < 1) {
        this.$message.success(this.$t("SELECT_ONE_DATA"));
        return;
      }
      this.isBatchDispatch = true;
      this.drawerVisible = true;
    },
    handleItem({ id }) {
      this.isBatchDispatch = false;
      this.$axios
        .get(
          `${ApiConstant.PREFIX_CORE}/api/epm/erm/repair-ticket/repair-process/${id}`
        )
        .then((res) => {
          this.eqpdata = { ...res?.data?.data };
        });
      this.drawerVisible = true;
    },
    // 获取选择用户组件返回数据
    getReturnData(selectedRowKeys, selectedRows) {
      if (selectedRows.length > 0) {
        this.selectUser = selectedRows;
        this.form.planRepairUser = selectedRows[0]?.userName;
      }
    },
    // 保存
    handleSave() {
      this.form.repairTicketIdList = this.selectedRowKeys;
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.confirmLoading = true;
          this.$axios
            .put(
              `${ApiConstant.PREFIX_CORE}/api/epm/erm/repair-ticket/assign`,
              this.form
            )
            .then(() => {
              this.confirmLoading = false;
              this.$message.success(this.$t("SAVE_SUCCESS"));
              this.$refs.MomTable?.query();
              this.handleCancel();
            })
            .catch((e) => {
              this.confirmLoading = false;
            });
        }
      });
    },
    // 取消
    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";
.btn_disabled {
  color: rgba(0, 0, 0, 0.25) !important;
  background-color: #f5f5f5 !important;
  border-color: #d9d9d9 !important;
}
</style>
