<!-- 维修工单 -->
<template>
  <div class="ele-body">
    <el-card shadow="never">
      <div class="filter-container">
        <seekPage
          :seekList="seekList"
          :formLength="3"
          @search="search"
        ></seekPage>
      </div>
      <ele-pro-table
        ref="table"
        :columns="columns"
        :datasource="datasource"
        :pageSize="20"
      >
        <!-- 操作列 -->
        <template v-slot:action="{ row }">
          <el-link
            v-if="row.orderStatus == 0"
            type="primary"
            :underline="false"
            icon="el-icon-edit"
            @click="handleNotice(row)"
          >
            接收
          </el-link>
          <el-link
            v-if="row.orderStatus == 3 && row.requestUserId ==  $store.state.user.info.userId"
            type="primary"
            :underline="false"
            icon="el-icon-edit"
            @click="goDetail(row)"
          >
            验收
          </el-link>
          <el-link
            v-if="
              row.orderStatus !== 3 &&
              row.orderStatus !== 0 &&
              row.orderStatus !== 4 &&
              $store.state.user.info.userId == row.executeUserId
            "
            type="primary"
            :underline="false"
            icon="el-icon-edit"
            @click="toSigningUpWork(row)"
          >
            报工
          </el-link>
          <el-link
            v-if="
              row.orderStatus !== 3 &&
              row.orderStatus !== 4 &&
             $store.state.user.info.userId== row.executeUserId
            "
            type="primary"
            :underline="false"
            icon="el-icon-edit"
            @click="toRedeploy(row)"
          >
            转派
          </el-link>
          <el-link
            type="primary"
            :underline="false"
            icon="el-icon-edit"
            @click="openDetail(row)"
          >
            详情
          </el-link>
        </template>
      </ele-pro-table>
    </el-card>
    <!-- 验收 -->
    <RepairDetailsDialog ref="detailsDialogRef" @refesh="getData" />
    <!-- 非完成报工接收  注意事项-->
    <Notice ref="noticeShow" :repairInfo="repairInfo" @agree="agree" />
    <!-- 转派弹窗 -->
    <redeployOther ref="redeployOtherRef" @refresh="getData" />
    <!-- 报工弹框 -->
    <signingUpWork ref="signingUpWorkRef" @refresh="getData" />
  </div>
