<template>
  <div class="app-container calendar-list-container">
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input
        v-if="contentType == 'alumniInfo' || contentType == 'recruitInfo'"
        clearable
        class="filter-item"
        style="width: 200px"
        placeholder="请输入姓名"
        v-model="listQuery.title"
      ></el-input>
      <el-input
        v-else-if="contentType == 'lecture'"
        clearable
        class="filter-item"
        style="width: 200px"
        placeholder="请输入标题"
        v-model="listQuery.title"
      ></el-input>
      <el-input
        v-else-if="contentType == 'video'"
        clearable
        class="filter-item"
        style="width: 200px"
        placeholder="请输入视频简介"
        v-model="listQuery.title"
      ></el-input>
      <el-input
        v-else
        clearable
        class="filter-item"
        style="width: 200px"
        placeholder="请输入标题"
        v-model="listQuery.title"
      ></el-input>
      <el-select
        v-if="contentType == 'activity'"
        v-model="listQuery.activityState"
        placeholder="请选择"
        clearable
        class="filter-item"
        style="width: 200px"
      >
        <el-option label="报名进行中" :value="1"> </el-option>
        <el-option label="报名已截止" :value="2"> </el-option>
        <el-option label="报名待开始" :value="3"> </el-option>
        <el-option label="活动进行中" :value="4"> </el-option>
        <el-option label="活动已结束" :value="5"> </el-option>
      </el-select>

      <el-date-picker
        v-if="contentType == 'lecture'"
        clearable
        class="filter-item"
        v-model="listQuery.dateRange"
        type="daterange"
        unlink-panels
        range-separator="至"
        value-format="yyyy-MM-dd"
        start-placeholder="主讲开始日期"
        end-placeholder="主讲结束日期"
      >
      </el-date-picker>
      <el-date-picker
        v-else-if="contentType == 'activity'"
        clearable
        class="filter-item"
        v-model="listQuery.dateRange"
        type="daterange"
        unlink-panels
        range-separator="&"
        value-format="yyyy-MM-dd"
        start-placeholder="活动开始日期"
        end-placeholder="活动结束日期"
      >
      </el-date-picker>
      <el-date-picker
        v-else
        clearable
        class="filter-item"
        v-model="listQuery.dateRange"
        type="daterange"
        unlink-panels
        range-separator="至"
        value-format="yyyy-MM-dd"
        start-placeholder="创建开始日期"
        end-placeholder="创建结束日期"
      >
      </el-date-picker>
      <el-button
        class="filter-item"
        type="primary"
        v-waves
        icon="el-icon-search"
        @click="handleFilter"
        >查找</el-button
      >
      <el-button
        class="filter-item"
        type="primary"
        @click="handleCreate"
        icon="el-icon-edit"
        >添加</el-button
      >
      <el-button
        class="filter-item"
        type="warning"
        icon="el-icon-delete"
        @click="delAll"
        >批量删除</el-button
      >
      <!-- <el-button class="filter-item" type="primary" :loading="downloadLoading" v-waves icon="el-icon-download" @click="handleDownload">导出</el-button> -->
      <!-- <el-button v-if="contentType=='activity'" class="filter-item" type="primary" @click="handleCreate">标签管理</el-button> -->
      <el-row v-if="contentType == 'activity'">
        <el-tag
          :key="tag.id"
          v-for="tag in dynamicTags"
          closable
          :disable-transitions="false"
          @close="handleClose(tag)"
        >
          <a @click="handleTagClick">{{ tag.tagName }}</a>
        </el-tag>
        <el-input
          class="input-new-tag"
          v-if="inputVisible"
          v-model="inputValue"
          ref="saveTagInput"
          size="small"
          @keyup.enter.native="handleInputConfirm"
          @blur="handleInputConfirm"
        >
        </el-input>
        <el-button v-else class="button-new-tag" size="small" @click="showInput"
          >+ New Tag</el-button
        >
      </el-row>
    </div>

    <!-- 查询结果 -->
    <el-table
      size="small"
      :data="list"
      v-loading="listLoading"
      @selection-change="handleSelectionChange"
      element-loading-text="正在查询中。。。"
      border
      fit
      highlight-current-row
    >
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form
            v-if="contentType == 'activity'"
            label-position="left"
            inline
            class="demo-table-expand"
          >
            <el-form-item label="报名开始时间：">
              <span>{{ props.row.registStartDate }}</span>
            </el-form-item>
            <el-form-item label="报名截止时间：">
              <span>{{ props.row.registEndDate }}</span>
            </el-form-item>
            <el-form-item label="活动开始时间：">
              <span>{{ props.row.activityStartDate }}</span>
            </el-form-item>
            <el-form-item label="活动结束时间：">
              <span>{{ props.row.activityEndDate }}</span>
            </el-form-item>
            <el-form-item label="创建时间：">
              <span>{{ props.row.createDate }}</span>
            </el-form-item>
            <el-form-item label="活动标签：" v-if="props.row.activity">
              <el-tag
                :key="tag.id"
                v-for="tag in props.row.activity.split(',')"
                type="primary"
                >{{ tag }}</el-tag
              >
            </el-form-item>
          </el-form>
          <el-form
            v-else-if="
              contentType == 'alumniInfo' || contentType == 'recruitInfo'
            "
            label-position="left"
            inline
            class="demo-table-expand"
          >
            <el-form-item label="头像：">
              <img
                :src="props.row.image"
                style="width: 50px; height: 50px; border-radius: 50%"
              />
            </el-form-item>
          </el-form>
          <el-form
            v-else-if="contentType == 'activityNews'"
            label-position="left"
            inline
            class="demo-table-expand"
          >
            <el-form-item label="关联活动：">
              <el-tag type="primary">{{
                getRelativeActivity(props.row.activityForNews)
              }}</el-tag>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column type="selection" width="55px"> </el-table-column>
      <!--<el-table-column align="center" width="65px" label="ID" prop="id" sortable>
      </el-table-column>-->
      <el-table-column
        type="index"
        label="序号"
        header-align="center"
        align="center"
      >
      </el-table-column>

      <el-table-column
        v-if="contentType == 'alumniInfo' || contentType == 'recruitInfo'"
        align="center"
        min-width="150px"
        label="姓名"
        prop="title"
      >
      </el-table-column>
      <el-table-column
        v-else-if="contentType == 'video'"
        align="center"
        min-width="150px"
        label="视频简介"
        prop="title"
      >
      </el-table-column>
      <el-table-column
        v-else-if="contentType == 'lecture'"
        align="center"
        min-width="150px"
        label="标题"
        prop="title"
      >
      </el-table-column>
      <el-table-column
        v-else
        align="center"
        min-width="150px"
        label="标题"
        prop="title"
      >
      </el-table-column>

      <el-table-column
        v-if="contentType == 'alumniInfo' || contentType == 'recruitInfo'"
        align="center"
        min-width="100px"
        label="描述"
        prop="universitarios"
      >
      </el-table-column>

      <el-table-column
        v-if="contentType == 'lecture'"
        align="center"
        min-width="100px"
        label="主讲教师"
        prop="lectureSpeaker"
      >
      </el-table-column>

      <el-table-column
        v-if="contentType == 'lecture'"
        align="center"
        min-width="100px"
        label="主讲时间"
        prop="lectureStartDate"
      >
      </el-table-column>
      <el-table-column
        v-if="contentType == 'lecture'"
        align="center"
        min-width="100px"
        label="主讲地址"
        prop="lectureAddress"
      >
      </el-table-column>

      <el-table-column
        v-if="contentType == 'activity'"
        align="center"
        min-width="100px"
        label="发起人"
        prop="creator"
      >
      </el-table-column>
      <el-table-column
        v-else
        align="center"
        min-width="100px"
        label="创建者"
        prop="creator"
      >
      </el-table-column>

      <el-table-column
        v-if="contentType == 'activity'"
        align="center"
        min-width="100px"
        label="当前状态"
        prop="activityState"
      >
      </el-table-column>

      <el-table-column
        align="center"
        min-width="120px"
        label="创建时间"
        prop="createDate"
      >
      </el-table-column>
      <el-table-column
        align="center"
        min-width="80px"
        label="优先级"
        prop="weight"
      ></el-table-column>

      <el-table-column
        align="center"
        label="操作"
        width="300"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <template v-if="contentType == 'activity'">
            <el-dropdown
              v-if="scope.row.activityAuditState == 0"
              size="mini"
              trigger="click"
              @command="handleCommand"
            >
              <el-button size="mini" type="primary">
                审核<i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item :command="{ command: 1, id: scope.row.id }"
                  >通过</el-dropdown-item
                >
                <el-dropdown-item :command="{ command: 2, id: scope.row.id }"
                  >拒绝</el-dropdown-item
                >
              </el-dropdown-menu>
            </el-dropdown>
            <el-tag v-else-if="scope.row.activityAuditState == 1" type="success"
              >通过</el-tag
            >
            <el-tag v-else-if="scope.row.activityAuditState == 2" type="danger"
              >被拒</el-tag
            >
            <el-tag v-else-if="scope.row.activityAuditState == 3" type="danger"
              >已取消</el-tag
            >
          </template>
          <el-button
            type="primary"
            size="small"
            @click="handleUpdate(scope.row, false)"
            >编辑</el-button
          >
          <el-button type="danger" size="small" @click="handleDelete(scope.row)"
            >删除</el-button
          >
          <el-button
            v-if="contentType == 'activity'"
            type="primary"
            size="small"
            @click="handleList(scope.row)"
            >人员列表
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="listQuery.page"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="listQuery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    <!--人员名单对话框-->
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="UdialogFormVisible"
      width="70%"
    >
      <template v-if="!dialogFlag">
        <el-button
          style="margin-bottom: 25px"
          class="filter-item"
          type="primary"
          :loading="downloadLoading"
          v-waves
          icon="el-icon-download"
          @click="handleDownload"
          >导出</el-button
        >
        <el-button
          class="filter-item"
          type="primary"
          :loading="downloadLoadingAll"
          v-waves
          icon="el-icon-download"
          @click="handleDownloadAll"
          >批量导出</el-button
        >

        <el-table
          size="small"
          :data="userList"
          v-loading="listLoading"
          element-loading-text="正在查询中。。。"
          border
          fit
          highlight-current-row
        >
          <!--<el-table-column align="center" width="100px" label="ID" prop="userId" sortable>
          </el-table-column>-->
          <el-table-column
            type="index"
            label="序号"
            header-align="center"
            align="center"
          >
          </el-table-column>

          <el-table-column
            align="center"
            min-width="100px"
            label="姓名"
            prop="userName"
          >
          </el-table-column>

          <el-table-column
            align="center"
            min-width="100px"
            label="头像"
            prop="photo"
          >
            <template slot-scope="scope">
              <img
                :src="scope.row.photo"
                style="width: 50px; height: 50px; border-radius: 50%"
              />
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            min-width="150px"
            label="报名时间"
            prop="createDate"
          >
          </el-table-column>
          <el-table-column
            align="center"
            min-width="100px"
            label="联系方式"
            prop="phone"
          >
          </el-table-column>
          <el-table-column
            align="center"
            min-width="80px"
            label="邮编"
            prop="postcode"
          >
          </el-table-column>
          <el-table-column
            align="center"
            min-width="120px"
            label="邮寄地址"
            prop="address"
          >
          </el-table-column>
          <el-table-column
            align="center"
            min-width="100px"
            label="备注"
            prop="annotation"
          >
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            background
            @size-change="handleGoodsSizeChange"
            @current-change="handleGoodsCurrentChange"
            :current-page="userlistQuery.page"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="userlistQuery.limit"
            layout="total, sizes, prev, pager, next, jumper"
            :total="userTotal"
          >
          </el-pagination>
        </div>
      </template>
    </el-dialog>
    <!-- 添加或修改对话框 -->
    <el-dialog
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      width="70%"
    >
      <template v-if="!dialogFlag">
        <el-form
          :rules="rules"
          ref="dataForm"
          :model="dataForm"
          status-icon
          label-position="left"
          label-width="110px"
          style="width: 600px; margin-left: 50px"
        >
          <el-form-item
            v-if="contentType == 'alumniInfo' || contentType == 'recruitInfo'"
            label="姓名"
          >
            <el-input v-model="dataForm.title"></el-input>
          </el-form-item>
          <el-form-item
            v-else-if="contentType == 'video'"
            prop="title"
            label="视频简介"
          >
            <el-input v-model="dataForm.title"></el-input>
          </el-form-item>
          <el-form-item
            v-else-if="contentType == 'lecture'"
            label="标题"
            prop="title"
            style="width: 750px"
          >
            <el-input v-model="dataForm.title"></el-input>
          </el-form-item>
          <el-form-item v-else label="标题" prop="title">
            <el-input v-model="dataForm.title"></el-input>
          </el-form-item>

          <el-form-item
            v-if="contentType == 'alumniInfo' || contentType == 'recruitInfo'"
            label="描述"
            prop="title"
          >
            <el-input v-model="dataForm.universitarios"></el-input>
          </el-form-item>
          <el-tooltip content="优先级越大，位置越靠前！" placement="top-start">
            <el-form-item label="优先级" prop="weight">
              <el-input-number
                :precision="0"
                :step="1"
                v-model="dataForm.weight"
              ></el-input-number>
            </el-form-item>
          </el-tooltip>

          <el-form-item
            v-if="contentType == 'alumniInfo' || contentType == 'recruitInfo'"
            label="首页头像"
            prop="image"
          >
            <el-upload
              class="avatar-uploader"
              :action="fileImgUrl"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item
            v-if="contentType == 'video'"
            label="视频封面"
            prop="image"
          >
            <el-upload
              class="ad-avatar-uploader"
              :action="fileImgUrl"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="dataForm.image" :src="dataForm.image" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item v-if="contentType == 'video'" label="视频" prop="video">
            <el-tooltip
              content="建议视频格式:mp4"
              placement="top-start"
              style="width: 178px"
            >
              <el-upload
                class="k-avatar-uploader el-upload--text"
                :action="fileImgUrl"
                :show-file-list="false"
                :on-success="handleVideoSuccess"
                :before-upload="beforeUploadVideo"
                :on-progress="uploadVideoProcess"
              >
                <video
                  v-if="dataForm.file != '' && videoFlag == false"
                  :src="dataForm.file"
                  class="k-avatar"
                  width="480px"
                  height="270px"
                  controls="controls"
                >
                  您的浏览器不支持视频播放
                </video>
                <i
                  v-else-if="dataForm.file == '' && videoFlag == false"
                  class="el-icon-plus k-avatar-uploader-icon"
                ></i>
                <div
                  v-if="!pass && videoUploadPercent !== 0"
                  class="img-content img-progress"
                >
                  <el-progress
                    v-if="!pass && videoUploadPercent !== 0"
                    type="circle"
                    :percentage="videoUploadPercent"
                    :status="proStatus"
                    style="margin-top: 30px"
                  ></el-progress>
                </div>
              </el-upload>
            </el-tooltip>
            <P class="text">请保证视频格式正确，且不超过200M</P>
          </el-form-item>
          <!-- about Activity -->
          <template v-if="contentType == 'activity'" label-width="10">
            <el-form-item label="是否需要邮寄">
              <el-select v-model="dataForm.activityType" placeholder="请选择">
                <el-option
                  v-for="item in aTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="活动地点" prop="activityAddress">
              <el-input v-model="dataForm.activityAddress"></el-input>
            </el-form-item>

            <el-form-item label="费用" prop="activityCost">
              <el-input-number
                :precision="2"
                :step="0.01"
                v-model="dataForm.activityCost"
              ></el-input-number>
            </el-form-item>

            <el-form-item label="活动人数限制（0为不限）" prop="activityLimit">
              <el-input-number
                :precision="0"
                :step="1"
                v-model="dataForm.activityLimit"
              ></el-input-number>
            </el-form-item>

            <el-form-item
              label="报名开始时间"
              prop="registStartDate"
              label-width="10"
            >
              <el-date-picker
                v-model="dataForm.registStartDate"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm"
                placeholder="选择日期"
                :picker-options="pickerOptions0"
                style="width: 350px"
              ></el-date-picker>
            </el-form-item>

            <el-form-item
              label="报名截止时间"
              prop="registEndDate"
              label-width="10"
            >
              <el-date-picker
                v-model="dataForm.registEndDate"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm"
                placeholder="选择日期"
                :picker-options="pickerOptions1"
                style="width: 350px"
              ></el-date-picker>
            </el-form-item>

            <el-form-item
              label="活动开始时间"
              prop="activityStartDate"
              label-width="10"
            >
              <el-date-picker
                v-model="dataForm.activityStartDate"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm"
                placeholder="选择日期"
                :picker-options="pickerOptions2"
                style="width: 350px"
              ></el-date-picker>
            </el-form-item>

            <el-form-item
              label="活动结束时间"
              prop="activityEndDate"
              label-width="10"
            >
              <el-date-picker
                v-model="dataForm.activityEndDate"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm"
                placeholder="选择日期"
                :picker-options="pickerOptions3"
                style="width: 350px"
              ></el-date-picker>
            </el-form-item>

            <el-form-item
              label="活动分类标签"
              prop="activitys"
              label-width="10"
            >
              <el-select
                v-model="dataForm.activitys"
                multiple
                placeholder="请选择"
                @change="activityChange"
                style="width: 350px"
              >
                <el-option
                  v-for="item in dynamicTags"
                  :key="item.id"
                  :label="item.tagName"
                  :value="item.tagName"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </template>
          <!-- end Activity -->

          <!-- about lecture -->
          <template v-if="contentType == 'lecture'">
            <el-form-item label="主讲教师" prop="lectureSpeaker">
              <el-input v-model="dataForm.lectureSpeaker"></el-input>
            </el-form-item>
            <el-form-item label="主讲地点" prop="lectureAddress">
              <el-input v-model="dataForm.lectureAddress"></el-input>
            </el-form-item>
            <el-form-item label="主讲时间" prop="lectureStartDate">
              <el-date-picker
                v-model="dataForm.lectureStartDate"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm"
                placeholder="选择日期"
                style="width: 350px"
              ></el-date-picker>
            </el-form-item>
          </template>
          <!-- end lecture -->

          <el-form-item
            v-if="
              contentType == 'schoolInfo' ||
              contentType == 'activity' ||
              contentType == 'activityNews'
            "
            style="width: 800px"
            label="列表图片"
            prop="image"
          >
            <el-tooltip content="建议图片宽高比260*200" placement="top-start">
              <el-upload
                :action="fileImgUrl"
                list-type="picture-card"
                multiple
                :limit="5"
                :file-list="dataForm.images"
                :on-success="handleGallerySucess"
                :on-exceed="handleExceed"
                :before-upload="uploadBannerImg"
                :on-remove="handleRemove"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
            </el-tooltip>
          </el-form-item>
          <el-form-item
            v-if="
              contentType == 'manual' ||
              contentType == 'rules' ||
              contentType == 'reading'
            "
            label="上传附件"
          >
            <el-upload
              class="avatar-uploader"
              :action="fileImgUrl"
              multiple
              :limit="1"
              :file-list="dataForm.files"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeUploadFile"
              :on-exceed="handleExceedPdf"
              :before-remove="beforeRemove"
              :on-remove="handleRemove"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-form-item>
          <el-form-item v-if="contentType == 'notice'" label="上传附件">
            <el-upload
              class="avatar-uploader"
              :action="fileImgUrl"
              list-type="text"
              multiple
              :limit="5"
              :file-list="dataForm.files"
              :on-success="handleAvatarSuccess"
              :on-exceed="handleExceed"
              :before-remove="beforeRemove"
              :on-remove="handleRemove"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>

            <!--
            <el-upload
              class="avatar-uploader"
              :action="fileImgUrl"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :before-remove="beforeRemove"
              :file-list="dataForm.files"
              :on-success="handleAvatarSuccess"
              :on-exceed="handleExceed">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
            -->
          </el-form-item>

          <!-- about activityNews -->
          <el-form-item
            label="关联活动"
            prop="activityForNews"
            v-if="contentType == 'activityNews'"
          >
            <el-select
              v-model="dataForm.activityForNews"
              filterable
              placeholder="请选择"
              style="width: 350px"
            >
              <el-option
                v-for="item in activityList"
                :label="item.title"
                :value="item.id"
                :key="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <!-- end activityNews -->

          <!-- 公告不需要推送到圈子 -->
          <el-form-item
            label="推送到圈子"
            prop="organizeId"
            v-if="contentType != 'notice'"
          >
            <el-select
              v-model="dataForm.organizeId"
              multiple
              filterable
              placeholder="请选择"
              style="width: 350px"
            >
              <el-option
                :key="item.id"
                v-for="item in organizes"
                :label="item.organizeName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item
            style="width: 800px"
            v-if="contentType != 'manual' || contentType != 'rules'"
            label="内容"
            prop="content"
          >
            <tinymce v-model="dataForm.content" ref="tinymce1"></tinymce>
          </el-form-item>
        </el-form>
      </template>
      <template v-else>
        <el-form
          status-icon
          label-position="left"
          label-width="100px"
          style="width: 400px; margin-left: 50px"
        >
        </el-form>
      </template>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <template v-if="!dialogFlag">
          <el-button
            v-if="dialogStatus == 'create'"
            type="primary"
            @click="createData"
            >确定</el-button
          >
          <el-button v-else type="primary" @click="updateData">确定</el-button>
        </template>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listNews,
  createNews,
  readNews,
  updateNews,
  updateNewsAuth,
  deleteNews,
  deleteAllNews,
  listActivityOrg,
} from "@/api/news";
import {
  listActivityTag,
  createActivityTag,
  deleteActivityTag,
  ActivityUser,
  ActivityUserAll,
} from "@/api/activitytag";
import { selectOrg, createOrg, updateOrg } from "@/api/organize";
import waves from "@/directive/waves"; // 水波纹指令
import BackToTop from "@/components/BackToTop";
import Tinymce from "@/components/Tinymce";
import SidebarItem from "../layout/components/Sidebar/SidebarItem";

