<template>
  <div class="ele-body">
    <el-card shadow="never" v-loading="loading">
      <workorder-search @search="reload"> </workorder-search>
      <!-- 数据表格 -->
      <ele-pro-table
        ref="table"
        :columns="columns"
        :datasource="datasource"
        cache-key="systemRoleTable"
      >
        <!-- 表头工具栏 -->
        <!-- <template v-slot:toolbar>
          <el-button
            size="small"
            type="primary"
            class="ele-btn-icon"
            @click="goDetail({ id: 1 })"
          >
            详情
          </el-button>
        </template> -->
        <template v-slot:code="{ row }"
          ><el-link type="primary" :underline="false" @click="goDetail(row)">
            {{ row.code }}
          </el-link></template
        >
        <!-- 操作列 -->
        <template v-slot:action="{ row }">
          <el-link
            v-if="row.orderStatus !== 3 && row.orderStatus !== 4"
            type="primary"
            :underline="false"
            icon="el-icon-truck"
            @click="addSpareItems(row)"
          >
            申请备品备件
          </el-link>
          <el-link
            v-if="row.orderStatus !== 3 && row.orderStatus !== 4"
            type="primary"
            :underline="false"
            icon="el-icon-edit"
            @click="toReport(row)"
          >
            报工
          </el-link>
          <el-link
            v-if="row.orderStatus !== 3 && row.orderStatus !== 4"
            type="primary"
            :underline="false"
            icon="el-icon-edit"
            @click="toRedeploy(row)"
          >
            转派
          </el-link>
          <el-link
            v-if="row.orderStatus == 3"
            type="primary"
            :underline="false"
            icon="el-icon-edit"
            @click="downLoadOrder(row)"
          >
            下载
          </el-link>
          <!-- <el-link
            type="primary"
            :underline="false"
            icon="el-icon-edit"
            @click="goDetail(row)"
          >
            详情
          </el-link> -->
        </template>
      </ele-pro-table>
    </el-card>
    <!-- <el-dialog :visible.sync="visible" width="20vw">
      <el-form label-width="100px">
     
      ></el-form>

      <div slot="footer">
        <el-button type="primary" @click="spareItems">确定</el-button>
        <el-button @click="visible = false">关闭</el-button>
      </div>
    </el-dialog> -->
    <RepairDetailsDialog ref="detailsDialogRef" />
    <!-- 报工弹窗 -->
    <RepairReportingWork ref="repairReportingWorkRef" @refresh="reload" />
    <!-- 转派弹窗 -->
    <redeployOther ref="redeployOtherRef" @refresh="reload" />
    <!-- 备件弹窗 -->
    <edit @refresh="reload" ref="edit" />
    <!-- <AddSpareDialog
      ref="addSpareDialogRef"
      :selectedSpare="selectedSpare"
      @submit="spareItemSelectSubmit"
    /> -->
  </div>
</template>