</template>
<script>
  import RepairDetailsDialog from '../components/RepairDetailsDialog.vue';
  import redeployOther from '../components/redeployOther.vue';
  import signingUpWork from '../components/signingUpWork.vue';
  import { workorderStatus, resultStatus } from '@/utils/dict/tickets';
  import {
    getWorkOrderList,
    getRule,
    startExecuting,
    getWorkOrderDetail
  } from '@/api/tickets';
  import pagenation from '@/components/Pagination';
  import Notice from '../components/notice.vue';

  // 修改
  import {
    notifyMessagePageAPI,
    updateNotifyMessageReadByIdAPI
  } from '@/api/bpm/task';
  import { mapGetters } from 'vuex';
  export default {
    components: {
      pagenation,
      redeployOther,
      signingUpWork,
      Notice,
      RepairDetailsDialog
    },
    data() {
      return {
        ruleNameList: [],
        userId: '',
        workorderStatus: [],
        resultStatus,
        repairInfo: {},

        //
        addOrEditDialogFlag: false,
        columns: [
          {
            columnKey: 'index',
            label: '序号',
            type: 'index',
            width: 60,
            align: 'center',
            showOverflowTooltip: true,
            fixed: 'left'
          },
          {
            prop: 'code',
            label: '工单编号',
            minWidth: '200',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'planCode',
            label: '计划单号',
            width: '200',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'planName',
            label: '维修名称',
            align: 'center',
            minWidth: '180',
            showOverflowTooltip: true
          },
          {
            prop: 'ruleName',
            label: '规则名称',
            align: 'center',
            minWidth: '180',
            showOverflowTooltip: true
          },
          {
            prop: 'equiCode',
            label: '设备编号',
            align: 'center',
            minWidth: '180',
            showOverflowTooltip: true
          },

          {
            prop: 'equiName',
            label: '设备名称',
            align: 'center',
            minWidth: '180',
            showOverflowTooltip: true
          },
          {
            prop: 'requestUserName',
            label: '报修人',
            align: 'center',
            minWidth: '180',
            showOverflowTooltip: true
          },
          {
            prop: 'executeUserName',
            label: '执行人',
            align: 'center',
            minWidth: '180',
            showOverflowTooltip: true
          },
          {
            prop: 'acceptTime',
            label: '开始时间',
            align: 'center',
            minWidth: '180',
            showOverflowTooltip: true
          },
          {
            prop: 'finishTime',
            label: '结束时间',
            align: 'center',
            minWidth: '180',
            showOverflowTooltip: true
          },
          {
            prop: 'planFinishTime',
            label: '计划完成时间',
            align: 'center',
            minWidth: '180',
            showOverflowTooltip: true
          },
          {
            prop: 'acceptanceStatus',
            label: '执行结果',
            align: 'center',
            showOverflowTooltip: true,
            formatter: (_row, _column, cellValue) => {
              return _row.acceptanceStatus
                ? resultStatus.filter(
                    (item) => item.code == _row.acceptanceStatus
                  )[0].label
                : '';
            }
          },
          {
            prop: 'orderStatus',
            label: '状态',
            align: 'center',
            showOverflowTooltip: true,
            formatter: (_row, _column, cellValue) => {
              return workorderStatus.filter(
                (item) => item.id == _row.orderStatus
              )[0]?.label;
            }
          },

          {
            prop: 'practicalTime',
            label: '实际工时',
            align: 'center',
            showOverflowTooltip: true,
            formatter: (_row, _column, cellValue) => {
              let _this = this;
              return _this.time_interval(_row.acceptTime, _row.finishTime);
            }
          },

          {
            columnKey: 'action',
            label: '操作',
            minWidth: 250,
            align: 'center',
            slot: 'action',
            fixed: 'right'
          }
        ],
        searchForm: {
          code: '',
          status: '',
          ruleId: '',
          date: '',
          startTime: '',
          endTime: '',
          executeUserId: '',
          statusType: 0,
          type: 3,
          isQueryTodo: 1,
          executeUserId: ''
        },
        tableData: [],
        size: 20,
        page: 1,
        total: 0
      };
    },
    computed: {
      ...mapGetters(['user']),
      // 是否开启响应式布局
      styleResponsive() {
        return this.$store.state.theme.styleResponsive;
      },
      seekList() {
        return [
          {
            label: '工单编号',
            value: 'code',
            type: 'input',
            placeholder: ' '
          },
          {
            label: '规则名称：',
            value: 'ruleId',
            type: 'select',
            placeholder: '  ',
            planList: this.ruleNameList.map((item) => {
              return { label: item.name, value: item.id };
            })
          },
          {
            label: '状态',
            value: 'status',
            type: 'select',
            planList: workorderStatus.map((item) => {
              return { label: item.label, value: item.id };
            }),
            placeholder: ' '
          },

          {
            label: '创建时间',
            value: 'createTime',
            type: 'date',
            dateType: 'datetimerange',
            placeholder: '',
            width: 380,
            labelWidth: '130px',
            valueAr: ['startTime', 'endTime']
          }
        ];
      }
    },
    methods: {
      //新增或修改模板
      async handleAddOrEdit(row) {
        await updateNotifyMessageReadByIdAPI([row.id]);
        this.$refs.table.reload();
      },
      search(e) {
        this.searchForm = e;
        this.$refs.table.reload({ page: 1, where: e });
      },

      // 获取table数据
      async datasource({ page, where, limit, ...row }) {
        const res = await getWorkOrderList({
          ...where,
          pageNum: page,
          size: limit,
          executeUserId: this.userId,
          userId: this.user.info.userId,
          type: 3,
          isQueryTodo: 1,
          statusType: 1
        });

        this.total = res.total;
        this.$emit('recount');
        return res;
      },

      // 获取规则名列表(设备维修)
      async getRuleNameList() {
        const res = await getRule({
          status: 1,
          type: 3,
          pageNum: 1,
          size: -1
        });
        if (res.list) {
          this.ruleNameList = res.list || [];
        }
      },
      async handleNotice(row) {
        this.id = row.id;
        const res = await getWorkOrderDetail(row.code);
        console.log(res, 'resresresresres');
        this.repairInfo = res.repairRequestResponse;
        this.$refs.noticeShow.open(row);
      },
      agree() {
        this.$refs.noticeShow.close();
        this.handleExecute();
      },
      // 执行工单
      handleExecute() {
        startExecuting({
          id: this.id
        }).then(() => {
          this.reload();
        });
      },
      // 验收
      goDetail(row) {
        row.title = '工单详情';
        row.tabLabel = '工单信息';
        this.$refs.detailsDialogRef.init(row);
      },
      // 转派
      toRedeploy(row) {
        this.$refs.redeployOtherRef.open(row);
      },
      // 报工
      toSigningUpWork(row) {
        this.$refs.signingUpWorkRef.open(row);
      },
      openDetail(row) {
        row.title = '工单详情';
        row.tabLabel = '工单信息';
        this.$refs.detailsDialogRef.init(row, true);
      },
      getData() {
        this.search(this.searchForm);
      },
      // 计算实际工时
      time_interval(dt1, dt2) {
        if (!dt1 || !dt2) {
          return '';
        }
        if (typeof dt1 == 'string') {
          dt1 = new Date(dt1.replace(/-/, '/'));
          dt2 = new Date(dt2.replace(/-/, '/'));
        }
        var res = dt2 - dt1;
        if (isNaN(res)) throw Error('invalid dates arguments');
        let re = res / (1000 * 60 * 60);

        var h = parseInt(re);
        var m = parseInt((re - h) * 60);
        let result = '';
        if (h) {
          result += `${h} 小时`;
        }
        if (m) {
          result += `${m} 分钟`;
        }
        return result;
      },
      changeDate(val) {
        if (val === null) {
          this.searchForm.startTime = '';
          this.searchForm.endTime = '';
          return;
        }
        this.searchForm.startTime = val[0];
        this.searchForm.endTime = val[1];
      }
    },
    created() {
      this.userId = localStorage.getItem('userId');
      this.searchForm.executeUserId = this.userId;
      this.getRuleNameList();
      this.workorderStatus = workorderStatus.filter((item) => {
        return [0, 2, 3].includes(item.id);
      });
    }
  };
