<template>
  <!-- 保养执行列表页 -->
  <div class="knowledge-box">
    <div class="sys-operate">
      <!-- <el-button type="primary" @click="add()">增加</el-button>
      <el-button type="primary" @click="remove()" :disabled="btnDelDisabled">删除</el-button>
      <el-button type="primary" @click="execution()" :disabled="btnOtherDisabled">保养执行</el-button> -->
      <el-button type="primary" v-has="'upkeep:execution:complete'" @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="设备名称" class="form_item-inline" style="width:33%">
            <el-input v-model="search_data.deviceName" placeholder="请填写设备名称"></el-input>
          </el-form-item>
          <el-form-item label="计划时间" class="form_item-inline" style="width:34%">
            <el-date-picker v-model="planTime" type="daterange" clearable range-separator="-" start-placeholder="开始日期"
              end-placeholder="结束日期"></el-date-picker>
          </el-form-item>
          <!-- <el-form-item label="保养状态">
          <el-select v-model="search_data.resultId" clearable 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="负责人">
          <el-select v-model="search_data.engineer_id" filterable clearable placeholder="请选择">
            <el-option
              v-for="item in getUserList"
             :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </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" @row-click="clickRow" ref="tb"
        :summary-method="getSummaries" show-summary :data="tableData" @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="work_orderNo" width="160" align="center" label="保养单号" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-link type="primary" @click="viewDetail(scope.row)">{{
              scope.row.work_orderNo
            }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="planName" align="center" label="保养名称" show-overflow-tooltip></el-table-column>
        <el-table-column prop="device_serialno" align="center" label="设备编号" show-overflow-tooltip></el-table-column>
        <el-table-column prop="deviceName" label="设备名称" show-overflow-tooltip></el-table-column>
        <el-table-column prop="deviceModelas" align="center" width="50" label="规格型号"
          show-overflow-tooltip></el-table-column>
        <el-table-column prop="dept_name" align="center" label="保养部门" show-overflow-tooltip></el-table-column>
        <el-table-column prop="username" align="center" label="保养负责人" show-overflow-tooltip></el-table-column>
        <el-table-column sortable="custom" prop="start_time" align="center" label="计划开始时间" width="124"
          show-overflow-tooltip></el-table-column>
        <el-table-column sortable="custom" prop="end_time" align="center" label="计划结束时间" width="124"
          show-overflow-tooltip></el-table-column>
        <!-- <el-table-column prop="man_hour" align="center" label="保养工时（小时）" width="60"
          show-overflow-tooltip></el-table-column>
        <el-table-column prop="manhourCost" align="center" label="保养工时费（元）" width="60"
          show-overflow-tooltip></el-table-column>
        <el-table-column prop="cost" align="center" label="保养材料费（元）" width="60" show-overflow-tooltip></el-table-column>
        <el-table-column prop="totalCost" align="center" label="保养费（元）" width="60"
          show-overflow-tooltip></el-table-column> -->
        <el-table-column prop="result_name" align="center" label="保养状态" show-overflow-tooltip></el-table-column>
        <el-table-column sortable="custom" prop="recordResultId" align="center" label="验收结果" width="124">
          <template slot-scope="scope">
            <span>{{ scope.row.record_result }}</span>
          </template>
        </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>
  </div>
</template>

<script>
import { formatDateTime } from "@/utils/tools.js";
export default {
  name: "upkeep_execution_unaccept",
  data() {
    return {
      total: 0, //总条数
      pageSizes: [10, 20, 50], //每页展示多少条
      search_data: {
        pageno: 1,
        pagesize: 10,
        singleStatus: 57
      },

      planTime: "",

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

      btnDelDisabled: true,
      btnOtherDisabled: true,
      rowIds: [],
      tableData: [],
      dialogVisible: false,
      pictLoading: false,
      totalCost: 0,
      totalManHour: 0,
      totalUpkeepCost: 0,
      totalManhourCost: 0
    };
  },
  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();
    },
    clickRow(row) {
      this.$refs.tb.toggleRowSelection(row);
    },
    initData() {
      Promise.all([
        this.$api.commonAPI.getUsers(),
        this.$api.dictAPI.getDictsByType("task_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.start_time = formatDateTime(this.planTime[0]);
        this.search_data.end_time = formatDateTime(this.planTime[1]);
      } else {
        this.search_data.start_time = "";
        this.search_data.end_time = "";
      }
      this.pictLoading = true;
      this.$api.upkeepPlanAPI
        .addValidRecords(this.search_data)
        .then(res => {
          this.pictLoading = false;
          if (res.data) {
            this.total = res.data.totalRows;
            this.tableData = res.data.datas ? res.data.datas : [];
            this.totalCost = res.data.totalCost;
            this.totalManHour = res.data.totalManHour;
            this.totalManhourCost = res.data.totalManhourCost;
          } else {
            this.total = 0;
            this.tableData = [];
          }
        })
        .catch(r => {
          console.log(r);
        });
    },
    /**
     * 计算合计
     */
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      sums[1] = "总计";
      sums[10] = this.totalManHour;
      sums[11] = this.totalManhourCost;
      sums[12] = this.totalCost;
      sums[13] = this.totalUpkeepCost;
      return sums;
    },
    /**
     * 查询
     */
    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: "/upkeep/execution_add",
        query: {
          t: Date.now()
        }
      });
    },
    /**
     * 保养执行
     */
    execution() {
      let item = this.rowIds[0];
      if (item.result === 58) {
        this.$alert("保养已完成验收，您无法再次执行该保养！", "提示", {
          type: "warning"
        });
        return;
      }
      let id = item.plan_id;
      this.$router.push({
        path: "/upkeep/execution_add",
        query: { planid: item.plan_id, id: item.id, t: Date.now() }
      });
    },
    /**
     * 查看明细
     */
    viewDetail(r) {
      this.$router.push({
        path: "/upkeep/execution_detail",
        query: { id: r.id, t: Date.now() }
      });
    },
    /**
     *查看明细
     */
    openDetails(r) {
      this.$router.push({
        path: "/upkeep/detail",
        query: { id: r.id, t: Date.now() }
      });
    },

    /**
     * 完成验收
     */
    complete() {
      let item = this.rowIds[0];
      if (item.result === 58) {
        this.$alert("保养已完成验收，您无法再次验收该保养！", "提示", {
          type: "warning"
        });
        return;
      }
      let id = item.id;
      this.$router.push({
        path: "/upkeep/execution_check",
        query: { id: id, t: Date.now() }
      });
    },
    /**
     * 删除
     */
    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.upkeepPlanAPI
          .batchRemove(params)
          .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"
            });
          });
      });
    },
    /**
     * 处理选中
     */
    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>
