<template>
  <div class="app-container">
    <page-header :content="id?'编辑':'添加'"></page-header>
    <el-form ref="dataForm" :model="dataForm" :rules="dataRules" label-width="140px">
      <el-form-item label="任务名称" prop="name">
        <el-input v-model.trim="dataForm.name" class="input-width" clearable maxlength="32" placeholder="请输入任务名称"></el-input>
      </el-form-item>

      <el-form-item label="检查路线" prop="routeId">
        <el-select
            v-model="dataForm.routeId"
            :remote-method="remoteRouteMethod"
            class="input-width"
            clearable
            filterable
            placeholder="请选择检查路线"
            remote>
          <el-option
              v-for="item in routeList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="执行模式" prop="type">
        <el-select v-model="dataForm.runModel" class="input-width" placeholder="请选择执行模式">
          <el-option v-for="item in runModelList" :key="item.id" :label="item.label" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="任务执行时间范围" prop="timeRange">
        <el-date-picker
            v-model="dataForm.timeRange"
            :picker-options="beginTime"
            class="input-width"
            format="yyyy-MM-dd HH:mm"
            end-placeholder="任务执行结束时间"
            range-separator="-"
            start-placeholder="任务执行结束时间"
            type="datetimerange"
            value-format="timestamp">
        </el-date-picker>
      </el-form-item>

      <el-form-item label="执行人" prop="executors">
        <el-select
            v-model="dataForm.executors"
            :remote-method="remoteUserMethod"
            class="input-width"
            clearable
            filterable
            multiple
            placeholder="请选择执行人"
            remote>
          <el-option
              v-for="item in userList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <page-footer showConfirm width="800px" @cancel="onCancel" @confirm="onConfirm"></page-footer>
  </div>
</template>

<script>

import {validateNotEmpty} from "@/utils/validate";
import {dateFormat} from "@/utils/dateUtil";

export default {
  name: "UpkeepTaskEdit",
  data() {
    return {
      id: undefined, // 数据id
      dataForm: {
        id: undefined, // 任务id
        routeId: undefined, // 检查路线id
        name: undefined, // 名称
        runModel: undefined, // 执行模式 1其中一人、2每人分别
        timeRange: [undefined, undefined], // 任务执行开始日期
        beginTime: undefined,
        endTime: undefined,
        executors: [], // 执行人列表
      },
      beginTime: {
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            const start = new Date().getTime();
            const end = new Date(dateFormat("yyyy/MM/dd 23:59:00", new Date())).getTime();
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '明天',
          onClick(picker) {
            const start = new Date(dateFormat("yyyy/MM/dd 00:00:00", Date.now() + 3600 * 1000 * 24)).getTime();
            const end = new Date(dateFormat("yyyy/MM/dd 23:59:00", Date.now() + 3600 * 1000 * 24)).getTime();
            picker.$emit('pick', [start, end]);
          }
        }],
        disabledDate: (time) => {
          return time < new Date(dateFormat("yyyy/MM/dd 00:00:00", new Date())).getTime();
        }
      },
      runModelList: [{id: 1, label: "其中一人"}, {id: 2, label: "每人分别"}], // 任务执行模式列表
      routeList: [], // 路线列表
      userList: [], // 用户列表

      dataRules: {
        'routeId': [{validator: validateNotEmpty, errorMessage: "检查路线不能为空", required: true, trigger: 'change'}],
        'name': [{validator: validateNotEmpty, errorMessage: "名称不能为空", required: true, trigger: 'blur'}],
        'runModel': [{validator: validateNotEmpty, errorMessage: "执行模式不能为空", required: true, trigger: 'change'}],
        'timeRange': [{validator: validateNotEmpty, errorMessage: "任务执行时间不能为空", required: true, trigger: 'blur'}],
        'executors': [{validator: validateNotEmpty, errorMessage: "执行人列表不能为空", required: true, trigger: 'change'}],
      },
    }
  },

  watch: {
    'dataForm.timeRange'(value) {
      if (value) {
        this.dataForm.beginTime = value[0];
        this.dataForm.endTime = value[1];
      } else {
        this.dataForm.beginTime = undefined;
        this.dataForm.endTime = undefined;
      }
    },
  },

  mounted() {
    this.initData();
  },

  methods: {
    // 初始化数据
    initData() {
      this.id = this.$route.query.id;
      if (this.id) {
        this.getDetail(this.id);
      }
    },

    // 取消
    onCancel() {
      this.$router.back();
    },

    // 确认
    onConfirm() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.$axios.put('/v1/upkeep/task/update', this.dataForm).then(() => {
            this.$message.success("更新成功！");
            this.$eventBus.$emit("UpkeepTaskUpdate");
            this.onCancel();
          });
        }
      });
    },

    // 获取详情
    getDetail(id) {
      this.$axios.get(`/v1/upkeep/task/query/${id}`).then(data => {
        this.routeList = [data.route];
        this.userList = data.executors;
        data.timeRange = [data.beginTime, data.endTime];
        data.routeId = data.route.id;
        data.executors = data.executors.map(item => item.id);
        this.dataForm = data;
      })
    },

    // 远程搜索路线
    remoteRouteMethod(query) {
      if (query) {
        this.$axios.get("/v1/check/route/list/option", {params: {name: query}}, false).then((data) => {
          this.routeList = data;
        })
      }
    },

    // 远程搜索用户
    remoteUserMethod(query) {
      if (query) {
        this.$axios.get("/v1/system/user/list/option", {params: {keyword: query}}, false).then((data) => {
          this.userList = data;
        })
      }
    }
  },

}
</script>
<style lang="scss" scoped>
.app-container {
  .input-width {
    width: 500px;
  }
}
</style>
