<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="86px">
      <el-form-item label="条目名称" prop="detailName">
        <el-input
          v-model="queryParams.detailName"
          placeholder="请输入详细条目名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="节假日" prop="holidayName">
        <el-input
          v-model="queryParams.holidayName"
          placeholder="请输入节假日名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['calendarManagement:schoolCalendarDetail:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['calendarManagement:schoolCalendarDetail:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['calendarManagement:schoolCalendarDetail:remove']"
        >删除
        </el-button>
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="warning"-->
      <!--          plain-->
      <!--          icon="el-icon-download"-->
      <!--          size="mini"-->
      <!--          @click="handleExport"-->
      <!--          v-hasPermi="['calendarManagement:schoolCalendarDetail:export']"-->
      <!--        >导出-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-close"
          size="mini"
          @click="close">关闭
        </el-button>
      </el-col>
      <!--      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>-->
    </el-row>

    <el-table v-loading="loading" :data="schoolCalendarDetailList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="详细条目名称" min-width="150" align="center" prop="detailName"/>
      <el-table-column label="节假日名称" min-width="150" align="center" prop="holidayName"/>
      <el-table-column label="内容" min-width="180" align="center" prop="detailContent">
        <template slot-scope="scope">
          <span v-html="scope.row.detailContent"></span>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" min-width="140" align="center" prop="startTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" min-width="140" align="center" prop="endTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="120" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['calendarManagement:schoolCalendarDetail:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['calendarManagement:schoolCalendarDetail:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改校历详细条目对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="860px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="详细条目名称" prop="detailName">
          <el-input v-model="form.detailName" placeholder="请输入详细条目名称"/>
        </el-form-item>
        <el-form-item label="节假日名称" prop="holidayName">
          <el-input v-model="form.holidayName" placeholder="请输入节假日名称"/>
        </el-form-item>
        <el-row>
          <el-col :span="10">
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker clearable
                              v-model="form.startTime"
                              type="date"
                              style="width: 100%"
                              value-format="yyyy-MM-dd"
                              :picker-options="pickerOptionsStart"
                              placeholder="请选择开始时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker clearable
                              v-model="form.endTime"
                              type="date"
                              style="width: 100%"
                              value-format="yyyy-MM-dd"
                              :picker-options="pickerOptionsEnd"
                              placeholder="请选择结束时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="内容">
          <editor v-model="form.detailContent" :min-height="192"/>
        </el-form-item>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listSchoolCalendarDetailFull,
  getSchoolCalendarForSelecter,
  listSchoolCalendarDetail,
  getSchoolCalendarDetail,
  delSchoolCalendarDetail,
  addSchoolCalendarDetail,
  updateSchoolCalendarDetail
} from "@/api/smartSchool/calendarManagement/schoolCalendarDetail";