<script>
  import { workorderStatus, resultStatus } from '@/utils/dict/operationManage';
  import WorkorderSearch from './components/workorder-search.vue';
  import AddSpareDialog from '@/components/addSpareDialog';
  import edit from '@/views/sparePartsApply/components/edit';
  import RepairReportingWork from '../components/repairReportingWork.vue';
  import RepairDetailsDialog from '../components/RepairDetailsDialog.vue';
  import redeployOther from '@/views/maintenance/components/redeployOther.vue';
  import {
    getWorkOrderList,
    applySpareParts,
    save
  } from '@/api/maintenance/repair';
  import outin from '@/api/maintenance/outin';
  import { getToken } from '@/utils/token-util';
  import { download } from '@/utils/file';
  import { API_BASE_URL } from '@/config/setting';

  import axios from 'axios';
  export default {
    components: {
      WorkorderSearch,
      RepairDetailsDialog,
      redeployOther,
      AddSpareDialog,
      RepairReportingWork,
      edit
    },
    data() {
      return {
        workorderStatus,
        resultStatus,
        currentRow: {},
        warehousingMaterialList: [],
        batchDetailsVOList: [],
        materialCodeReqList: [],
        selectionList: [],
        wlParams: {},
        visible: false,
        materialObj: {},
        // 表格列配置
        columns: [
          {
            columnKey: 'index',
            label: '序号',
            type: 'index',
            width: 55,
            align: 'center',
            showOverflowTooltip: true,
            fixed: 'left'
          },
          {
            prop: 'code',
            slot: 'code',
            label: '工单编号',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 150
          },
          {
            prop: 'planCode',
            // label: '关联单号',
            label: '计划单号',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110
          },
          {
            prop: 'planName',
            label: '维修名称',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110
          },
          {
            prop: 'substanceDetailVO.name',
            label: '设备名称',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110
          },
          {
            prop: 'substanceDetailVO.fixCode',
            label: '固资编码',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110
          },
          {
            prop: 'substanceDetailVO.codeNumber',
            label: '设备编号',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110
          },
          {
            prop: 'executeUserName',
            label: '执行人',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110
          },
          {
            prop: 'acceptTime',
            label: '开始时间',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110
          },
          {
            prop: 'finishTime',
            label: '结束时间',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110
          },
          {
            prop: 'planFinishTime',
            label: '计划完成时间',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110
          },
          {
            columnKey: 'orderHour',
            label: '实际工时(分钟)',
            align: 'center',
            resizable: false,
            showOverflowTooltip: true,
            minWidth: 120,
            formatter: (row) => {
              if (row.finishTime && row.acceptTime) {
                return parseInt(
                  (new Date(row.finishTime).getTime() -
                    new Date(row.acceptTime).getTime()) /
                    60000
                );
              }
            }
          },
          {
            prop: 'orderStatus',
            label: '状态',
            align: 'center',
            showOverflowTooltip: true,
            formatter: (row) => {
              return workorderStatus.filter(
                (item) => item.code == row.orderStatus
              )[0].label;
            }
          },
          {
            prop: 'acceptanceStatus',
            label: '执行结果',
            align: 'center',
            showOverflowTooltip: true,
            formatter: (row) => {
              return row.acceptanceStatus
                ? resultStatus.filter(
                    (item) => item.code == row.acceptanceStatus
                  )[0].label
                : '';
            }
          },
          {
            columnKey: 'action',
            fixed: 'right',
            label: '操作',
            width: 300,
            align: 'center',
            resizable: false,
            slot: 'action',
            showOverflowTooltip: true
          }
        ],
        // 加载状态
        loading: false,
        pageType: 'add',
        dialogTitle: '',
        isBindPlan: false,
        warehouseList: [],
        warehouseId: ''
      };
    },
    created() {},
    methods: {
      downLoadOrder(row) {
        let params = {
          id: row.id
        };
        // downloadAsset(params, '设备台账导出数据');
        axios({
          url: `${API_BASE_URL}/eam/workorder/excel?id=${row.id}`,
          method: 'get',
          responseType: 'blob',
          headers: {
            Authorization: getToken()
          }
        }).then((res) => {
          download(res.data, '维修工单');
        });
      },
      async handleNewSave() {
        let { user } = JSON.parse(sessionStorage.getItem('vuex-eam'));
        console.log(user);
        let userInfo = user.info;
        let obj = {
          fromUser: userInfo.userId,
          bizType: '4', // 领用出库
          extInfo: {
            assetType: 6,
            verifyDeptCode: userInfo.deptId[0],
            verifyDeptName: userInfo.deptName
          },
          type: 2,
          fromType: 2
        };
        obj = { ...obj, ...this.wlParams };
        if (this.dimension == 4) {
          obj.num = this.materialObj.wlList.length;
        } else {
          obj.num = this.materialCodeReqList.length;
        }
        obj.storageSource = 1;
        try {
          const res = await outin.saveNew(obj);
          if (res.code == 0) {
            let arr = obj.realTimeInventoryNewPOList.map((item) => {
              return {
                sparePartsId: item.id,
                sparePartsList: JSON.stringify({
                  ...item,
                  inventoryDetailsNewPOList: [],
                  inventoryDetailsVOList: [],
                  outInIds: res.data
                })
              };
            });
            applySpareParts({
              workOrderId: this.currentRow.id,
              infoList: arr
            }).then((res) => {
              this.$message.success('申请成功！');
            });
          }
        } catch (error) {
          console.log(error);
        }
      },
      detailData(data) {
        applySpareParts({
          workOrderId: this.currentRow.id,
          listId: data.map((item) => item.id),
          listNumber: data.map((item) => item.measureQuantity)
        }).then((res) => {
          this.$message.success('申请成功！');
        });
      },
      // 添加备品备件
      addSpareItems(row) {
        let data = JSON.parse(JSON.stringify(row));
        console.log(data, 'data1');
        data['deviceList'] = [data.substanceDetailVO];
        this.$refs.edit.open(data, 'add');
        console.log(data, 'data2');
      },

      /* 表格数据源 */
      datasource({ page, limit, where, order }) {
        return getWorkOrderList({
          pageNum: page,
          size: limit,
          ...where,
          type: 3
        });
      },
      async changeEnable(row) {
        const res = await putRoles(row);
        if (res.code == 0) {
          this.$message({
            type: 'success',
            message: '修改成功',
            customClass: 'ele-message-border'
          });
          this.reload();
        }
      },
      /* 刷新表格 */
      reload(where) {
        this.$refs.table.reload({ page: 1, where });
      },

      goDetail(row) {
        row.title = '工单详情';
        row.tabLabel = '工单信息';
        this.$refs.detailsDialogRef.init(row);
      },

      // 转派
      toRedeploy(row) {
        this.$refs.redeployOtherRef.open(row);
      },
      // 报工
      toReport(row) {
        this.$refs.repairReportingWorkRef.open(row, true);
      }
    }
  };
</script>

<style lang="scss" scoped></style>