export default {
  name: "index",
  components: { SidebarItem, BackToTop, Tinymce },
  directives: {
    waves,
  },
  inject: ["reload"],
  data() {
    return {
      contentType: undefined,
      title: "",
      listLoading: false,
      videoUploadPercent: 0, //上传进度
      pass: null, //是否上传成功
      listQuery: {
        type: undefined,
        activityType: [],
        activityState: undefined,
        title: undefined,
        creator: undefined,
        page: 1,
        limit: 20,
        sort: "+id",
        dateRange: undefined,
        activityAuditState: -1,
      },
      userlistQuery: {
        page: 1,
        limit: 10,
        newsId: undefined,
        sort: "+id",
      },
      userTotal: undefined,
      list: undefined,
      userListAll: undefined,
      userList: undefined,
      delarr: [],
      multipleSelection: [],
      total: 0,
      dialogFormVisible: false,
      UdialogFormVisible: false,
      dialogStatus: "",
      dialogFlag: false,
      textMap: {
        update: "编辑",
        create: "创建",
        userList: "参加人员名单",
      },
      dataForm: {
        id: undefined,
        type: undefined,
        title: undefined,
        content: undefined,
        image: "",
        images: [],
        file: undefined,
        fileName: undefined,
        files: [],
        creator: undefined,
        createDate: undefined,
        activityStartDate: undefined,
        activityEndDate: undefined,
        registStartDate: undefined,
        registEndDate: undefined,
        activity: undefined,
        activityAddress: undefined,
        activitys: [],
        organizeId: [],
        lectureStartDate: undefined,
        lectureAddress: undefined,
        lectureSpeaker: undefined,
        activityAuditState: undefined,
        activityForNews: undefined,
        universitarios: undefined,
        activityCost: 0.0,
        activityLimit: 0,
        activityType: undefined,
      },
      imageUrl: undefined,
      rules: {
        userName: [
          { required: true, message: "姓名不能为空", trigger: "blur" },
        ],
        title: [{ required: true, message: "标题不能为空", trigger: "blur" }],
        image: [{ required: true, message: "图片不能为空", trigger: "blur" }],
        /*video:[{required:true,message: '视频不能为空',trigger:'blur'}],*/
        registStartDate: [
          { required: true, message: "时间不能为空", trigger: "blur" },
        ],
        registEndDate: [
          { required: true, message: "时间不能为空", trigger: "blur" },
        ],
        activityStartDate: [
          { required: true, message: "时间不能为空", trigger: "blur" },
        ],
        activityEndDate: [
          { required: true, message: "时间不能为空", trigger: "blur" },
        ],
        activitys: [
          { required: true, message: "标签不能为空", trigger: "blur" },
        ],
      },
      fileImgUrl: this.upLoadUrl,
      videoFlag: false,
      downloadLoading: false,
      downloadLoadingAll: false,
      dynamicTags: [],
      inputVisible: false,
      inputValue: "",
      activityList: [],
      organizes: [],
      pickerOptions0: {
        disabledDate: (time) => {
          let beginDateVal = new Date(this.dataForm.registEndDate).getTime();
          if (beginDateVal) {
            return (
              time.getTime() > beginDateVal ||
              time.getTime() < Date.now() - 8.64e7
            );
          } else {
            return time.getTime() < Date.now() - 8.64e7;
          }
        },
      },
      pickerOptions1: {
        disabledDate: (time) => {
          let beginDateVal = new Date(
            this.dataForm.activityStartDate
          ).getTime();
          if (beginDateVal) {
            return (
              time.getTime() > beginDateVal ||
              time.getTime() < Date.now() - 8.64e7
            );
          } else {
            return time.getTime() < Date.now() - 8.64e7;
          }
        },
      },
      pickerOptions2: {
        disabledDate: (time) => {
          let beginDateVal = new Date(this.dataForm.activityEndDate).getTime();
          if (beginDateVal) {
            return (
              time.getTime() > beginDateVal ||
              time.getTime() < Date.now() - 8.64e7
            );
          } else {
            return time.getTime() < Date.now() - 8.64e7;
          }
        },
      },
      pickerOptions3: {
        disabledDate: (time) => {
          return time.getTime() < Date.now() - 8.64e7;
        },
      },
      aTypeOptions: [
        {
          value: "mail",
          label: "是",
        },
        {
          value: "",
          label: "否",
        },
      ],
    };
  },

  created() {
    this.title = this.$route.meta.title;
    this.textMap.create = "创建-" + this.title;
    this.contentType = this.$route.name;

    listActivityTag().then((response) => {
      this.dynamicTags = response.data.data.items;
    });

    if (this.contentType == "activityNews") {
      listNews({
        type: "activity",
        page: 1,
        limit: 2000,
        sort: "+id",
        activityAuditState: 1,
      })
        .then((response) => {
          this.activityList = response.data.data.items;
        })
        .catch(() => {
          this.activityList = [];
        });
    }

    selectOrg({ orgType: undefined, orgName: undefined, page: 1, limit: 1000 })
      .then((response) => {
        this.organizes = response.data.data.items;
      })
      .catch(() => {
        this.organizes = [];
      });

    this.getList();
  },
  computed: {
    proStatus() {
      //上传状态
      if (this.pass) {
        return "success";
      } else if (this.pass == false) {
        return "exception";
      } else {
        return "";
      }
    },
  },

  methods: {
    resetForm() {
      this.dataForm = {
        id: undefined,
        type: undefined,
        title: undefined,
        content: undefined,
        image: undefined,
        images: [],
        file: undefined,
        fileName: undefined,
        files: [],
        createDate: undefined,
        activityStartDate: undefined,
        activityEndDate: undefined,
        activity: undefined,
        activityAddress: undefined,
        activitys: [],
        organizeId: [],
        lectureStartDate: undefined,
        lectureAddress: undefined,
        lectureSpeaker: undefined,
        activityAuditState: undefined,
        activityForNews: undefined,
        universitarios: undefined,
        activityCost: 0.0,
        activityLimit: 0,
        activityType: undefined,
      };
    },

    resetList() {
      this.listQuery = {
        type: undefined,
        activityType: [],
        activityState: undefined,
        title: undefined,
        creator: undefined,
        page: 1,
        limit: 20,
        sort: "+id",
        dateRange: undefined,
        activityAuditState: -1,
      };
      this.list = undefined;
      this.userList = undefined;
      this.total = 0;
    },
    getUserList() {
      this.loading = true;
      ActivityUser(this.userlistQuery)
        .then((response) => {
          this.userList = response.data.data.items;
          this.userTotal = response.data.data.total;
          this.loading = false;
        })
        .catch(() => {
          this.userList = [];
          this.userTotal = 0;
          this.loading = false;
        });
    },
    getAllList() {
      ActivityUserAll(this.userlistQuery)
        .then((response) => {
          this.userListAll = response.data.data.items;
        })
        .catch(() => {
          this.userListAll = [];
        });
    },
    getList() {
      this.listLoading = true;
      this.listQuery.type = this.contentType;
      listNews(this.listQuery)
        .then((response) => {
          this.list = response.data.data.items;
          this.total = response.data.data.total;
          this.listLoading = false;
        })
        .catch(() => {
          this.list = [];
          this.total = 0;
          this.listLoading = false;
        });
    },
    cancel() {
      this.reload();
      this.dialogFormVisible = false;
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },

    handleSizeChange(val) {
      this.listQuery.limit = val;
      this.getList();
    },

    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.getList();
    },

    handleGoodsSizeChange(val) {
      this.userlistQuery.limit = val;
      this.getUserList();
    },
    handleGoodsCurrentChange(val) {
      this.userlistQuery.page = val;
      this.getUserList();
    },

    handleCreate() {
      this.resetForm();

      this.dialogFormVisible = true;
      this.dialogStatus = "create";
      this.dialogFlag = false;

      this.$nextTick(() => {
        this.$refs.tinymce1.setContent("");
        this.$refs["dataForm"].clearValidate();
      });
    },

    createData() {
      this.$refs["dataForm"].validate((valid) => {
        debugger;
        if (valid) {
          if (this.dataForm.activityEndDate < this.dataForm.activityStartDate) {
            this.$alert("活动结束时间不得小于活动开始时间", "提示", {
              confirmButtonText: "确定",
            });
          } else if (
            this.dataForm.activityStartDate < this.dataForm.registEndDate
          ) {
            this.$alert("活动开始时间不得小于报名截止时间", "提示", {
              confirmButtonText: "确定",
            });
          } else if (
            this.dataForm.registEndDate < this.dataForm.registStartDate
          ) {
            this.$alert("报名截止时间不得小于报名开始时间", "提示", {
              confirmButtonText: "确定",
            });
          } else {
            this.dataForm.type = this.contentType;
            createNews(this.dataForm)
              .then((response) => {
                //this.list.unshift(response.data.data)
                this.getList();
                this.dialogFormVisible = false;

                this.$notify({
                  title: "成功",
                  message: "创建成功",
                  type: "success",
                  duration: 2000,
                });
                this.reload();
              })
              .catch(() => {});
          }
        }
      });
    },
    handleList(row) {
      var newsId = row.id;
      if (newsId) {
        this.dialogStatus = "userList";
        this.UdialogFormVisible = true;
        this.userlistQuery.newsId = newsId;
        this.getUserList();
        this.getAllList();
      }
    },
    handleUpdate(row) {
      debugger;
      console.log(row);
      this.dataForm = Object.assign({ organizeId: [], activitys: [] }, row);
      let content = this.dataForm.content;

      // 活动标签列表
      if (this.dataForm.activity) {
        this.dataForm.activitys = this.dataForm.activity.split(",");
      }

      // 构建轮播图片列表
      if (this.dataForm.image) {
        let images = this.dataForm.image.split(",");
        this.dataForm.images = [];
        for (let i in images) {
          let url = images[i];
          let name = "image_" + i;

          this.dataForm.images.push({
            name: name,
            url: url,
            response: { error: "0", data: { url: url } },
          });
        }
      }
      if (
        this.contentType == "alumniInfo" ||
        this.contentType == "recruitInfo"
      ) {
        this.imageUrl = this.dataForm.image;
      }

      if (this.dataForm.file) {
        let files = this.dataForm.file.split(",");
        let names = "";
        if (this.dataForm.fileName) {
          names = this.dataForm.fileName.split(",");
        }
        this.dataForm.files = [];
        for (let i in files) {
          let fileUrl = files[i];
          let fileName = names[i];
          this.dataForm.files.push({
            name: fileName,
            url: fileUrl,
            response: { error: "0", data: { url: fileUrl } },
          });
        }
      }

      listActivityOrg({ newsId: this.dataForm.id })
        .then((response) => {
          let items = response.data.data.items;
          this.dataForm.organizeId = items.map((item) => {
            return item.organizeId;
          });
        })
        .catch(() => {});

      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs.tinymce1.setContent(content);
        this.$refs["dataForm"].clearValidate();
      });
    },

    updateData() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          if (this.dataForm.activityEndDate < this.dataForm.activityStartDate) {
            this.$alert("活动结束时间不得小于活动开始时间", "提示", {
              confirmButtonText: "确定",
            });
          } else if (
            this.dataForm.activityStartDate < this.dataForm.registEndDate
          ) {
            this.$alert("活动开始时间不得小于报名截止时间", "提示", {
              confirmButtonText: "确定",
            });
          } else if (
            this.dataForm.registEndDate < this.dataForm.registStartDate
          ) {
            this.$alert("报名截止时间不得小于报名开始时间", "提示", {
              confirmButtonText: "确定",
            });
          } else {
            updateNews(this.dataForm)
              .then(() => {
                this.getList();
                // for(const v of this.list) {
                //   if(v.id === this.dataForm.id ) {
                //     const index = this.list.indexOf(v)
                //     this.list.splice(index, 1, this.dataForm)
                //     break
                //   }
                // }

                this.dialogFormVisible = false;
                this.$notify({
                  title: "成功",
                  messagae: "更新成功",
                  type: "success",
                  duration: 2000,
                });
                this.reload();
              })
              .catch(() => {});
          }
        }
      });
    },

    handleDelete(row) {
      this.$confirm("确认删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteNews(row)
            .then(() => {
              this.$notify({
                title: "成功",
                message: "删除成功",
                type: "success",
                duration: 2000,
              });

              const index = this.list.indexOf(row);
              this.list.splice(index, 1);
            })
            .catch(() => {});
        })
        .catch(() => {});
    },
    delAll() {
      this.$confirm("确认删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          const length = this.multipleSelection.length;

          if (length > 0) {
            for (let i = 0; i < length; i++) {
              this.delarr.push(this.multipleSelection[i].id);
            }
            const newsIds = this.delarr.join(",");
            deleteAllNews({ newsId: newsIds })
              .then(() => {
                this.$notify({
                  title: "成功",
                  message: "删除成功",
                  type: "success",
                  duration: 2000,
                });
                this.getList();
              })
              .catch(() => {});
          } else {
            this.$notify({
              title: "警告提示",
              message: "请选择要删除的信息！",
              type: "warning",
            });
          }
        })
        .catch(() => {});
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    // 视频上传
    handleVideoSuccess(res, file) {
      // 获取上传图片地址
      this.videoFlag = false;
      this.videoUploadPercent = 0;
      if (res.errno === 0) {
        this.pass = true;
        this.dataForm.file = res.data.url;
      } else {
        this.pass = false;
        this.$message.error("视频上传失败，请重新上传！");
      }
    },
    beforeUploadFile(file){
      console.log(file);
      const size = file.size / 1024 / 1024;
      console.log(size);
      if(size > 10 || ["application/pdf"].indexOf(file.type) === -1){
        this.$message.error("文件大小不能超过10MB,格式必须为pdf！");
          return false;
      }
    },
    beforeUploadVideo(file) {
      const isLt200M = file.size / 1024 / 1024 < 200;
      // if (['video/mp4', 'video/ogg', 'video/flv', 'video/x-flv', 'video/avi', 'video/wmv', 'video/rmvb'].indexOf(file.type) === -1) {
      if (["video/mp4"].indexOf(file.type) === -1) {
        this.$message.error("请上传正确的视频格式");
        return false;
      }
      if (!isLt200M) {
        this.$message.error("上传视频大小不能超过200MB!");
        return false;
      }
    },
    uploadVideoProcess(event) {
      this.videoFlag = true;
      this.videoUploadPercent = Math.floor(event.percent);
    },
    handleDownload() {
      this.downloadLoading = true;
      import("@/vendor/Export2Excel").then((excel) => {
        const tHeader = [
          "id",
          "姓名",
          "报名时间",
          "联系方式",
          "邮编",
          "邮寄地址",
          "备注",
        ];
        const filterVal = [
          "userId",
          "userName",
          "createDate",
          "phone",
          "postcode",
          "address",
          "annotation",
        ];
        excel.export_json_to_excel2(
          tHeader,
          this.userList,
          filterVal,
          "参加人员名单"
        );
        this.downloadLoading = false;
      });
    },
    handleDownloadAll() {
      this.downloadLoadingAll = true;
      import("@/vendor/Export2Excel").then((excel) => {
        const tHeader = [
          "id",
          "姓名",
          "报名时间",
          "联系方式",
          "邮编",
          "邮寄地址",
          "备注",
        ];
        const filterVal = [
          "userId",
          "userName",
          "createDate",
          "phone",
          "postcode",
          "address",
          "annotation",
        ];
        excel.export_json_to_excel2(
          tHeader,
          this.userListAll,
          filterVal,
          "参加人员名单"
        );
        this.downloadLoadingAll = false;
      });
    },

    handlePreview(file) {
      console.log(file);
    },

    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },

    handleRemove(file, fileList) {
      console.log(file, fileList);

      if (
        this.contentType == "notice" ||
        this.contentType == "manual" ||
        this.contentType == "rules" ||
        this.contentType == "reading"
      ) {
        let files = [];
        let names = [];
        for (let i in fileList) {
          let response = fileList[i].response;
          let name = fileList[i].name;
          let url = response.data.url;
          files.push(url);
          names.push(name);
        }
        this.dataForm.file = files.join(",");
        this.dataForm.fileName = names.join(",");
      } else {
        let images = [];
        for (let i in fileList) {
          let response = fileList[i].response;
          let url = response.data.url;
          images.push(url);
        }
        this.imageUrl = images.join(",");
        this.dataForm.image = images.join(",");
      }
    },

    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 5 个文件，本次选择了 ${files.length} 个文件！，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },

    handleExceedPdf(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件！，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },

    uploadBannerImg(file) {
      const isJPGs = file.type === "image/jpeg";
      console.log(isJPGs);
    },

    handleAvatarSuccess(res, file, fileList) {
      // this.imageUrl = URL.createObjectURL(file.raw)
      console.log(file, fileList);
      console.log("------", "==========");
      console.log("res = " , res);

      if (
        this.contentType == "alumniInfo" ||
        this.contentType == "recruitInfo"
      ) {
        this.imageUrl = res.data.url;
        this.dataForm.image = res.data.url;
      } else if (this.contentType == "video") {
        this.imageUrl = res.data.url;
        this.dataForm.image = res.data.url;
      } else if (
        this.contentType == "notice" ||
        this.contentType == "manual" ||
        this.contentType == "rules" ||
        this.contentType == "reading"
      ) {
        let files = [];
        let names = [];
        for (let i in fileList) {
          let response = fileList[i].response;
          if (response.errno && response.errno != "0") {
            this.$message.error("该文件上传失败,已被移除,请重新上传!");
            // 上传失败移除该 file 对象
            fileList.splice(i, 1);
          } else {
            let name = fileList[i].name;
            let url = fileList[i].response.data.url;
            files.push(url);
            names.push(name);
          }
        }
        this.dataForm.file = files.join(",");
        this.dataForm.fileName = names.join(",");
      }
    },

    beforeAttacheUpload(file) {
      return true;
    },

    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },

    handleGallerySucess(res, file, fileList) {
      this.dataForm.image = ""; // 清空画廊图片数组

      let images = [];
      for (let i in fileList) {
        let response = fileList[i].response;
        if (response.errno && response.errno != "0") {
          this.$message.error("该图片上传失败,已被移除,请重新上传!");
          // 上传失败移除该 file 对象
          fileList.splice(i, 1);
        } else {
          let url = response.data.url;
          images.push(url);
        }
      }

      this.dataForm.image = images.join(",");
    },

    activityChange(activitys) {
      this.dataForm.activity = activitys.join(",");
    },

    handleClose(tag) {
      this.$confirm("确定移除该标签?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteActivityTag(tag).then(() => {
            this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
          });
        })
        .catch(() => {});
    },

    showInput() {
      this.inputVisible = true;
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        createActivityTag({ tagName: inputValue }).then((response) => {
          if (response.data.data.code) {
            this.$message.error(response.data.data.message);
          } else {
            this.dynamicTags.push(response.data.data);
          }
        });
      }
      this.inputVisible = false;
      this.inputValue = "";
    },

    handleTagClick(event) {
      let tagName = event.target.innerHTML;
      let p = event.target.parentNode;
      //let className= p.className

      if (p.active) {
        p.active = false;
        p.className = "el-tag el-tag--medium";
        p.style.boxShadow = "none";

        let index = this.listQuery.activityType.indexOf(tagName);
        this.listQuery.activityType.splice(index, 1);
      } else {
        p.active = true;
        p.className = "el-tag el-tag--success el-tag--medium";
        p.style.boxShadow = "0px 0px 3px #67c23a inset";

        this.listQuery.activityType.push(tagName);
      }

      this.getList();
    },

    handleCommand(obj) {
      // command == 1 表示通过；command == 2 表示拒绝
      let news = { id: obj.id, activityAuditState: obj.command };

      updateNewsAuth(news).then((response) => {
        for (const v of this.list) {
          if (v.id === obj.id) {
            v.activityAuditState = obj.command;
            break;
          }
        }
      });
    },

    getRelativeActivity(id) {
      if (id) {
        for (let v of this.activityList) {
          if (v.id === id) {
            return v.title;
          }
        }
      }

      return "";
    },
  },

  watch: {
    $route(to, from) {
      this.title = this.$route.meta.title;
      this.textMap.create = "创建-" + this.title;
      this.contentType = this.$route.name;

      this.resetForm();
      this.resetList();

      if (this.contentType == "activityNews") {
        listNews({
          type: "activity",
          page: 1,
          limit: 2000,
          sort: "+id",
          activityAuditState: 1,
        })
          .then((response) => {
            this.activityList = response.data.data.items;
          })
          .catch(() => {
            this.activityList = [];
          });
      }

      this.getList();
    },
  },
};
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
  border-radius: 178px;
}

.el-tag + .el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
  margin-top: 2px;
  height: 28px;
  line-height: 23px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
</style>
