<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="theme">
        <el-input
          v-model="queryParams.theme"
          placeholder="请输入标题"
          clearable
        />
      </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"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          >删除
        </el-button>
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      ref="table"
      :data="picList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index" width="80" />
      <el-table-column label="活动主题" align="center" prop="theme" />
      <el-table-column label="活动开始时间" align="center" prop="beginTime" />
      <el-table-column label="活动结束时间" align="center" prop="endTime" />
      <el-table-column label="活动负责人" align="center" prop="fzr" />
      <el-table-column label="所属社团" align="center" prop="orgName" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="附件" align="center" prop="file">
        <template slot-scope="scope">
          <el-carousel trigger="click" height="150px" :interval="4000">
            <el-carousel-item
              v-for="(item, index) in scope.row.file.split(',')"
              :key="index"
            >
              <el-image
                :src="pev + item"
                style="width: 150px; height: 130px"
                :preview-src-list="[pev + item]"
              >
              </el-image>
            </el-carousel-item>
          </el-carousel>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <div>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              >编辑
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              >删除
            </el-button>
          </div>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleCheck(scope.row)"
            >查看
          </el-button>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 添加或编辑社团主题对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="120px"
        style="width: 80%; margin: auto"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="活动主题:" prop="theme">
              <el-input
                v-model="form.theme"
                placeholder="请输入"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="活动开始时间:" prop="beginTime">
              <el-date-picker
                v-model="form.beginTime"
                type="date"
                placeholder="选择活动开始时间"
                style="width: 100%"
                :picker-options="pickerOptionsStart"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="活动结束时间:" prop="endTime">
              <el-date-picker
                v-model="form.endTime"
                type="date"
                placeholder="选择活动结束时间"
                style="width: 100%"
                :picker-options="pickerOptionsEnd"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="活动负责人:" prop="fzr">
              <el-input
                v-model="form.fzr"
                placeholder="请输入"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="所属社团:" prop="orgName">
              <el-input
                v-model="form.orgName"
                placeholder="请输入"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注:" prop="remark">
              <el-input
                v-model="form.remark"
                placeholder="请输入"
                style="width: 100%"
                type="textarea"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item
              prop="file"
              style="
                display: flex;
                text-align: center;
                justify-content: center;
                transform: translateX(-30px);
              "
            >
              <el-upload
                multiple
                v-loading="uploadLoading"
                class="avatar-uploader"
                :action="uploadFileUrl"
                accept="image/*"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <div v-if="form.file.length > 0">
                  <img
                    v-for="(item, index) in form.file"
                    :key="index"
                    :src="pev + item"
                    class="avatar"
                  />
                </div>
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import picAvatar from "@/views/smartSchool/schoolManage/introduce/schoolInfo/profile/picAvatar";
import { changeUserStatus } from "@/api/system/user";
import { uploadImage as commonUpload } from "@/api/common";
import { ExportType, TEXT_SIZE } from "@/enums/common";

import {
  getClubInfo, // 查询社团活动记录列表
  listClubInfo, // 查询社团活动记录列表
  editClubInfo, // 编辑社团活动记录
  addClubInfo, // 新增社团活动记录
  delClubInfo, // 删除社团活动记录
} from "@/api/smartSchool/MassOrganization/clubActivities";