</script>

<style lang="scss" scoped>
  // 步骤条边线显示
  // ::v-deep .el-step__head.is-process .el-step__icon.is-text {
  //   border: none !important;
  //   background: none !important;
  // }
  // ::v-deep .el-step:last-of-type .el-step__line {
  //   display: block !important;
  //   width: 3px !important;
  // }
  // ::v-deep .el-steps:last-child .el-step__line {
  //   display: none !important;
  // }
  // .patrolInspection {
  //   height: 100%;
  //   width: 100%;
  //   display: flex;
  //   flex-direction: column;
  //   .search {
  //     flex: 0 0 50px;
  //   }
  //   .table {
  //     flex: 1;
  //     .el-table {
  //       width: 100%;
  //       display: flex;
  //       flex-direction: column;
  //     }
  //   }
  //   .table-footer {
  //     flex: 0 0 30px;
  //     display: flex;
  //     justify-content: flex-end;
  //   }
  // }

  // 修改
  // ::v-deep .el-card__body {
  //   padding: 0;
  // }

  // .app-container {
  //   background: #f0f3f3;
  //   min-height: calc(100vh - 84px);
  // }

  // .zw-page-table {
  //   background: #ffffff;
  //   padding-top: 20px;
  // }

  // .pagination-wrap {
  //   display: flex;
  //   justify-content: flex-end;
  //   padding: 10px 0;
  // }

  // .table {
  //   width: 100%;
  //   margin-top: 10px;
  // }
</style>
