<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"
        >新 增
        </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"-->
      <!--        >修 改-->
      <!--        </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>-->
      <!--          v-show="queryParams.dcwjZt==='0'"-->
      <!--      </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>
        <template slot-scope="scope">
          {{ scope.row.scope }}
        </template>
      </el-table-column>
      <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="200px" show-overflow-tooltip prop="dcwjMs"/>
      <el-table-column label="操作" align="center" min-width="270px">
        <template v-slot="scope">
          <el-button
            v-show="scope.row.dcwjZt==='1'"
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            @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"
                     @click="publishExamExecute(scope.row)"
          >发布
          </el-button>
          <el-button v-show="scope.row.dcwjZt==='2'"
                     size="mini"
                     type="text"
                     @click="toQuestionResult(scope.row.id,scope.row.pubType)"
          >问卷结果
          </el-button>
          <!--          @click="jumpTo(ActivityResult(scope.row.id,scope.row.pubType))"-->
          <el-button v-show="scope.row.dcwjZt==='1'"
                     size="mini"
                     type="text"
                     @click="handleDelete(scope.row)"
          >删除
          </el-button>
          <el-button
            v-show="scope.row.dcwjZt==='2'"
            size="mini"
            type="text"
            @click="recallExamExecute(scope.row)"
          >撤回
          </el-button>
          <el-button
            size="mini"
            type="text"
            @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="650px" 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="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" placeholder="请输入问卷描述"/>
        </el-form-item>
        <el-col :span="12">
          <el-form-item label="接收人类型" prop="pubType">
            <el-select v-model="form.pubType" @change="receiveChange" placeholder="请选择接收人类型">
              <el-option
                v-for="item in [{
                value: '1',
                label: '教师'},{
                value: '0',
                label: '家长'
                }]"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="级部" prop="gradeIds">
            <treeselect
              v-model="form.gradeIds"
              :disabled="gradeDisabled || !isEditable"
              multiple
              :options="gradeTree"
              :show-count="true"
              :defaultExpandLevel="2"
              :disable-branch-nodes="true"
              placeholder="请选择级部"
            />
          </el-form-item>
        </el-col>
      </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 {
  getDateList,
  gradeTree,
  addToList,
  deleteData,
  getGrade,
  getGradeTree,
  editOnList,
  publishExam,
  recallExam,
  getSchoolYear,
  getQueryOne
} from "@/api/smartSchool/teachAffairAdministration/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: "QuestionnaireActivity",
  dicts: ["quest_state"],
  components: {
    Treeselect
  },
  data() {
    return {
      gradeDisabled: true,
      // 级部树
      gradeTree: [],
      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'}],
        pubType: [{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(`/teachAffairQuestion/content/${examId}`, {}, {
        state,
        title
      }),
      //问卷结果
      ActivityResult: (examId, pubType) => new Path_Destination(`/teachAffairQuestion/result/${examId}`, {pubType: pubType}),
    };
  },
  created() {
    this.getList();
    gradeTree().then(response => {
      this.gradeTree = response.data
    })
  },
  methods: {
    toQuestionResult(examId, pubType) {
      this.$router.push({
        path: '/teachAffairQuestion/result',
        query: {
          examId: examId,
          pubType: pubType
        }
      })
    },
    jumpTo,
    /** 查询问卷调查活动列表 */
    getList() {
      this.loading = true;
      getDateList(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 = "添加问卷调查活动";
      // gradeTree().then(response => {
      //   this.gradeTree = response.data
      // })
    },

    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids[0]
      let res = await getQueryOne(id)

      this.form = res.data
      if (this.form.pubType == 0) {
        this.gradeDisabled = false
      } else {
        this.gradeDisabled = true
      }

      // res = await gradeTree()
      // this.gradeTree = res.data
      this.open = true;
      this.isEditable = true
      this.title = "修改问卷调查活动";

    },
    /** 查看按钮操作 */
    async handleCheck(row) {
      this.reset();
      const id = row.id || this.ids[0]
      let res = await getQueryOne(id)
      this.form = res.data
      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();
            })
          }
        }
      });
    },
    receiveChange(newValue) {
      this.form.gradeIds = []
      if (newValue == 1) {
        this.gradeDisabled = true
      } else {
        this.gradeDisabled = false
      }
    },
    /** 删除按钮操作 */
    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>
