<template>
  <div class="app-container">
    <!-- 搜索工作栏 -->
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="false"
      v-show="showSearch"
      class="search-form"
      label-width="90px"
    >
      <el-row :gutter="24">
        <el-col :span="8">
          <el-form-item label="工单分类" prop="categoryId" class="form-item-full">
            <TreeSelect
              v-model="queryParams.categoryId"
              :options="categoryTree"
              :normalizer="normalizer"
              :flat="true"
              :disable-branch-nodes="true"
              placeholder="请选择工单分类"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="技术运维商" prop="techOperatorId" class="form-item-full">
            <el-select
              v-model="queryParams.techOperatorId"
              placeholder="请选择技术运维商"
              clearable
            >
              <el-option
                v-for="item in operatorList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="部门用户" prop="userId" class="form-item-full">
          <el-select v-model="queryParams.userId" placeholder="请选择用户" clearable>
            <el-option v-for="item in userList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="8">
          <el-form-item label="工单状态" prop="status" class="form-item-full">
            <el-select v-model="queryParams.status" placeholder="请选择工单状态" clearable size="small">
              <el-option v-for="dict in this.getDictDatas(DICT_TYPE.TRS_WORKORDER_STATUS)"
                          :key="dict.value" :label="dict.label" :value="dict.value"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="工单描述" prop="requirement" class="form-item-full">
            <el-input v-model="queryParams.requirement" placeholder="请输入工单描述" clearable @keyup.enter.native="handleQuery"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="下单时间" prop="orderTime" class="form-item-full">
            <el-date-picker
              v-model="queryParams.orderTime"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="['00:00:00', '23:59:59']"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24" style="text-align: right;">
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-col>
      </el-row>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5" v-if="listUserRoles.includes(162)">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="addopenForm(undefined)"
          v-hasPermi="['server:workorder-infos:create']"
          >新增</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" :loading="exportLoading"
                   v-hasPermi="['server:workorder-infos:export']">导出</el-button>
      </el-col> -->
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
    >
      <!-- <el-table-column label="工单ID" align="center" prop="id" /> -->
      <el-table-column label="工单分类" align="center" prop="category" />
      <el-table-column label="技术运维商" align="center" prop="techOperator" />
      <el-table-column label="部门用户" align="center" prop="user" />
      <!-- <el-table-column label="需求描述" align="center" prop="requirement" /> -->
      <!-- <el-table-column label="资料描述" align="center" prop="requiredInfo" /> -->
      <el-table-column
        label="下单时间"
        align="center"
        prop="orderTime"
        width="180"
      >
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.orderTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="工单状态" align="center" prop="status">
        <template v-slot="scope">
          <dict-tag type="trs_workorder_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <!-- <el-table-column label="打回原因" align="center" prop="rejectReason" /> -->
      <el-table-column
        label="期望完成日期"
        align="center"
        prop="expectedCompletionDate"
        width="180"
      >
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.expectedCompletionDate) }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column> -->
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template v-slot="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="openForm(scope.row.id, 'inspect')"
            v-hasPermi="['server:workorder-infos:update']"
            >查看</el-button
          >
          <el-button
            v-if="(scope.row.status === '21' && queryParams.type === 'user') || (scope.row.status === '31' && queryParams.type === 'dsjzx') || (scope.row.status === '41' && queryParams.type === 'zwgk') || ((scope.row.status === '51' || scope.row.status === '60') && scope.row.techOperatorId === deptId && scope.row.rejectReason ==='' && queryParams.type === 'yws')"
            size="mini"
            type="text"
            icon="el-icon-document"
            @click="openForm(scope.row.id, 'check')"
            v-hasPermi="['server:workorder-infos:update']"
            >审核</el-button
          >
          <el-button v-if="scope.row.status === '10' || (scope.row.rejectReason !== null && scope.row.rejectReason !== '' && String(scope.row.creator) === String($store.getters.userId) && scope.row.status !== '0')" size="mini" type="text" icon="el-icon-edit" @click="openForm(scope.row.id,'edit')"
          v-hasPermi="['server:workorder-infos:update']">修改</el-button>
          <el-button v-if="scope.row.status === '10' || (scope.row.rejectReason !== null && scope.row.rejectReason !== '' && String(scope.row.creator) === String($store.getters.userId) && scope.row.status !== '0')" size="mini" type="text" icon="el-icon-delete" @click="closeWorkorder(scope.row.id)"
          v-hasPermi="['server:workorder-infos:update']">关闭</el-button>
          <!-- <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['server:workorder-infos:delete']">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNo"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import * as WorkorderInfosApi from "@/api/server/WorkorderInfos";