export default {
  name: "communityStyle",
  components: { picAvatar },
  data() {
    return {
      //图片上传列表
      uploadList: [],
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传的图片服务器地址
      pev: process.env.VUE_APP_BASE_API,
      // 输入框字数限制
      TEXT_SIZE,
      srcList: [],
      //是否上传的院徽
      isUploadPic: false,
      //照片是否删除
      options: [
        {
          value: 0,
          label: "否",
        },
        {
          value: 1,
          label: "是",
        },
      ],
      //获取子组件传来的信息
      pic: [],
      // 图片路径
      imageUrl: undefined,
      // 图片上传遮罩层
      uploadLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 园区照片表格数据
      picList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        cis: "",
        theme: "",
      },
      // 表单参数
      form: {
        theme: "",
        beginTime: "",
        endTime: "",
        fzr: "",
        id: "",
        orgName: this.$route.query.name,
        remark: "",
        file: [],
      },
      // 表单校验
      rules: {
        theme: [
          {
            required: true,
            message: "请输入相片名称",
            trigger: "blur",
          },
        ],
        seqencing: [{ required: true, message: "请输入排序", trigger: "blur" }],
        remark: [
          {
            max: TEXT_SIZE,
            message: "备注信息在0到200字之间",
            trigger: "blur",
          },
        ],
      },
      // 作为临时图片展示
      tempImage: "",
      // 导出选项
      exportOptions: {
        title: "选择导出类别",
        open: false,
      },
      //查看状态
      check: false,
      file: "",
      // 开始结束日期限制
      pickerOptionsStart: {
        disabledDate: (time) => {
          if (this.form.endTime) {
            return time.getTime() >= new Date(this.form.endTime).getTime();
          }
        },
      },
      // 结束日期限制
      pickerOptionsEnd: {
        disabledDate: (time) => {
          if (this.form.beginTime) {
            return time.getTime() <= new Date(this.form.beginTime).getTime();
          }
        },
      },
    };
  },
  created() {
    this.getList();
  },
  watch: {
    pic: {
      handler(newValue, oldValue) {
        console.log("watch----oldValue", oldValue);
        console.log("watch----newValue", newValue);
        this.isUploadPic = newValue[3];
      },
    },
  },

  methods: {
    //是否删除 选中值发生变化时id处理函数
    selectChangeHandler(value) {
      this.form.isShow = value;
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      this.picList = [];
      const params = {
        cid: this.$route.query.id,
        theme: this.queryParams.theme,
      };
      getClubInfo(params).then((response) => {
        this.picList = response.rows;
        // this.picList.file = response.rows.file;
        this.total = response.total;
        this.loading = false;
      });
    },

    //获取图片信息
    getSchoolInfoPic(val) {
      this.pic = val;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        params: {},
        id: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        delFlag: null,
        theme: null,
        picUrl: null,
        seqencing: null,
        isShow: 0,
        file: [],
      };
      this.imageUrl = "";
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.throttle(() => {
        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.uploadList = [];
      this.check = false;
      this.reset();
      this.open = true;
      this.title = "新增社团活动记录";
      this.form.orgName = this.$route.query.name;
    },
    /** 编辑按钮操作 */
    handleUpdate(row) {
      this.reset();
      const ids = row.id || this.ids;
      this.uploadList = [];
      this.form.file = [];
      this.form.orgName = this.$route.query.name;
      listClubInfo(ids).then((response) => {
        this.form = response.data;
        this.form.file = response.data.file.split(",");
        this.imageUrl = this.pev + this.form.picUrl;
        this.open = true;
        this.title = "编辑社团活动记录";
      });
    },
    /** 查看按钮操作 */
    handleCheck(row) {
      this.check = true;
      this.open = true;
      this.uploadList = [];
      this.form.file = [];
      const ids = row.id || this.ids;
      listClubInfo(ids).then((response) => {
        this.form = response.data;
        this.form.file = response.data.file.split(",");
        this.open = true;
      });
      this.title = "查看社团活动记录";
    },
    // 上传成功回调
    handleAvatarSuccess(res, file) {
      console.log("response上传成功回调", res);
      console.log("file上传成功回调", file);
      if (res.code == 200) {
        this.uploadList.push(res.fileName);
        this.form.file = this.uploadList;
        console.log("this.form.file5555", this.form.file);
      }
      console.log(this.uploadList, "this.uploadList11111111");
      console.log(this.form.file, "this.form.file2222222222");
      console.log(this.pev, "this.pev33333333");
      console.log(res.fileName, "res.fileName444444");
    },
    // 上传前格式和图片大小限制
    beforeAvatarUpload(file) {
      const type =
        file.type === "image/jpeg" ||
        "image/jpg" ||
        "image/webp" ||
        "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!type) {
        this.$message.error("图片格式不正确!(只能包含jpg，png，webp，JPEG)");
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
      }
      return type && isLt2M;
    },
    //删除图片
    handleRemove(file, fileList) {
      this.imageUrl = "";
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            // 编辑
            const params = {
              id: this.form.id,
              theme: this.form.theme,
              file: this.uploadList.toString(),
            };
            console.log(params, "params");
            editClubInfo(params)
              .then((response) => {
                this.getList();
                this.$message.success("编辑成功");
                this.open = false;
              })
              .catch((err) => {});
          } else {
            // 新增
            const params = {
              cid: this.$route.query.id,
              theme: this.form.theme,
              beginTime: this.form.beginTime,
              endTime: this.form.endTime,
              fzr: this.form.fzr,
              orgName: this.form.orgName,
              file: this.uploadList.toString(),

              remark: this.form.remark,
            };
            console.log(params, "params");
            addClubInfo(params)
              .then((response) => {
                this.getList();
                this.$message.success("新增成功");
                this.open = false;
              })
              .catch((err) => {});
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      if (ids) {
        this.$modal
          .confirm(
            `是否确认删除选中的${
              Object.hasOwnProperty.call(ids, "length") ? ids.length : 1
            }条数据？`
          )
          .then(() => {
            this.$modal.loading("正在处理数据，请稍等...");
            return delClubInfo(ids);
          })
          .then(() => {
            this.$modal.closeLoading();
            this.getList();
            this.$modal.msgSuccess("删除成功");
          })
          .catch(() => {
            this.$modal.closeLoading();
          });
      }
    },
  },
};
</script>
<style scoped>
.avatar,
.avatar-uploader,
.el-icon-plus {
  width: 650px;
}
</style>
