<template>
  <div class="questionnaire-activity app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="问卷名称" prop="dcwjName">
        <el-input v-model="queryParams.dcwjName"
                  placeholder="请输入问卷名称"
                  clearable
                  @keyup.enter.native="handleQuery"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="问卷状态" prop="dcwjZt">
        <el-select v-model="queryParams.dcwjZt" placeholder="请选择问卷状态" @keyup.enter.native="handleQuery">
          <el-option v-for="item in dict.type.quest_state" :value="item.value" :label="item.label"></el-option>
        </el-select>
      </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="['smart-campus:purchase:add']"
        >添加
        </el-button>
        <!--          v-show="queryParams.dcwjZt==='0'"-->
      </el-col>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="success"-->
      <!--          plain-->
      <!--          icon="el-icon-edit"-->
      <!--          size="mini"-->
      <!--          :disabled="single"-->
      <!--          @click="handleUpdate"-->
      <!--          v-hasPermi="['smart-campus:purchase:edit']"-->
      <!--        >修改-->
      <!--        </el-button>-->
      <!--        &lt;!&ndash;          v-show="queryParams.dcwjZt==='0'"&ndash;&gt;-->
      <!--      </el-col>-->
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="danger"-->
      <!--          plain-->
      <!--          icon="el-icon-delete"-->
      <!--          size="mini"-->
      <!--          :disabled="multiple"-->
      <!--          @click="handleDelete"-->
      <!--          v-hasPermi="['smart-campus:purchase:remove']"-->
      <!--        >删除-->
      <!--        </el-button>-->
      <!--        &lt;!&ndash;          v-show="queryParams.dcwjZt==='0'"&ndash;&gt;-->
      <!--      </el-col>-->
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="warning"-->
      <!--          plain-->
      <!--          icon="el-icon-download"-->
      <!--          size="mini"-->
      <!--          @click="handleExport"-->
      <!--          v-hasPermi="['smart-campus:purchase:export']"-->
      <!--        >导出-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="activityList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" min-width="55" align="center"/>
      <el-table-column type="index" label="序号" min-width="55" align="center"/>
      <el-table-column label="范围" align="center" prop="scope" min-width="200px" show-overflow-tooltip/>
      <el-table-column label="问卷名称" align="center" prop="dcwjName" min-width="150px" show-overflow-tooltip/>
      <el-table-column label="状态" align="center" prop="dcwjZt">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.quest_state" :value="scope.row.dcwjZt"/>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" sortable align="center" min-width="150px" prop="dcwjKssj"/>
      <el-table-column label="结束时间" sortable align="center" min-width="150px" prop="dcwjJssj"/>
      <el-table-column label="描述" align="center" min-width="150px" show-overflow-tooltip prop="dcwjMs"/>
      <el-table-column label="操作" align="center" min-width="300px">
        <template v-slot="scope">
          <el-button
            v-show="scope.row.dcwjZt==='1'"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-document"
            @click="jumpTo(QuestionnaireContent(scope.row.id, scope.row.dcwjZt,scope.row.dcwjName))"
          >问卷内容
          </el-button>
          <el-button v-show="scope.row.dcwjZt==='1'"
                     size="mini"
                     type="text"
                     icon="el-icon-s-promotion"
                     @click="publishExamExecute(scope.row)"
          >发布
          </el-button>
          <el-button v-show="scope.row.dcwjZt==='2'"
                     size="mini"
                     type="text"
                     icon="el-icon-document-checked"
                     @click="jumpTo(ActivityResult(scope.row.id))"
          >问卷结果
          </el-button>

          <el-button v-show="scope.row.dcwjZt==='1'"
                     size="mini"
                     type="text"
                     icon="el-icon-delete"
                     @click="handleDelete(scope.row)"
          >删除
          </el-button>
          <el-button
            v-show="scope.row.dcwjZt==='2'"
            size="mini"
            type="text"
            icon="el-icon-refresh-left"
            @click="recallExamExecute(scope.row)"
          >撤回
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleCheck(scope.row)"
          >查看
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <ExPagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改问卷调查活动对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="auto" class="add-edit-dialog"
               :disabled="!isEditable">
        <el-row>
          <el-col :span="24">
            <el-form-item label="问卷名称" prop="dcwjName">
              <el-input v-model="form.dcwjName" placeholder="请输入活动名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="开始时间" prop="dcwjKssj">
              <el-date-picker clearable
                              v-model="form.dcwjKssj"
                              type="datetime"
                              value-format="yyyy-MM-dd HH:mm:ss"
                              placeholder="请选择开始时间"
                              :picker-options="StartPickerOptions"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="" prop="dcwjJssj" label-width="0px">
              <el-date-picker clearable
                              v-model="form.dcwjJssj"
                              type="datetime"
                              value-format="yyyy-MM-dd HH:mm:ss"
                              placeholder="请选择结束时间"
                              :picker-options="EndPickerOptions"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="范围" prop="gradeId">
              <!--              <el-input v-model="form.gradeId" placeholder="请输入问卷范围"/>-->
              <treeselect
                :disabled="!isEditable"
                v-model="form.gradeId"
                :options="treeOptions"
                :searchable="true"
                :show-count="true"
                :disable-branch-nodes="true"
                :clearable="false"
                placeholder="请选择部门"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="学年" prop="schoolYear">
              <el-input v-model="form.schoolYear" placeholder="请输入学年" disabled/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="问卷描述" prop="dcwjMs">
          <el-input type="textarea" v-model="form.dcwjMs"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" v-show="isEditable" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">{{ isEditable ? '取 消' : '退 出' }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addToList,
  deleteData,
  getGrade,
  getGradeTree,
  editOnList,
  getList,
  publishExam,
  recallExam,
  getSchoolYear,
} from "@/api/smartSchool/gradeWork/questionnaireManagement/QuestionnaireActivity/request.js";
import {jumpTo, Path_Destination} from "@/utils/utilLibrary/routerBatch/routerBatch";
import {QUESTION_STATE} from "@/enums/questionnaire/content";
import Treeselect from "@riophae/vue-treeselect";
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

