<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="请选择计划类型" @change="onTypeChange">
          <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!==1" prop="days" :rules="[{validator: validateNotEmpty, errorMessage: '计划不能为空', required: dataForm.type!==1}]">
        <el-select v-model="dataForm.days" filterable class="input-width" multiple placeholder="请选择计划" clearable>
          <el-option
              v-for="item in dayList"
              :key="item.id"
              :label="item.label"
              :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="beginDate">
        <el-date-picker v-model="dataForm.beginDate" class="input-width" placeholder="请选择计划执行开始日期" type="date" :picker-options="beginDateRange" 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="endDateRange" 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: "PatrolPlanEdit",
  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: 1, // 类型 1:日计划 2:周计划 3:月计划 4:季计划 5:半年计划 6:年计划
        runModel: undefined, // 执行模式 1其中一人、2每人分别
        beginDate: undefined, // 计划执行开始日期
        endDate: undefined, // 计划执行结束日期，空代表永不结束
        timeRange: [defaultStartTime, defaultEndTime], // 任务执行时间
        beginTime: defaultStartTime, // 任务执行开始时间
        endTime: defaultEndTime, // 任务执行结束时间
        days: undefined, // 计划包含的天 [1-365]
        remark: undefined, // 备注
        executors: [], // 执行人列表
      },
      beginDateRange: {
        disabledDate: (time) => {
          return time < new Date(dateFormat("yyyy/MM/dd 00:00:00", new Date())).getTime() || (this.dataForm.endDate && time > this.dataForm.endDate);
        }
      },
      endDateRange: {
        disabledDate: (time) => {
          return time < (this.dataForm.beginDate || new Date(dateFormat("yyyy/MM/dd 00:00:00", new Date())).getTime());
        }
      },
      defaultStartTime,
      defaultEndTime,
      typeList: [{id: 1, label: "日计划"}, {id: 2, label: "周计划"}, {id: 3, label: "月计划"}, {id: 4, label: "季计划"}, {id: 5, label: "半年计划"}, {id: 6, label: "年计划"}], // 计划类型列表
      runModelList: [{id: 1, label: "其中一人"}, {id: 2, label: "每人分别"}], // 计划执行模式列表
      dayList: [], // 日期
      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;
      }
    }
  },

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

  methods: {
    validateNotEmpty,
    // 初始化数据
    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) {
          let dataForm = JSON.parse(JSON.stringify(this.dataForm));
          dataForm.days = dataForm.days && JSON.stringify(dataForm.days);
          if (this.id) { // 更新
            this.$axios.put('/v1/patrol/plan/update', dataForm).then(() => {
              this.$message.success("更新成功！");
              this.$eventBus.$emit("PatrolPlanUpdate");
              this.onCancel();
            });
          } else { // 添加
            this.$axios.post('/v1/patrol/plan/add', dataForm).then(() => {
              this.$message.success("保存成功！");
              this.$eventBus.$emit("PatrolPlanAdd");
              this.onCancel();
            });
          }
        }
      });
    },

    // 获取详情
    getDetail(id) {
      this.$axios.get(`/v1/patrol/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.days = data.days && JSON.parse(data.days);
        data.executors = data.executors.map(item => item.id);
        this.dataForm = data;
      })
    },

    // 计划类型改变
    onTypeChange(value) {
      this.dataForm.days = undefined;
      this.dayList=[];
      if (value === 2) {
        this.dayList = [{id: 1, label: "周一"}, {id: 2, label: "周二"}, {id: 3, label: "周三"}, {id: 4, label: "周四"}, {id: 5, label: "周五"}, {id: 6, label: "周六"}, {id: 7, label: "周日"}];
      } else if (value === 3) {
        for (let i = 1; i < 32; i++) {
          this.dayList.push({id: i, label: i});
        }
      } else if (value === 4) {
        for (let i = 1; i < 94; i++) {
          this.dayList.push({id: i, label: i});
        }
      } else if (value === 5) {
        for (let i = 1; i < 187; i++) {
          this.dayList.push({id: i, label: i});
        }
      } else if (value === 6) {
        for (let i = 1; i < 366; i++) {
          this.dayList.push({id: i, label: i});
        }
      }
    },

    // 远程搜索路线
    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: 400px;
  }
}
</style>