export default {
  name: "SchoolCalendarDetail",
  data() {
    return {
      //时间限制
      limitDate: {
        start: null,
        end: null
      },
      calendarId: undefined,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 校历详细条目表格数据
      schoolCalendarDetailList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      calendarName: undefined,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        calendarId: null,
        detailName: null,
        detailContent: null,
        startTime: null,
        endTime: null,
        holidayName: null,
        weekValue: null,
        weekName: null,
      },
      // 表单参数
      form: {},
      // 列信息
      columns: [
        {key: 0, label: `校历表id`, visible: true},
        {key: 1, label: `详细条目名称`, visible: true},
        {key: 2, label: `内容`, visible: true},
        {key: 3, label: `状开始时间态`, visible: true},
        {key: 4, label: `结束时间`, visible: true},
        {key: 5, label: `节假日名称`, visible: true},
        {key: 6, label: `星期数值`, visible: true},
        {key: 7, label: `星期`, visible: true},
        {key: 8, label: `操作`, visible: true},
      ],
      // 表单校验
      rules: {
        detailName: [
          {required: true, message: "详细条目名称不能为空", trigger: "blur"}
        ],
        startTime: [
          {required: true, message: "开始时间不能为空", trigger: "blur"}
        ],
        endTime: [
          {required: true, message: "结束时间不能为空", trigger: "blur"},
          {validator: this.checkEndTime, trigger: 'change'}
        ],
        weekValue: [
          {
            required: true,
            pattern: "[1-9]\\d*",
            message: "星期数值不合法", trigger: "blur"
          }

        ]
      },
      pickerOptionsStart: {
        disabledDate: (time) => {
          return (
            Date.parse(time) > Date.parse(this.limitDate.end) ||
            Date.parse(time) < Date.parse(this.limitDate.start) - 8.64e7
          )
        }
      },
      pickerOptionsEnd: {
        disabledDate: (time) => {
          return (
            Date.parse(time) > Date.parse(this.limitDate.end) ||
            Date.parse(time) < Date.parse(this.limitDate.start) - 8.64e7 ||
            Date.parse(time) < Date.parse(this.form.startTime) - 8.64e7
          )
        }
      },
    }
  },
  created() {
    this.calendarId = this.$route.query && this.$route.query.calendarId
    this.getList();
    this.getLimitDate()
  },

  methods: {
    //时间限制
    getLimitDate() {
      this.limitDate.start = this.$route.query && this.$route.query.limitStartDate;
      this.limitDate.end = this.$route.query && this.$route.query.limitEndDate;
      console.log(this.limitDate)
      console.log(Date.parse(this.limitDate.start))
    },
    /** 查询校历详细条目列表 */
    getList() {
      this.loading = true;
      listSchoolCalendarDetail(this.queryParams, this.calendarId).then(response => {
        console.log(response)
        this.schoolCalendarDetailList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },


    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        calendarId: null,
        calendarName: null,
        detailName: null,
        detailContent: null,
        startTime: null,
        endTime: null,
        holidayName: null,
        weekValue: null,
        weekName: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加校历详细条目";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      console.log('row', row)
      this.reset();
      const id = row.id || this.ids
      getSchoolCalendarDetail(id).then(response => {
        console.log('response', response)
        this.form = response.data;
        this.open = true;
        this.title = "修改校历详细条目";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          console.log("this.form.id", this.form)
          if (this.form.id != null) {
            updateSchoolCalendarDetail(this.form, this.calendarId).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSchoolCalendarDetail(this.form, this.calendarId).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal
        .confirm(`是否确认删除选中的${Object.hasOwnProperty.call(ids, 'length') ? ids.length : 1}条数据？`)
        .then(() => {
          this.$modal.loading('正在删除数据，请稍等...');
          return delSchoolCalendarDetail(ids);
        }).then(() => {
        this.$modal.closeLoading();
        this.$modal.msgSuccess('删除成功');
        this.getList();
      })
        .catch(() => {
          this.$modal.closeLoading();
        })
      // const ids = row.id || this.ids;
      // this.$modal.confirm('是否确认删除校历详细条目编号为"' + ids + '"的数据项？').then(function () {
      //   return delSchoolCalendarDetail(ids);
      // }).then(() => {
      //   this.getList();
      //   this.$modal.msgSuccess("删除成功");
      // }).catch(() => {
      // });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.$confirm(`是否确认导出校历详细条目数据？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (this.ids.length) {
          console.log("this.ids", this.ids)
          this.download('/schoolCalendarDetail/export/' + this.ids, {
            ...this.queryParams
          }, `校历详细条目.xlsx`)
        } else {
          this.download('/schoolCalendarDetail/export/', {
            ...this.queryParams
          }, `校历详细条目.xlsx`)
        }
        // this.$message({
        //   type: 'success',
        //   message: '导出成功!'
        // });
      }).catch(() => {
        // this.$message({
        //   type: 'info',
        //   message: '已取消'
        // });
      });
    },
    // close() {
    //   // 关闭当前页面
    //   //   localStorage.removeItem('recItem');
    //   //   store.commit('tagsView/DEL_VISITED_VIEW', this.$route);
    //   // this.$router.push({
    //   //   path: '/school/calendar/schoolCalendar'
    //   // })
    // },
    /** 关闭按钮 */
    close() {
      const obj = {path: "/schoolManage/calendar/schoolCalendar"};
      this.$tab.closeOpenPage(obj);
    },
    //校验结束时间
    checkEndTime(rule, value, callback) {
      if (!value) {
        callback(new Error("请选择结束时间"));
      } else {
        if (!this.form.startTime) {
          callback(new Error("请选择开始时间！"))
        } else if (Date.parse(this.form.startTime) >= Date.parse(value)) {
          callback(new Error("结束时间必须大于开始时间！"))
        } else {
          callback();
        }
      }
    },
    dateFormat(row, column, cellValue, index) {
      //时间格式化
      const daterc = row[column.property]
      console.log('daterc', daterc)
      if (daterc) {
        const dateMat = new Date(parseInt(daterc.replace("/Date(", "").replace(")/", ""), 10));
        const year = dateMat.getFullYear();
        const month = dateMat.getMonth() + 1;
        const day = dateMat.getDate();
        const hh = dateMat.getHours();
        const mm = dateMat.getMinutes();
        const ss = dateMat.getSeconds();
        const timeFormat = year + "/" + month + "/" + day + " " + hh + ":" + mm + ":" + ss;
        return timeFormat;
      }

      // console.log('dateFormat,row')
      // console.log(row.weekName)
      // console.log('dateFormat,column')
      // console.log(column)
      // console.log('dateFormat,cellValue')
      // console.log(cellValue)
      // console.log('dateFormat,index')
      // console.log(index)
    }
  }
};
</script>
