<template>
  <div class="repair-box">
    <div class="sys-operate">
      <el-button type="primary" v-has="'repair:repair:add'" @click="add()">新增</el-button>
      <el-button type="primary" v-has="'repair:repair:remove'" @click="remove()" :disabled="btnDelDisabled">删除</el-button>
      <!-- <el-button type="primary" @click="add()">增加</el-button>
      <el-button type="primary" @click="remove()" :disabled="btnDelDisabled">删除</el-button>-->
<!--      <el-button type="primary" @click="send()" :disabled="btnOtherDisabled">维修转派</el-button>-->
<!--      <el-button type="primary" @click="repair()" :disabled="btnOtherDisabled">维修处理</el-button>-->
      <!-- <el-button type="primary" @click="complete()" :disabled="btnOtherDisabled">完工验收</el-button> -->
    </div>
    <div class="sys-search">
      <el-form inline class="form_item_search_out">
        <div class='form_item_input_out'>
        <el-form-item label="设备名称" style='width:22%' class="form_item-inline">
          <el-input v-model="search_data.divceName" placeholder="设备名称"></el-input>
        </el-form-item>
        <el-form-item label="报修时间" style='width:34%' class="form_item-inline">
          <el-date-picker
            v-model="repairTime"
            type="daterange"
            format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="故障等级" style='width:22%' class="form_item-inline">
          <el-select v-model="search_data.level" clearable placeholder="请选择">
            <el-option v-for="item in levels" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
          <el-form-item label="任务状态" style='width:22%' class="form_item-inline">
            <el-select v-model="search_data.reventStatus" clearable placeholder="请选择">
              <el-option
                v-for="item in statusList"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
<!--        <el-form-item label="部门" style='width:22%' class="form_item-inline">-->
<!--&lt;!&ndash;          <el-select v-model="search_data.deptIdQuery" filterable clearable placeholder="请选择">&ndash;&gt;-->
<!--&lt;!&ndash;            <el-option v-for="item in depts" :key="item.id" :label="item.name" :value="item.id"></el-option>&ndash;&gt;-->
<!--&lt;!&ndash;          </el-select>&ndash;&gt;-->
<!--          <el-cascader-->
<!--            v-model="selectDeptId" clearable-->
<!--            :options="depOptions"-->
<!--            :props="{ expandTrigger: 'hover',label:'text',value:'id', checkStrictly: true}"-->
<!--            @change="handleChange"></el-cascader>-->
<!--        </el-form-item>-->
        </div>
      <div class='form_item_btn_out' >
        <el-form-item>
          <el-button type="primary" @click="search()">查询</el-button>
        </el-form-item>
      </div>
      </el-form>
    </div>
    <div class="sys-table">
      <el-table border  @sort-change="sortChange"
        @row-click="clickRow"
        ref="tb"
        :data="tableData"
        :header-cell-style="{fontWeight: 'normal', textAlign: 'center', backgroundColor: '#eceff4', color: '#222'}"
        @selection-change="handleSelectionChange"
        v-loading="pictLoading"
      >
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column align="center" label="任务单号" width="160px" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-link type="primary" @click="openDetails(scope.row)">{{scope.row.workOrderNo}}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="reventStatusName" align="center" label="任务状态"></el-table-column>
        <el-table-column prop="deviceSerialno" align="center" label="设备编号" show-overflow-tooltip></el-table-column>
        <el-table-column prop="deviceName" label="设备名称" align="center" show-overflow-tooltip></el-table-column>
        <el-table-column prop="deviceModel" align="center" label="规格型号" show-overflow-tooltip></el-table-column>
        <el-table-column prop="reventLevelName" align="center" label="故障等级"></el-table-column>
        <el-table-column prop="reventTypeName" align="center" label="故障类型"></el-table-column>
        <el-table-column prop="createUserName" align="center" label="报修人" show-overflow-tooltip></el-table-column>
        <el-table-column prop="engineerDeptName" align="center" label="维修部门" show-overflow-tooltip></el-table-column>
        <el-table-column prop="engineerUserName" align="center" label="维修责任人" show-overflow-tooltip></el-table-column>
        <el-table-column sortable="custom"  prop="createTime" align="center" label="报修时间" width="124" show-overflow-tooltip></el-table-column>
      </el-table>
    </div>
    <div class="sys-pagination">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="search_data.pageno"
        :page-sizes="pageSizes"
        :page-size="search_data.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
    <DialogChooseSingleUser :visible.sync="chooseUserVisible" @change="getUser"></DialogChooseSingleUser>
  </div>
</template>

