<template>
  <!-- 巡检计划 -->
  <div class="sys-box knowledge-box">
    <div class="sys-operate">
      <el-button type="primary" v-has="'inspection:plan:add'" @click="add()"
        >新增</el-button
      >
      <el-button
        type="primary"
        v-has="'inspection:plan:remove'"
        @click="remove()"
        :disabled="btnDelDisabled"
        >删除</el-button
      >
      <el-button
        type="primary"
        v-has="'inspection:plan:startUsing'"
        @click="startUsing()"
        :disabled="btnDelDisabled"
        >启用</el-button
      >
      <el-button
        type="primary"
        v-has="'inspection:plan:forbidden'"
        @click="forbidden()"
        :disabled="btnDelDisabled"
        >禁用</el-button
      >
      <!-- <el-button type="primary" @click="importPlan()">导入</el-button>
      <el-button type="primary" @click="exportPlan()">导出</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
              placeholder="计划名称"
              v-model="search_data.planName"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="设备名称"
            style="width:22%"
            class="form_item-inline"
          >
            <el-input
              placeholder="设备名称"
              v-model="search_data.sbmc"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="计划状态"
            style="width:22%"
            class="form_item-inline"
          >
            <el-select
              clearable
              v-model="search_data.status"
              placeholder="计划状态"
            >
              <el-option
                v-for="item in statusList"
                :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 clearable v-model="search_data.engineerId" filterable placeholder="请选择">
            <el-option
              v-for="item in getUserList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select> -->
            <btn-input
              :valueText.sync="search_data.engineerName"
              :valueId.sync="search_data.engineerId"
              :chooseVisible.sync="chooseUserVisible"
            ></btn-input>
          </el-form-item>
          <el-form-item
            label="计划时间"
            style="width:34%"
            class="form_item-inline"
          >
            <el-date-picker
              v-model="planTime"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </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"
        v-loading="pictLoading"
        :data="tableData"
        @row-click="clickRow"
        ref="tb"
        @selection-change="handleSelectionChange"
        :header-cell-style="{
          fontWeight: 'normal',
          textAlign: 'center',
          backgroundColor: '#eceff4',
          color: '#222'
        }"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
        ></el-table-column>
        <el-table-column prop="workOrderNo" align="center" label="计划单号">
          <template slot-scope="scope">
            <el-link type="primary" @click="viewDetail(scope.row)">{{
              scope.row.workOrderNo
            }}</el-link>
          </template>
        </el-table-column>
        <el-table-column
          prop="planName"
          label="计划名称"
          align="center"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          sortable="custom"
          width="110"
          prop="statusId"
          align="center"
          label="计划状态"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.statusName }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="deptName"
          align="center"
          label="巡检部门"
        ></el-table-column>
        <el-table-column
          prop="userName"
          align="center"
          label="巡检人"
        ></el-table-column>
        <el-table-column
          sortable="custom"
          prop="startTime"
          align="center"
          label="计划开始时间"
          width="200"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          sortable="custom"
          prop="endTime"
          align="center"
          label="计划结束时间"
          width="200"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="content"
          align="center"
          label="备注"
          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 btnInput from "@/components/btnInput.vue";
import dialogChooseSingleUser from "@/components/System/dialogChooseSingleUser";
export default {
  name: "inspection_plan",
  components: {
    btnInput,
    dialogChooseSingleUser
  },
  data() {
    return {
      total: 0, //总条数
      pageSizes: [10, 20, 50], //每页展示多少条
      search_data: {
        pageno: 1,
        pagesize: 10
      },

      planTime: "",

      statusList: [], //计划状态
      getUserList: [], //用户

      btnDelDisabled: true,
      btnOtherDisabled: true,
      chooseUserVisible: false,
      rowIds: [],
      tableData: [],
      dialogVisible: false,
      pictLoading: false
    };
  },
  created() {
    var _this = this;
    document.onkeydown = e => {
      if (e.key === "Enter") {
        _this.search();
      }
    };
  },
  mounted() {
    this.getList();
    this.initData();
  },
  methods: {
    /**
     * 获取选择的负责人
     */
    getUser(val) {
      if (val) {
        this.$set(this.search_data, "engineerName", val.name);
        this.$set(this.search_data, "engineerId", val.id);
      } else {
        this.$set(this.search_data, "engineerName", "");
        this.$set(this.search_data, "engineerId", "");
      }
    },
    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();
    },
    clickRow(row) {
      this.$refs.tb.toggleRowSelection(row);
    },
    /**
     * 启用
     */
    startUsing() {
      let ids = [];
      this.rowIds.forEach(item => {
        ids.push(item.id);
      });
      this.$confirm("确认启用选中的巡检计划吗?", "提示", {
        type: "warning"
      }).then(() => {
        this.$api.patroPlanAPI
          .startUsing({ ids: ids })
          .then(res => {
            console.log(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"
            });
          });
      });
    },
    /**
     * 禁用
     */
    forbidden() {
      let ids = [];
      this.rowIds.forEach(item => {
        ids.push(item.id);
      });
      this.$confirm("确认禁用选中的巡检计划吗?", "提示", {
        type: "warning"
      }).then(() => {
        this.$api.patroPlanAPI
          .forbidden({ ids: ids })
          .then(res => {
            console.log(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"
            });
          });
      });
    },
    initData() {
      Promise.all([
        this.$api.commonAPI.getUsers(),
        this.$api.dictAPI.getDictsByType("plan_status")
      ])
        .then(([r1, r2]) => {
          if (r1.code === 0) {
            this.getUserList = r1.datas;
          }
          if (r2.code === 0) {
            this.statusList = r2.datas;
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    /**
     * 获取列表
     */
    getList() {
      if (this.planTime) {
        this.search_data.startTime = formatDateTime(this.planTime[0]);
        this.search_data.endTime = formatDateTime(this.planTime[1]);
      } else {
        this.search_data.startTime = "";
        this.search_data.endTime = "";
      }
      this.pictLoading = true;
      this.$api.patroPlanAPI
        .planList(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: "/inspection/plan_add",
        query: {
          t: Date.now()
        }
      });
    },
    /**
     * 查看明细
     */
    viewDetail(r) {
      if (r.statusId === 146) {
        this.$router.push({
          path: "/inspection/plan_add",
          query: { id: r.id, t: Date.now() }
        });
      } else {
        this.$router.push({
          path: "/inspection/plan_add",
          query: { id: r.id, t: Date.now() }
        });
      }
    },
    /**
     * 导入
     */
    importPlan() {},
    /**
     * 导出
     */
    exportPlan() {},
    /**
     *查看明细
     */
    openDetails(r) {
      this.$router.push({
        path: "/inspection/detail",
        query: { id: r.id, t: Date.now() }
      });
    },

    /**
     * 删除POST /apis/patrolPlan/batcnRemovePlan
     */
    remove() {
      let ids = [];
      this.rowIds.forEach(item => {
        ids.push(item.id);
      });
      // const ids = this.rowIds.map(item => item.id).toString();
      let params = { ids: ids };
      this.$confirm("确认删除选中的巡检计划吗?", "提示", {
        type: "warning"
      }).then(() => {
        this.$api.patroPlanAPI
          .batcnRemovePlan(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></style>
