<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.type" class="input-width" placeholder="请选择计划类型">
          <el-option v-for="item in typeList" :key="item.id" :label="item.label" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="周计划" v-if="dataForm.type===2" prop="weeks" :rules="[{validator: validateNotEmpty, errorMessage: '周计划不能为空', required: dataForm.type===2}]">
        <el-select v-model="dataForm.weeks" class="input-width" multiple placeholder="请选择周计划" clearable>
          <el-option
              v-for="item in weekList"
              :key="item.id"
              :label="item.label"
              :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="月计划" v-if="dataForm.type===3" prop="months" :rules="[{validator: validateNotEmpty, errorMessage: '月计划不能为空', required: dataForm.type===3}]">
        <el-select v-model="dataForm.months" class="input-width" multiple placeholder="请选择月计划" clearable>
          <el-option
              v-for="item in monthList"
              :key="item"
              :label="item"
              :value="item">
          </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="beginDate">
        <el-date-picker v-model="dataForm.beginDate" class="input-width" placeholder="请选择计划执行开始日期" type="date" :picker-options="beginDateMax" value-format="timestamp"></el-date-picker>
      </el-form-item>

      <el-form-item label="计划执行结束日期" prop="endDate">
        <el-date-picker v-model="dataForm.endDate" class="input-width" placeholder="请选择计划执行结束日期，空代表永不结束" type="date" :picker-options="beginDateMin" value-format="timestamp"></el-date-picker>
      </el-form-item>

      <el-form-item label="任务执行时间" prop="timeRange">
        <el-time-picker
            v-model="dataForm.timeRange"
            class="input-width"
            end-placeholder="任务执行结束时间"
            format="HH:mm"
            is-range
            placeholder="请选择任务执行时间"
            range-separator="至"
            start-placeholder="任务执行开始时间"
            value-format="timestamp">
        </el-time-picker>
      </el-form-item>

      <el-form-item label="备注" prop="remark">
        <el-input v-model.trim="dataForm.remark" class="input-width" clearable maxlength="512" placeholder="请输入备注"></el-input>
      </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: "UpkeepPlanEdit",
  data() {
    const defaultStartTime = new Date(dateFormat("yyyy/MM/dd 00:00:00", new Date())).getTime();
    const defaultEndTime = new Date(dateFormat("yyyy/MM/dd 23:59:59", new Date())).getTime();
    return {
      id: undefined, // 数据id
      dataForm: {
        id: undefined, // 计划id
        routeId: undefined, // 检查路线id
        name: undefined, // 名称
        type: undefined, // 类型 1日计划、2周计划、3月计划
        runModel: undefined, // 执行模式 1其中一人、2每人分别
        beginDate: undefined, // 计划执行开始日期
        endDate: undefined, // 计划执行结束日期，空代表永不结束
        timeRange: [defaultStartTime, defaultEndTime], // 任务执行时间
        beginTime: defaultStartTime, // 任务执行开始时间
        endTime: defaultEndTime, // 任务执行结束时间
        weeks: undefined, // 周计划 [1-7]
        months: undefined, // 月计划 [1-31]
        remark: undefined, // 备注
        executors: [], // 执行人列表
      },
      beginDateMax: {
        disabledDate: (time) => {
          return time < new Date(dateFormat("yyyy/MM/dd 00:00:00", new Date())).getTime() || (this.dataForm.endDate && time > this.dataForm.endDate);
        }
      },
      beginDateMin: {
        disabledDate: (time) => {
          return time < this.dataForm.beginDate;
        }
      },
      defaultStartTime,
      defaultEndTime,
      typeList: [{id: 1, label: "日计划"}, {id: 2, label: "周计划"}, {id: 3, label: "月计划"}], // 计划类型列表
      runModelList: [{id: 1, label: "其中一人"}, {id: 2, label: "每人分别"}], // 计划执行模式列表
      weekList: [{id: 1, label: "周一"}, {id: 2, label: "周二"}, {id: 3, label: "周三"}, {id: 4, label: "周四"}, {id: 5, label: "周五"}, {id: 6, label: "周六"}, {id: 7, label: "周日"}], // 周计划列表
      monthList: [], // 月计划列表
      routeList: [], // 路线列表
      userList: [], // 用户列表

      dataRules: {
        'routeId': [{validator: validateNotEmpty, errorMessage: "检查路线不能为空", required: true, trigger: 'change'}],
        'name': [{validator: validateNotEmpty, errorMessage: "名称不能为空", required: true, trigger: 'blur'}],
        'type': [{validator: validateNotEmpty, errorMessage: "类型不能为空", required: true, trigger: 'change'}],
        'runModel': [{validator: validateNotEmpty, errorMessage: "执行模式不能为空", required: true, trigger: 'change'}],
        'beginDate': [{validator: validateNotEmpty, errorMessage: "计划执行开始日期不能为空", required: true, trigger: 'blur'}],
        '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 = this.defaultStartTime;
        this.dataForm.endTime = this.defaultEndTime;
      }
    },
    'dataForm.type'(value) {
      if (value === 1) {
        this.dataForm.weeks = undefined;
        this.dataForm.months = undefined;
      } else if (value === 2) {
        this.dataForm.months = undefined;
      } else if (value === 3) {
        this.dataForm.weeks = undefined;
      }
    },
    'dataForm.beginData'(value) {
      if (value) {
        this.$refs["endDate"].set
        this.dataForm.endDate = undefined;
        this.dataForm.months = undefined;
      } else if (value === 2) {
        this.dataForm.months = undefined;
      } else if (value === 3) {
        this.dataForm.weeks = undefined;
      }
    }
  },

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

  methods: {
    validateNotEmpty,
    // 初始化数据
    initData() {
      for (let i = 1; i < 32; i++) {
        this.monthList.push(i);
      }
      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) {
          let dataForm = JSON.parse(JSON.stringify(this.dataForm));
          dataForm.weeks = dataForm.weeks && JSON.stringify(dataForm.weeks);
          dataForm.months = dataForm.months && JSON.stringify(dataForm.months);
          if (this.id) { // 更新
            this.$axios.put('/v1/upkeep/plan/update', dataForm).then(() => {
              this.$message.success("更新成功！");
              this.$eventBus.$emit("UpkeepPlanUpdate");
              this.onCancel();
            });
          } else { // 添加
            this.$axios.post('/v1/upkeep/plan/add', dataForm).then(() => {
              this.$message.success("保存成功！");
              this.$eventBus.$emit("UpkeepPlanAdd");
              this.onCancel();
            });
          }
        }
      });
    },

    // 获取详情
    getDetail(id) {
      this.$axios.get(`/v1/upkeep/plan/query/${id}`).then(data => {
        this.routeList = [data.route];
        this.userList = data.executors;
        data.timeRange = [data.beginTime, data.endTime];
        data.routeId = data.route.id;
        data.weeks = data.weeks && JSON.parse(data.weeks);
        data.months = data.months && JSON.parse(data.months);
        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>