<script>
import { formatDateTime } from "@/utils/tools.js";
import DialogChooseSingleUser from "../../components/System/dialogChooseSingleUser";
export default {
  components: {
    DialogChooseSingleUser
  },
  name: "repair_index_unhandle",
  data() {
    return {
        depOptions: [],
        selectDeptId:[],
      total: 0, //总条数
      pageSizes: [10, 20, 50], //每页展示多少条
      search_data: {
        pageno: 1,
        pagesize: 10,
        startTime: "",
        endTime: "",
        time: "",
        reventStatus: "",
        heldPerson: "",
        createBy: "",
        tabType:0,
        title: ""
      },

      repairTime: "",
      typeList: [], //任务类型
      levels: [], //任务等级
      statusList: [{
        name:'待处理',
        value: 0,
      },{
        name:'待验收',
        value: 1,
      },{
        name:'已验收',
        value: 2,
      },{
        name:'超期未处理',
        value: 3,
      },{
        name:'暂存',
        value: 4,
      }], //任务状态
      getUserList: [], //用户
      resultList: [], //验收结果
      depts: [],
      btnDelDisabled: true,
      btnOtherDisabled: true,
      rowIds: [],
      tableData: [],
      dialogVisible: false,
      pictLoading: false,
      chooseUserVisible: false
    };
  },
  created() {
    var _this = this;
    document.onkeydown = e => {
      if (e.key === "Enter") {
        _this.search()
      }
    }
  },
  mounted() {
    this.getList();
    this.initData();
  },
  methods: {
    sortChange({ column, prop, order }){
      let j={ column, prop, order };
      let order_=j.order=="ascending"?'asc':'desc'
      this.$set(this.search_data,'sort',j.prop)
      this.$set(this.search_data,'order',order_)
      this.getList();
    },
      //根据当前id,获取一条树枝上的所有id数据
      treeFindPath (tree, func, path = []) {
          if (!tree) return []
          for (const data of tree) {
              path.push(data.id)
              if (func(data)) return path
              if (data.children) {
                  const findChildren = this.treeFindPath(data.children, func, path)
                  if (findChildren.length) return findChildren
              }
              path.pop()
          }
          return []
      },
      //当选择器选项没有下一级时，将children设置为undefined，就能选则该项了
      setDeptList(tree){
          for (const data of tree) {
              if(!data.hasChildren){
                  data.children=undefined;
              }else{
                  this.setDeptList(data.children)
              }
          }

      },

// 选择部门
      handleChange:function(value){
          this.search_data.deptIdQuery=value.length>=1?value[value.length-1]:'';
          this.selectDeptId=value;
      },
    clickRow(row) {
      this.$refs.tb.toggleRowSelection(row);
    },
    initData() {
      Promise.all([
        this.$api.commonAPI.getUsers(),
        this.$api.dictAPI.getDictsByType("task_type"),
        this.$api.dictAPI.getDictsByType("task_level"),
        this.$api.dictAPI.getDictsByType("task_status"),
        this.$api.dictAPI.getDictsByType("acceptance_result"),
        this.$api.commonAPI.getDeptsTree()
      ])
        .then(([r1, r2, r3, r4, r5, r6]) => {
          if (r1.code === 0) {
            this.getUserList = r1.datas;
          }
          if (r2.code === 0) {
            this.typeList = r2.datas;
          }
          if (r3.code === 0) {
            this.levels = r3.datas;
          }
          // if (r4.code === 0) {
          //   this.statusList = r4.datas;
          //   this.statusList.push({
          //     id: 999, name: "超时未处理"
          //   })
          // }
          if (r5.code === 0) {
            this.resultList = r5.datas;
          }
          if (r6.code === 0) {
              this.depOptions=r6.data.children;
              this.setDeptList(this.depOptions);
            // this.depts = r6.datas;
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    /**
     * 获取故障列表
     */
    getList() {
      if (this.repairTime) {
        this.search_data.startTime = formatDateTime(this.repairTime[0]);
        this.search_data.endTime = formatDateTime(this.repairTime[1]);
      } else {
        this.search_data.startTime = "";
        this.search_data.endTime = "";
      }
      this.pictLoading = true;
      this.$api.repairCheckAPI
        .eventList(this.search_data)
        .then(res => {
          this.pictLoading = false;
          if (res.data) {
            this.total = res.data.totalRows;
            this.tableData = res.data.datas ? res.data.datas : [];
          } else {
            this.total = 0;
            this.tableData = [];
          }
        })
        .catch(r => {
          console.log(r);
        });
    },
    /**
     * 查询
     */
    search() {
      this.search_data.pageno = 1;
      this.getList();
    },
    // 上下分页
    handleCurrentChange(val) {
      this.search_data.pageno = val;
      this.getList();
    },
    // 每页显示多少条
    handleSizeChange(val) {
      this.search_data.pagesize = val;
      this.getList();
    },
    /**
     * 新增
     */
    add() {
      this.$router.push({
        path: "/repair/add",
        query: {
          s: this.$route.path,
          t: Date.now()
        }
      });
    },
    /**
     * 获取用户信息
     */
    getUser(data) {
      let item = this.rowIds[0];
      let userid = data.id;
      let eventid = item.reventId;
      this.$confirm("确认将维修单转派给" + data.name + "吗?", "提示", {
        type: "warning"
      }).then(() => {
        this.$api.repairCheckAPI
          .reventTurnToSend({ eventId: eventid, userId: userid })
          .then(res => {
            if (res.code === 0) {
              this.$message({
                message: res.msg,
                type: "success"
              });
              this.getList();
            } else {
              this.$message({
                message: res.msg ? "转派失败，请重试" : res.msg,
                type: "error"
              });
            }
          })
          .catch(error => {
            this.$message({
              message: "转派失败，请重试",
              type: "error"
            });
          });
      });
    },
    /**
     * 转派
     */
    send() {
      let item = this.rowIds[0];
      if (item.reventStatusId !== 56) {
        this.$alert("维修单已在处理进程中，您无法转派该维修单！", "提示", {
          type: "warning"
        });
        return;
      }
      let id = item.id;
      this.chooseUserVisible = true;
    },
    /**
     *查看明细
     */
    openDetails(r) {
      this.$router.push({
        path: "/repair/add",
        query: { id: r.reventId, t: Date.now(),status:r.reventStatusId }
      });
      // if (r.reventStatusId === 146) {
      //
      // } else {
      //   this.$router.push({
      //     path: "/repair/detail",
      //     query: { id: r.reventId, t: Date.now() }
      //   });
      // }
    },

    /**
     * 完成验收
     */
    complete() {
      let item = this.rowIds[0];
      if (item.reventStatusId === 58) {
        this.$alert("维修单已完成验收，您无法再次验收该维修单！", "提示", {
          type: "warning"
        });
        return;
      }
      let id = item.reventId;
      this.$router.push({
        path: "/repair/check",
        query: { id: id, t: Date.now() }
      });
    },
    /**
     * 维修处理
     */
    repair() {
      let item = this.rowIds[0];
      if (item.reventStatusId === 58) {
        this.$alert("维修单已完成验收，您无法再次处理该维修单！", "提示", {
          type: "warning"
        });
        return;
      }
      let id = item.reventId;
      this.$router.push({
        path: "/repair/handle",
        query: { id: id, t: Date.now() }
      });
    },
    /**
     * 删除
     */
    remove() {
      let ids = [];
      this.rowIds.forEach(item => {
        ids.push(item.reventId);
      });
      let params = { ids: ids };
      this.$confirm("确认删除选中的维修单据吗?", "提示", {
        type: "warning"
      }).then(() => {
        this.$api.repairCheckAPI
          .batchRemove(params)
          .then(res => {
            if (res.code === 0) {
              this.$message({
                message: res.msg,
                type: "success"
              });
              this.getList();
            } else {
              this.$message({
                message: res.msg ? res.msg :"删除失败，请重试" ,
                type: "error"
              });
            }
          })
          .catch(error => {
            this.$message({
              message: "删除失败，请重试",
              type: "error"
            });
          });
      });
    },
    /**
     * 处理选中
     */
    handleSelectionChange(val) {
      this.rowIds = val;
      this.setBtn(val);
    },
    /**
     * 控件操作按钮状态
     */
    setBtn(val) {
      let isFlag = true;
      let isDelFlag = true;
      if (val.length > 0) {
        isDelFlag = false;
        if (val.length == 1) {
          isFlag = false;
        }
      } else {
        isFlag = true;
        isDelFlag = true;
      }
      this.btnDelDisabled = isDelFlag;
      this.btnOtherDisabled = isFlag;
    }
  }
};
</script>


<style scoped>
.flex {
  display: flex;
}
.sys-form {
  padding: 0px;
}
.sys-form .form-inline {
  width: 33.33%;
}
.sys-form .form-inline .el-input,
.sys-form .form-inline .el-select .el-input {
  width: 100%;
}
</style>
<style >
.repair-box .sys-form .form-inline .el-select .el-input {
  width: 100%;
}
.repair-box .el-rate {
  margin-top: 10px;
}
</style>