import * as WorkorderTypeApi from "@/api/server/WorkorderType";
import * as PermissionApi from "@/api/system/permission";
import * as UserApi from "@/api/system/user";
import TreeSelect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  components: {
    TreeSelect,
  },
  data() {
    return {
      //用户列表
      userList: [],
      //技术运维商列表
      operatorList: [],
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 工单列表
      list: [],
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 选中行
      currentRow: {},
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        categoryId: null,
        techOperatorId: null,
        userId: null,
        requirement: null,
        requiredInfo: null,
        orderTime: [],
        status: null,
        rejectReason: null,
        expectedCompletionDate: [],
        createTime: [],
        type: "",
      },
      categoryTree: [],
      listUserRoles: [],
      deptId: null,
    };
  },
  created() {
    this.getList();
    this.getOperatorList();
    this.getUserList();
    this.getCategoryList();
  },
  methods: {
    /** 查询列表 */
    async getList() {
      try {
        this.loading = true;
        //获取当前用户部门
        const userInfo = await UserApi.getUser(this.$store.getters.userId);
        this.deptId = userInfo.data.deptId;
        //获取当前用户角色
        const listUserRoles = await PermissionApi.listUserRoles(
          this.$store.getters.userId
        );
        this.listUserRoles = listUserRoles.data;
        listUserRoles.data.forEach((item) => {
          if (item === 161) {
            this.queryParams.type = "user";
          } else if (item === 162) {
            this.queryParams.type = "yws";
          } else if (item === 163) {
            this.queryParams.type = "dsjzx";
          } else if (item === 164) {
            this.queryParams.type = "zwgk";
          }
        });
        const res = await WorkorderInfosApi.getWorkorderInfosPage(
          this.queryParams
        );
        this.list = res.data.list;
        this.total = res.data.total;
      } finally {
        this.loading = false;
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.queryParams.search = 'search';
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.search = 'all';
      this.handleQuery();
    },
    /** 添加/修改操作 */
    openForm(id, type) {
      if (type === "inspect") {
        this.$router.push({
          path: "/server/workorder-infos-view-workorder",
          query: {
            id: id,
          },
        });
      } else if (type === "check") {
        this.$router.push({
          path: "/server/workorder-infos-check",
          query: {
            id: id,
          },
        });
      } else if (type === "edit") {
        this.$router.push({
        path: '/server/workorder-infos-add-workorder',
        query: {
          type: id ? 'edit' : 'add',
          id: id
        }
      });
      } else {
        this.$router.push({
          path: "/server/workorder-infos-check",
          query: {
            type: id ? "edit" : "add",
            id: id,
          },
        });
      }
    },
    /** 删除按钮操作 */
    async handleDelete(row) {
      const id = row.id;
      await this.$modal.confirm('是否确认删除工单编号为"' + id + '"的数据项?');
      try {
        await WorkorderInfosApi.deleteWorkorderInfos(id);
        await this.getList();
        this.$modal.msgSuccess("删除成功");
      } catch {}
    },
    /** 导出按钮操作 */
    async handleExport() {
      await this.$modal.confirm("是否确认导出所有工单数据项?");
      try {
        this.exportLoading = true;
        const data = await WorkorderInfosApi.exportWorkorderInfosExcel(
          this.queryParams
        );
        this.$download.excel(data, "工单.xls");
      } catch {
      } finally {
        this.exportLoading = false;
      }
    },
    //获取处理运维商
    async getOperatorList() {
      const res = await WorkorderTypeApi.suplierList();
      this.operatorList = res.data;
    },
    async getUserList() {
      const res = await WorkorderInfosApi.getUserList();
      this.userList = res.data;
    },
    //获取工单分类
    async getCategoryList() {
      this.categoryTree = [];
      const res = await WorkorderTypeApi.getWorkorderTypeList();
      this.categoryTreeList = res.data;
      const tree = this.handleTree(res.data, "id", "parentId");
      this.categoryTree = tree;
    },
    /** 转换工单类型数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children,
      };
    },
    addopenForm() {
      this.$router.push({
        path: "/server/workorder-infos-add-workorder",
        query: {
          type: "add",
        },
      });
    },
    //关闭工单
    async closeWorkorder(id) {
      this.$modal.confirm('是否确认关闭该工单?').then(async () => {
      try {
        await WorkorderInfosApi.closeWorkorderInfos(id);
          await this.getList();
          this.$modal.msgSuccess("关闭成功");
        } catch {
          console.log('关闭失败');
        }
      });
    },
}
};
</script>

<style lang="scss" scoped>
.search-form {
  margin-bottom: 15px;
  background: #fff;
  padding: 18px 10px 8px 10px;
  border-radius: 4px;

  .form-item-full {
    width: 100%;

    :deep(.el-select),
    :deep(.el-date-editor),
    :deep(.el-input),
    :deep(.vue-treeselect) {
      width: 100%;
    }
  }

  .el-form-item {
    margin-bottom: 10px;
  }
}
</style>