export default {
  name: "GradeWorkQuestionnaire",
  dicts: ["quest_state"],
  components: {
    Treeselect
  },
  data() {
    return {
      QUESTION_STATE,
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 问卷调查活动表格数据
      activityList: [],
      treeOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      isEditable: true,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        dcwjName: null,
        dcwjZt: null,
      },
      // 表单参数
      form: {
        id: null,
        scope: null,
        dcwjName: null,
        dcwjZt: null,
        dcwjKssj: null,
        dcwjJssj: null,
        dcwjMs: null,
        schoolYear: null,
      },
      // 表单校验
      rules: {
        dcwjName: [{required: true, message: '问卷名称不能为空', trigger: 'blur'}],
        dcwjKssj: [{required: true, message: '开始时间不能为空', trigger: 'blur'}],
        dcwjJssj: [{required: true, message: '结束不能为空', trigger: 'blur'}],
        gradeId: [{required: true, message: '范围不能为空', trigger: 'blur'}],
      },
      StartPickerOptions: {
        disabledDate: (time) => {
          return time.getTime() < Date.now() - 1 * 24 * 3600 * 1000
        },
      },
      EndPickerOptions: {
        disabledDate: (time) => {
          return time.getTime() < Date.now() - 1 * 24 * 3600 * 1000 && Date.parse(time) < Date.parse(this.form.dcwjKssj)
        },
      },
      activeState: '',
      //问卷内容
      QuestionnaireContent: (examId, state, title) => new Path_Destination(`/gradeQuestion/content/${examId}`, {}, {
        state,
        title
      }),
      //问卷结果
      ActivityResult: (examId) => new Path_Destination(`/gradeQuestion/result/${examId}`),
    };
  },
  created() {
    this.getList();
  },
  methods: {
    jumpTo,
    /** 查询问卷调查活动列表 */
    getList() {
      this.loading = true;
      getList(this.queryParams).then(response => {
        this.activityList = response.rows
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    CurrentStateChange(row) {
      this.getList()
    },
    // 表单重置
    reset() {
      this.resetForm("form");
      this.form = {
        id: null,
        scope: null,
        dcwjName: null,
        dcwjZt: null,
        dcwjKssj: null,
        dcwjJssj: null,
        schoolYear: null,
        dcwjMs: null,
      };
      getSchoolYear().then((res) => {
        this.form.schoolYear = res.schoolYear
      }).catch()
      getGrade().then((res) => {
        this.$set(this.form, 'gradeId', res.data)
      }).catch()
      getGradeTree().then((res) => {
        this.treeOptions = res.data
      }).catch()
    },
    /** 搜索按钮操作 */
    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.isEditable = true
      this.title = "添加问卷调查活动";
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids[0]
      let response = ((id) => {
        return JSON.parse(JSON.stringify(this.activityList)).find(el => {
          return el.id === id
        })
      })(id)
      if (response) {
        console.log(response)
        this.form = response;
        this.open = true;
        this.isEditable = true
        this.title = "修改问卷调查活动";
      }
    },
    /** 查看按钮操作 */
    handleCheck(row) {
      this.reset();
      const id = row.id || this.ids[0]
      let response = ((id) => {
        return JSON.parse(JSON.stringify(this.activityList)).find(el => {
          return el.id === id
        })
      })(id)
      if (response) {
        this.form = response;
        this.open = true;
        this.isEditable = false
        this.title = "查看问卷调查活动";
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.$modal.loading('正在上传数据，请稍等...');
          if (this.form.id != null) {
            editOnList(this.form).then(response => {
              this.$modal.closeLoading();
              this.$modal.msgSuccess("修改成功");
              this.loading = false
              this.open = false;
              this.getList();
            }).catch(error => {
              this.$modal.closeLoading();
            })

          } else {
            addToList(this.form).then(response => {
              this.$modal.closeLoading();
              this.$modal.msgSuccess("新增成功");
              this.loading = false
              this.open = false;
              this.getList();
            }).catch(error => {
              this.$modal.closeLoading();
            })
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除问卷调查的数据项？').then(function () {
        return deleteData(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch((err) => {
        console.error(err)
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.loading = true
      const ids = this.ids;
      if (ids) {
        this.download(`/dcwjnull/export/${ids}`, {}, `问卷调查活动${Date.now()}.xlsx`)
      } else {
        this.download('/dcwjnull/export', {}, `问卷调查活动${Date.now()}.xlsx`)
      }
      this.loading = false
    },
    publishExamExecute(row) {
      this.$modal.confirm('是否发布该活动？').then(function () {
        return publishExam(row.id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("发布成功");
      }).catch((err) => {
        console.error(err)
      });
    },
    recallExamExecute(row) {
      this.$modal.confirm('是否撤回该活动？').then(function () {
        return recallExam(row.id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("撤回成功");
      }).catch((err) => {
        console.error(err)
      });
    },


  }
}
</script>

<style scoped lang="scss">
div.questionnaire-activity {
  div.belower {
    display: flex;
    flex-wrap: wrap;
    align-content: center;
    justify-content: center;
    align-items: center;
    overflow: hidden;

    &::v-deep .el-button {
      margin: 1px;
    }
  }
}

form.add-edit-dialog ::v-deep .el-input__inner, form.add-edit-dialog ::v-deep .el-date-editor, form.add-edit-dialog ::v-deep .el-select--medium {
  width: 98.5%;
}

</style>
