<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="时间" prop="dutyDeDate">
        <el-date-picker clearable
                        v-model="queryParams.dutyDeDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="类型" prop="dutyDeType">
        <el-select v-model="queryParams.dutyDeType" style="width: 100%" placeholder="请选择类型">
          <el-option
            v-for="dict in dutyDeType"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="姓名" prop="dutyDeUsername">
        <el-input
          v-model="queryParams.dutyDeUsername"
          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="['SchoolDuty:duty: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="['SchoolDuty:duty: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="['SchoolDuty:duty:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          plain
          type="success"
          icon="el-icon-upload"
          size="mini"
          @click="handleImport"
          v-hasPermi="['SchoolDuty:duty:export']"
        >导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['SchoolDuty:duty: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"></right-toolbar>-->
    </el-row>

    <el-table v-loading="loading" :data="dutyList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="序号" type="index" align="center"/>
      <el-table-column label="日期" align="center" prop="dutyDeDate" width="180"/>
      <el-table-column label="星期" align="center" prop="dutyDeWeek"/>
      <el-table-column label="类型" align="center" prop="dutyDeType">
        <template slot-scope="scope">
          {{ getDutyType(scope.row.dutyDeType) }}
        </template>
      </el-table-column>
      <el-table-column label="值班人员" align="center" prop="dutyDeUsername"/>
      <el-table-column label="值班人联系电话" align="center" prop="dutyDePhone"/>
      <el-table-column label="办公室电话" align="center" prop="dutyDeTel"/>
      <el-table-column label="操作" 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="['SchoolDuty:duty:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['SchoolDuty:duty:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
                 :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
                 :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
                   @click="importTemplate">下载模板
          </el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改值班管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" style="width: 90%">
        <el-form-item v-if="disabledd" label="日期" prop="dutyDeDate">
          <el-date-picker clearable
                          style="width: 100%;"
                          v-model="form.dutyDeDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择值班时间"
                          @change="handleDateChange(form.dutyDeDate)"
                          :picker-options="datePickerLimit">
          </el-date-picker>
        </el-form-item>
        <el-form-item v-if="disabledd" label="星期" prop="dutyDeWeek">
          <el-input v-model="form.dutyDeWeek" readonly/>
        </el-form-item>
        <el-form-item label="类型" prop="dutyDeType">
          <el-select v-model="form.dutyDeType" style="width: 100%" placeholder="请选择类型"
                     @change="handleTypeChange">
            <el-option
              v-for="dutyDeType in dutyType === '0' ? dutyDeTypeList[0] : dutyDeTypeList[1]"
              :key="dutyDeType.value"
              :label="dutyDeType.label"
              :value="dutyDeType.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="值班人姓名" prop="dutyDeUsername">
          <el-input v-model="form.dutyDeUsername" @focus="openSelect" placeholder="请输入值班人姓名"/>
        </el-form-item>
        <el-form-item label="值班人电话" prop="dutyDePhone">
          <el-input v-model="form.dutyDePhone" placeholder="请输入值班人联系电话"/>
        </el-form-item>
        <el-form-item label="办公室电话" prop="dutyDeTel">
          <el-input v-model="form.dutyDeTel" placeholder="请输入办公室电话"/>
        </el-form-item>
        <el-form-item label="说明" prop="remarks">
          <el-input v-model="form.remarks" type="textarea" :autosize="{ minRows: 3, maxRows: 5}"
                    placeholder="请输入内容"/>
        </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>

    <!--  选择值班人员-->
    <SelectDutyUser
      :open.sync="selectHandles.open"
      :title="selectHandles.title"
      :width="selectHandles.width"
      @select="selectDutyUser"
    ></SelectDutyUser>
  </div>
</template>

<script>
import {
  listDuty,
  getDuty,
  delDuty,
  addDuty,
  updateDuty,
  getWeek,
  teacherList
} from "@/api/smartSchool/schoolManage/dutyManage/dutyArrange";
import {getToken} from "@/utils/auth";
import {getDicts} from "@/api/system/dict/data";
import {isArray} from "@/utils/validate";
import SelectDutyUser from "./components/SelectDutyUser";

export default {
  name: "Duty",
  components: {
    SelectDutyUser
  },
  data() {
    return {
      disabledd: true,
      dutyType: "",
      //时间限制
      limitDate: {
        start: null,
        end: null
      },
      //值班人员姓名选择或输入
      dutyDeUsernameIsInput: false,
      dutyTeacherList: [],
      // 不同的假期类型对应不同的值班详情类型
      dutyDeTypeList: [],
      // 值班详情类型
      dutyDeType: [],
      dutyId: '',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedSchoolDutyDetails: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 值班管理表格数据
      dutyList: [],
      // 值班管理明细表格数据
      schoolDutyDetailsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        dutyDeUsername: null,
        dutyDeType: null,
        dutyDeDate: null,
        dutyDeWeek: null,
        state: null,
      },
      // 值班明细导入参数
      upload: {
        // 是否显示弹出层（值班明细导入）
        open: false,
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: 'Bearer ' + getToken()},
        // 上传的地址
        url: ''
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        delFlag: [
          {required: true, message: "$comment不能为空", trigger: "blur"}
        ]
      },
      //时间范围限制 值班日期要在值班时间范围内
      datePickerLimit: {
        disabledDate: time => Date.parse(time) > Date.parse(this.limitDate.end) || Date.parse(time) < Date.parse(this.limitDate.start) - 8.64e7
      },
      // 选择值班人员
      selectHandles: {
        open: false,
        title: '选择值班人',
        width: '50%'
      }
    };
  },
  computed: {
    getDutyType() {
      return item => {
        return this.dutyDeType.find(data => data.value === item)?.label;
      }
    }
  },
  created() {
    // 初始化：获取路由参数，上传路径
    this.init();
    this.getList();
    // 手动和处理字典数据获取：值班详细类型
    this.getDictData();
    // this.getLimitDate(); 合并到初始化中
  },
  methods: {
    //初始化
    init() {
      const {dutyId, dutyType, limitStartDate, limitEndDate} = this.$route.query;
      this.dutyId = dutyId;
      this.dutyType = dutyType;
      this.limitDate.start = limitStartDate;
      this.limitDate.end = limitEndDate;
      this.upload.url = process.env.VUE_APP_BASE_API + `/dutyDetails/importData/${this.dutyId}`;
    },
    // 获取字典数据：值班详细类型
    getDictData() {
      // 后续可以将字典类型放到常量文件夹中
      getDicts('duty_de_type').then(response => {
        if (isArray(response.data)) {
          // 赋值对应的字典数据
          this.dutyDeType = response.data.map(data => ({label: data.dictLabel, value: data.dictValue}));
          // 处理不同的假期类型对应的值班详情类型
          this.filterDict([0, 1]);
        }
      })
    },
    //时间限制
    /** @deprecated */
    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))
    },
    //对字典中的数据进行过滤
    filterDict(range) {
      this.dutyDeTypeList = [];
      let index = 0;
      /*
      * 这里建议使用不同的字典管理
      * */
      this.dutyDeType.forEach(data => {
        index = range.indexOf(parseInt(data.value));
        if (index > -1) {
          // 节日
          !this.dutyDeTypeList[0] && (this.dutyDeTypeList[0] = []);
          this.dutyDeTypeList[0].push(data);
          range.splice(index, 1);
        } else {
          // 寒暑假
          !this.dutyDeTypeList[1] && (this.dutyDeTypeList[1] = []);
          this.dutyDeTypeList[1].push(data);
        }
      })

      // if (this.dutyType === '0') {
      //   //节日
      //   for (let i = 0; i < 2; i++) {
      //     this.dutyDeTypeList.push(this.dict.type.duty_de_type[i]);
      //   }
      // } else if (this.dutyType === '1') {
      //   //寒暑假
      //   for (let i = 2; i < this.dict.type.duty_de_type.length; i++) {
      //     this.dutyDeTypeList.push(this.dict.type.duty_de_type[i]);
      //   }
      // }
    },
    //值班人员改变触发事件
    handleTeacherChange(value) {
      let teacher = this.dutyTeacherList.filter(function (teacher) {
        return teacher.value == value;
      })
      this.form.dutyDePhone = teacher[0].tel
      this.form.dutyDeUser = teacher[0].value
      this.form.dutyDeUsername = teacher[0].label
    },
    // 打开选中值班人
    openSelect() {
      console.log(this.dutyDeTypeList[1].slice(2));
      if (this.dutyType === '1' && this.dutyDeTypeList[1].slice(2).findIndex(item => this.form.dutyDeType === item.value) > -1) {
        return;
      }
      this.selectHandles.open = true;
    },
    // 触发选中值班人
    selectDutyUser(selectUser) {
      this.$set(this.form, 'dutyDeUsername', selectUser.name);
      this.$set(this.form, 'dutyDePhone', selectUser.tel);
      this.$set(this.form, 'dutyDeUser', selectUser.id);
    },

    //值班类型改变触发事件
    handleTypeChange(value) {
      this.$set(this.form, 'dutyDeUsername', null);
      this.$set(this.form, 'dutyDePhone', null);
      if (value != '4' && value != '5') {
        this.disabledd = true
        this.dutyDeUsernameIsInput = true;
        teacherList().then(response => {
          let dutyTeacher = {};
          for (let i = 0; i < response.rows.length; i++) {
            dutyTeacher = {
              value: response.rows[i].id,
              label: response.rows[i].teacherName,
              tel: response.rows[i].teacherTel
            }
            this.dutyTeacherList.push(dutyTeacher);
          }
        })
      } else {
        this.$set(this.form, 'dutyDeWeek', null);
        this.$set(this.form, 'dutyDeDate', null);
        this.disabledd = false
        this.dutyDeUsernameIsInput = false;
      }
    },
    //日期修改触发事件
    handleDateChange(dutyDeDate) {
      getWeek(dutyDeDate).then(response => {
        this.form.dutyDeWeek = response.dutyDeWeek
      })
    },

    //获取数据字典列表
    // getDutyType(dutyType) {
    //   if (this.dict.type.duty_de_type.length != 0) {
    //     for (let i = 0; i < this.dict.type.duty_de_type.length; i++) {
    //       let item = this.dict.type.duty_de_type[i]
    //       if (dutyType == item.value)
    //         return item.label
    //     }
    //   }
    // },

    /** 查询值班管理列表 */
    getList() {
      this.loading = true;
      // let id = this.$route.query && this.$route.query.dutyId;
      listDuty(this.dutyId, this.queryParams).then(response => {
        this.dutyList = response.rows || [];
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        dutyDeDate: null,
        dutyDePhone: null,
        dutyDeTel: null,
        dutyDeType: null,
        dutyDeUser: null,
        dutyDeUsername: null,
        dutyDeWeek: null,
        dutyId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        delFlag: null
      };
      this.schoolDutyDetailsList = [];
      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.filterDict();
      this.open = true;
      this.form.dutyDeDate = this.limitDate.start
      this.handleDateChange(this.form.dutyDeDate);
      this.title = "添加值班明细";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.filterDict([0, 1]);
      const id = row.id || this.ids
      // if(row.dutyDeType != '4' && row.dutyDeType != '5'){
      //   this.dutyDeUsernameIsInput = true;
      // }else{
      //   this.dutyDeUsernameIsInput = false;
      // }
      getDuty(id).then(response => {
        this.form = response.data;
        this.schoolDutyDetailsList = response.data.schoolDutyDetailsList;
        this.open = true;
        this.title = "修改值班明细";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.schoolDutyDetailsList = this.schoolDutyDetailsList;
          if (this.form.id != null) {
            updateDuty(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDuty(this.form, this.dutyId).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除值班管理编号为"' + ids + '"的数据项？').then(function () {
        return delDuty(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 值班管理明细序号 */
    rowSchoolDutyDetailsIndex({row, rowIndex}) {
      row.index = rowIndex + 1;
    },
    /** 值班管理明细添加按钮操作 */
    handleAddSchoolDutyDetails() {
      let obj = {};
      obj.dutyId = "";
      obj.dutyDeDate = "";
      obj.dutyDeWeek = "";
      obj.dutyDeType = "";
      obj.dutyDeUser = "";
      obj.dutyDeUsername = "";
      obj.dutyDePhone = "";
      obj.dutyDeTel = "";
      obj.remarks = "";
      this.schoolDutyDetailsList.push(obj);
    },
    /** 值班管理明细删除按钮操作 */
    handleDeleteSchoolDutyDetails() {
      if (this.checkedSchoolDutyDetails.length == 0) {
        this.$modal.msgError("请先选择要删除的值班管理明细数据");
      } else {
        const schoolDutyDetailsList = this.schoolDutyDetailsList;
        const checkedSchoolDutyDetails = this.checkedSchoolDutyDetails;
        this.schoolDutyDetailsList = schoolDutyDetailsList.filter(function (item) {
          return checkedSchoolDutyDetails.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleSchoolDutyDetailsSelectionChange(selection) {
      this.checkedSchoolDutyDetails = selection.map(item => item.index)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + '</div>', '导入结果', {dangerouslyUseHTMLString: true})
      this.getList()
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit()
    },
    // 下载值班明细模板
    importTemplate() {
      if (this.dutyType == '0') {
        //节日
        this.download(`/dutyDetails/importHolidayTemplate/${this.dutyId}`, {}, `节日值班安排明细_${Date.now()}.xlsx`)
      } else if (this.dutyType == '1') {
        //寒暑假
        this.download(`/dutyDetails/importTemplate/${this.dutyId}`, {}, `寒暑假值班安排明细_${Date.now()}.xlsx`)
      }

    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = '值班明细导入'
      this.upload.open = true
    },
    /** 导出按钮操作 */
    /*    handleExport() {
          this.download('duty/export', {
            ...this.queryParams
          }, `duty_${new Date().getTime()}.xlsx`)
        },*/
    handleExport() {
      this.download('dutyDetails/export', {
        dutyType: this.$route.query && this.$route.query.dutyType,
        dutyId: this.$route.query && this.$route.query.dutyId
      }, `值班安排明细${Date.now()}.xlsx`)
    },
    /** 关闭按钮 */
    close() {
      const obj = {path: "/schoolManage/dutyManage"};
      this.$tab.closeOpenPage(obj);
    },
  }
};
</script>

