<template>
  <div class="app-container power-maintenance">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="设备名称" prop="deviceName">
        <el-input
          v-model="queryParams.deviceName"
          placeholder="请输入设备名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="故障类型" prop="faultType">
        <el-select
          v-model="queryParams.faultType"
          placeholder="请选择故障类型"
          clearable
          size="small"
        >
          <el-option
            v-for="dict in faultTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="上报人" prop="reporterName">
        <el-input
          v-model="queryParams.reporterName"
          placeholder="请输入上报人名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="处理人" prop="handlerName">
        <el-input
          v-model="queryParams.handlerName"
          placeholder="请输入处理人名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="处理时间" prop="handleTime">
        <el-date-picker
          clearable
          size="small"
          style="width: 200px"
          v-model="queryParams.handleTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择处理时间"
        ></el-date-picker>
      </el-form-item>

      <el-form-item label="工单状态" prop="maintenanceStatus">
        <el-select
          v-model="queryParams.maintenanceStatus"
          placeholder="请选择工单状态"
          clearable
          size="small"
        >
          <el-option
            :label="keys"
            :value="val"
            v-for="(keys, val) in workStateList"
            :key="keys"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <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-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['iot:maintenance:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['iot:maintenance:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="maintenanceList"
      :default-sort="{ prop: 'createTime', order: 'descending' }"
      @sort-change="sortChange"
    >
      <el-table-column
        type="index"
        label="序号"
        align="center"
        :index="indexFormatter"
        width="80px"
      ></el-table-column>
      <el-table-column label="项目名称" align="left" prop="projectName" />
      <el-table-column label="项目地址" align="left" prop="projectAddress">
        <template slot-scope="scope">
          <span class="lay-table-textarea" :title="scope.row.projectAddress">
            {{ scope.row.projectAddress }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="设备名称" align="left" prop="deviceName" />
      <el-table-column
        label="故障类型"
        align="center"
        sortable="custom"
        width="150"
        prop="faultType"
        :formatter="statusFormat"
      />
      <el-table-column label="上报人" align="left" prop="reporterName" />
      <el-table-column label="处理人" align="left" prop="handlerName" />
      <el-table-column label="工作内容" align="left" prop="maintenanceContext">
        <template slot-scope="scope">
          <span class="lay-table-textarea" :title="scope.row.maintenanceContext">
            {{ scope.row.maintenanceContext }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        label="上报时间"
        align="left"
        prop="createTime"
        sortable="custom"
        width="120"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="处理时间"
        align="left"
        prop="handleTime"
        width="120"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.handleTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="工单状态"
        align="center"
        width="120"
        prop="maintenanceStatus"
      >
        <template slot-scope="scope">
          <el-tag
            v-if="scope.row.maintenanceStatus === '-1'"
            type="info"
            effect="plain"
          >
            {{ workStateList[scope.row.maintenanceStatus] }}
          </el-tag>
          <el-tag v-if="scope.row.maintenanceStatus === '0'" type="info">{{
            workStateList[scope.row.maintenanceStatus]
          }}</el-tag>
          <el-tag v-if="scope.row.maintenanceStatus === '5'" type="success">{{
            workStateList[scope.row.maintenanceStatus]
          }}</el-tag>
          <el-tag v-if="scope.row.maintenanceStatus === '3'">{{
            workStateList[scope.row.maintenanceStatus]
          }}</el-tag>
          <el-tag type="warning" v-if="scope.row.maintenanceStatus === '2'">{{
            workStateList[scope.row.maintenanceStatus]
          }}</el-tag>
          <el-tag
            type="danger"
            v-if="
              scope.row.maintenanceStatus === '1' ||
              scope.row.maintenanceStatus === '4'
            "
            >{{ workStateList[scope.row.maintenanceStatus] }}</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="150"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['iot:maintenance:edit']"
          >修改</el-button> -->
          <el-button size="mini" type="text" @click="handleDetails(scope.row)"
            >工单追踪</el-button
          >
          <!-- <el-button
            size="mini"
            type="text"
            @click="handleDelete(scope.row)"
            v-hasPermi="['iot:maintenance:remove']"
            >删除</el-button
          > -->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改工单信息对话框 -->
    <el-dialog
      class="eldialog-wrap"
      :close-on-click-modal="false"
      :title="title"
      :visible.sync="open"
      width="500px"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="设备名称" prop="deviceName">
          <el-input
            v-model="form.deviceName"
            @focus="openTableSelectDialog"
            placeholder="请输入设备名称"
          />
        </el-form-item>
        <el-form-item label="故障类型" prop="faultType">
          <el-select
            v-model="form.faultType"
            style="width: 100%"
            placeholder="请选择故障类型"
            @change="faultTypeChange"
          >
            <el-option
              v-for="dict in faultTypeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="上报人" prop="reporterName">
          <el-input
            v-model="form.reporterName"
            disabled
            placeholder="请输入上报人昵称"
          />
        </el-form-item>

        <el-form-item label="处理人" prop="handlerId">
          <el-select
            v-model="form.handlerId"
            style="width: 100%"
            placeholder="请选择处理人"
          >
            <el-option
              v-for="item in gdUserList"
              :key="item.userId"
              :label="item.nickName"
              :value="item.userId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="工作内容" prop="maintenanceContext">
          <el-input
            v-model="form.maintenanceContext"
            type="textarea"
            maxlength="200"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" @click="submitForm"
          >确 定</el-button
        >
        <el-button size="mini" @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="选择"
      :visible.sync="selectTableShow"
      width="75%"
      top="10vh"
      class="select-table-dialog"
      :close-on-click-modal="false"
    >
      <select-table-wrap
        v-if="selectTableShow"
        :tableOption="tableSelectOption.tableOpt"
        :queryOption="tableSelectOption.queryOpt"
        :tableList="tableSelectOption.tableList"
        @parentGetList="childGetList($event)"
        :otherOption="tableSelectOption.otherOption"
        @returnEvent="returnEvent($event)"
      />

      <div slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" @click="resuleClick"
          >确 定</el-button
        >
        <el-button
          size="mini"
          @click="
            () => {
              selectTableShow = false;
            }
          "
          >取 消</el-button
        >
      </div>
    </el-dialog>

    <el-dialog
      title="工单详情"
      class="eldialog-wrap dialot-det"
      top="5vh"
      @close="dialogCloes()"
      :visible.sync="openDestail"
      width="800px"
    >
      <div class="dialot-details">
        <details-wrap
          v-if="openDestail"
          tempType="workList"
          :maintenanceId="workDetails.maintenanceId"
        />
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listMaintenance,
  getMaintenance,
  delMaintenance,
  addMaintenance,
  updateMaintenance,
  exportMaintenance,
} from "@/api/power/maintenance";
import { myListDevice } from "@/api/iot/device";
import { listUser, gdListUser } from "@/api/system/user";
import { listDept } from "@/api/system/dept";
import DetailsWrap from "../mywork/details";
import Treeselect from "@riophae/vue-treeselect";
import SelectTableWrap from "@/components/SelectTable/index";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

// 工单状态(0:上报人创建工单 1:驳回上报人工单 2:处理人确认工单 3:处理人完成工单 4:驳回处理人工单 5:领导审批通过流程结束)
const workStateList = {
  "-1": "工单已生成",
  0: "工单已创建",
  1: "退回工单",
  2: "确认工单",
  3: "处理完成",
  4: "退回处理",
  5: "审核通过",
};

export default {
  name: "Maintenance",
  components: {
    Treeselect,
    SelectTableWrap,
    DetailsWrap,
  },
  data() {
    return {
      workStateList,
      openDestail: false,
      selectTableShow: false,
      tableSelectOption: {},
      selectResult: {},
      faultTypeOptions: [],
      workDetails: {},
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 工单信息表格数据
      maintenanceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        recordId: null,
        deviceId: null,
        deviceName: null,
        faultType: null,
        faultTypeName: null,
        reporterId: null,
        reporterName: null,
        maintenanceContext: null,
        handlerId: null,
        handlerName: null,
        handleTime: null,
        scenePictures: null,
        feedbackInformation: null,
        advice: null,
        maintenanceStatus: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      deptOptions: [],
      gdUserList: [],
    };
  },
  created() {
    // 获取故障类型（字典）
    this.getDicts("fault_type").then((response) => {
      this.faultTypeOptions = response.data;
    });
    this.getList();
    // this.getTreeselect();
  },
  methods: {
    sortChange(column) {
      const sort = {
        isAsc: column.order === "descending" ? "desc" : "asc",
        orderByColumn: column.prop,
      };
      this.queryParams = Object.assign(this.queryParams, sort);
      this.handleQuery();
    },
    dialogCloes() {
      this.getList();
    },
    faultTypeChange(val) {
      this.form["faultTypeName"] = this.statusFormat({ faultType: val }, null);
    },
    // 查看详情
    handleDetails(row) {
      console.log("handleDetail:", row);
      this.workDetails = row;
      this.openDestail = true;
    },
    // 打开设备选择窗口 ——表格
    openTableSelectDialog() {
      this.selectResult = {};
      this.tableSelectOption = {
        otherOption: {
          tableType: "device",
        },
        queryOpt: {
          disable: false,
          labelWidth: "68px",
          params: {
            deviceName: "",
            modelId: "",
            parentId: 0,
            // deviceType: "GATEWAY_CONTROLLER",
            deviceType: "",
          },
          page: {
            pageSize: 10,
            pageNum: 1,
            total: 0,
          },
          inline: true,
          queryChilds: [
            {
              style: "",
              placeholder: "设备名称",
              clearable: true,
              label: "设备名称",
              type: "input",
              key: "deviceName",
              size: "small",
              value: "",
            },
          ],
        },
        tableOpt: {
          loading: false,
          rowKey: "deviceId",
          selection: false,
          maxHeight: "45vh",
          childs: [
            {
              style: "",
              label: "所属型号",
              type: "",
              prop: "modelName",
              align: "left",
              width: "",
              "show-overflow-tooltip": false,
              tempType: "span",
            },
            {
              style: "",
              label: "设备名称",
              type: "",
              prop: "deviceName",
              align: "left",
              width: "",
              "show-overflow-tooltip": false,
              tempType: "span",
            },
            {
              style: "",
              label: "设备Key",
              type: "",
              prop: "deviceKey",
              align: "left",
              width: "",
              "show-overflow-tooltip": false,
              tempType: "span",
            },
            {
              style: "",
              label: "创建时间",
              type: "time",
              prop: "createTime",
              align: "center",
              width: "160",
              "show-overflow-tooltip": false,
              tempType: "span",
            },
          ],
          tableList: {
            type: Array,
          },
        },
        tableList: [],
      };
      this.selectTableShow = true;
    },
    // 查询回调
    childGetList(data) {
      myListDevice(Object.assign(data.page, data.param, { selected: 1 })).then(
        (response) => {
          this.tableSelectOption.tableList = response.rows;
          this.tableSelectOption.queryOpt.page.total = Number(response.total);
        }
      );
    },
    // 点击或者双击数据回调
    returnEvent(data) {
      if (data.type === "dblclick") {
        this.form.deviceId = data.value.deviceId;
        this.form.deviceName = data.value.deviceName;
        this.selectTableShow = false;
      } else if (data.type === "click") {
        this.selectResult = {};
        this.selectResult.deviceId = data.value.deviceId;
        this.selectResult.deviceName = data.value.deviceName;
      }
    },
    // 点击确定按钮
    resuleClick() {
      this.form.deviceId = this.selectResult.deviceId;
      this.form.deviceName = this.selectResult.deviceName;
      this.selectTableShow = false;
    },
    // 获取 工单 处理人列表
    gdListUser() {
      gdListUser().then((response) => {
        this.gdUserList = response.data;
      });
    },
    // 获取到用户列表 并且赋值到 部门表
    getUserList(data) {
      var userList = [];
      var _this = this;
      listUser().then((response) => {
        debugger;
        userList = response.rows;
        if (userList) {
          userList.forEach((v) => {
            if (v.deptId) {
              let deptId = v.deptId;
              v.deptId = v.userId;
              v.parentId = deptId;
            }
          });
        }
        _this.deptOptions = _this.handleTree(data.concat(userList), "deptId");
      });
      return userList;
    },
    /** 查询部门人员列表 */
    getTreeselect() {
      listDept({ pageNum: 1, pageSize: 99999 }).then((response) => {
        this.getUserList(response.data);
      });
    },
    normalizer(node) {
      if (node.nickName) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName ? node.deptName : node.nickName,
        children: node.children,
      };
    },
    treeselect(node, instanceId) {
      this.form.handlerName = node.nickName;
    },
    indexFormatter(val) {
      return (
        val + 1 + (this.queryParams.pageNum - 1) * this.queryParams.pageSize
      );
    },
    // 字典状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.faultTypeOptions, row.faultType);
    },
    /** 查询工单信息列表 */
    getList() {
      this.loading = true;
      listMaintenance(this.queryParams).then((response) => {
        this.maintenanceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        maintenanceId: null,
        recordId: null,
        deviceId: null,
        deviceName: null,
        faultType: null,
        reporterId: null,
        reporterName: null,
        maintenanceContext: null,
        handlerId: null,
        handlerName: null,
        handleTime: null,
        scenePictures: null,
        feedbackInformation: null,
        advice: null,
        maintenanceStatus: "0",
        tenantId: null,
        createId: null,
        createTime: null,
        updateId: null,
        updateTime: null,
        remark: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.maintenanceId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.gdListUser();
      this.form.reporterName = this.$store.getters.name;
      this.open = true;
      this.title = "添加工单信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const maintenanceId = row.maintenanceId || this.ids;
      getMaintenance(maintenanceId).then((response) => {
        this.form = response.data;
        this.gdListUser();
        this.open = true;
        this.title = "修改工单信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.maintenanceId != null) {
            updateMaintenance(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMaintenance(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const maintenanceIds = row.maintenanceId || this.ids;
      this.$confirm("是否删除该选项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delMaintenance(maintenanceIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有工单信息数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportMaintenance(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        });
    },
  },
};
</script>
<style lang="scss">
.power-maintenance {
  .eldialog-wrap {
    .el-dialog__header {
      border-bottom: 1px solid #747373;
    }
    .el-dialog__body {
      padding: 0px;
    }
    .el-form {
      padding: 20px;
      padding-right: 40px;
    }
    .el-dialog__footer {
      height: 60px;
      border-top: 1px solid #747373;
      text-align: right;
      width: 100%;
      padding: 0px;
      padding-top: 15px;
      .el-button + .el-button {
        margin-right: 10px;
      }
      .el-button {
        padding-top: 8px;
      }
    }
    .table-avatar {
      .el-form-item__content {
        margin-left: 0px !important;
      }
    }
  }
  .dialot-det {
    .el-dialog__body {
      padding: 0;
      overflow: auto;
    }
  }
}
</style>
