<template>
  <div class="activity">
    <el-form size="mini" inline>
      <el-form-item label="活动名称">
        <el-input v-model="searchForm.campaignName" placeholder="输入活动名称名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button size="mini" type="primary" icon="el-icon-search" @click="getActivityList()">搜索</el-button>
        <el-button size="mini" plain type="primary" icon="el-icon-add" @click="activityShow = true">新增活动</el-button>
        <el-button size="mini" plain icon="el-icon-refresh" @click="init">重置</el-button>
      </el-form-item>
    </el-form>
    <div style="margin-top:20px">
      <el-table v-loading="loading" max-height="700" border highlight-current-row :data="tableData"
        :header-cell-style="{ 'background-color': '#E4E7ED', color: '#000' }" style="width: 100%;">
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-form label-position="left" class="demo-table-expand">
              <el-form-item label="活动名称">
                <span>{{ props.row.campaignName }}</span>
              </el-form-item>
              <el-form-item label="活动说明">
                <span>{{ props.row.campaignContent }}</span>
              </el-form-item>
              <el-form-item label="活动时间">
                <span>{{ props.row.effectiveStartTime }}-{{ props.row.effectiveEndTime }}</span>
              </el-form-item>
              <el-form-item label="活动文件">
                <div v-if="props.row.fileName != '' && props.row.fileName != null">
                  <el-popconfirm title="确定要下载文件吗" v-for="(item, index) in  props.row.fileName.split(',')"
                    @confirm="downLoad(props.row.fileUrl, index)">
                    <el-button size="mini" type="primary" icon="el-icon-folder-opened" plain slot="reference">{{ item
                    }}</el-button>
                  </el-popconfirm>
                </div>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column prop="campaignName" label="活动名称" />
        <el-table-column prop="campaignContent" label="活动说明" />
        <el-table-column label="发起人" width="150">
          <template slot-scope="scope">
            <span>
              {{ getUser(scope.row.createId) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="发起时间" width="180" />
        <el-table-column label="活动状态" width="100">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.campaignStatus == 0" type="danger">失效</el-tag>
            <el-tag v-else type="success">生效</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="活动时间">
          <template slot-scope="scope">
            <span>
              {{ scope.row.effectiveStartTime }}-{{ scope.row.effectiveEndTime }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="审核状态" width="100">
          <template slot-scope="scope">
            <span v-if="scope.row.auditStatus == 0" style="color:#409EFF">待审核</span>
            <span v-if="scope.row.auditStatus == 1" style="color:#67C23A">通过</span>
            <span v-if="scope.row.auditStatus == 2" style="color:#F56C6C">驳回</span>
          </template>
        </el-table-column>
        <el-table-column label="状态管理" width="100">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.campaignStatus" :active-value="1" :inactive-value="0"
              @change="switchChange($event, scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="100">
          <template slot-scope="scope">
            <!-- <el-button type="text" @click="detailTemplate(scope.row)">查看</el-button> -->
            <el-button v-if="scope.row.auditStatus == 0" @click="editTemplate(scope.row)" type="text">编辑</el-button>
            <el-button v-else type="text" style="color: #909090;">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination style="float: right" @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="searchForm.pageNum" :page-sizes="[10, 20, 30, 40, 50]"
          layout="total, sizes, prev, pager, next, jumper" :total="total" :page-size="searchForm.pageSize">
        </el-pagination>
      </div>
    </div>

    <el-dialog :title="isEdit == 0 ? '新建活动' : '编辑活动'" :visible.sync="activityShow" width="50%" top="5vh"
      :close-on-click-modal="false" :close-on-press-escape="false" :show-close="false">
      <el-form ref="form" :model="form" label-width="120px" style="width:60%">
        <el-form-item label="活动名称" required>
          <el-input placeholder="请输入活动名称" v-model="form.campaignName"></el-input>
        </el-form-item>
        <el-form-item label="活动说明" required>
          <el-input type="textarea" :rows="2" placeholder="请输入活动说明" v-model="form.campaignContent"></el-input>
        </el-form-item>
        <el-form-item label="活动开始时间" required>
          <el-date-picker v-model="form.effectiveStartTime" type="datetime" placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="活动结束时间" required>
          <el-date-picker v-model="form.effectiveEndTime" type="datetime" placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="活动状态">
          <el-radio v-model="form.campaignStatus" :label="0">失效</el-radio>
          <el-radio v-model="form.campaignStatus" :label="1">生效</el-radio>
        </el-form-item>
        <el-form-item label="活动文件" required v-if="isEdit == 0">
          <div>
            <el-upload :auto-upload="false" :file-list="fileList" :limit="1" :multiple="false" :on-change="onChange"
              :on-remove="handleRemove" action="#" class="upload-demo" drag>
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">
                将文件拖到此处，或<em>点击上传</em>
              </div>
              <div slot="tip" class="el-upload__tip" style="font-size: 14px; color: red">
                支持文件上传：doc、docx
              </div>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="已上传文件" v-if="isEdit == 1">
          <el-tag v-for="(item, index) in fileName">{{ item }}</el-tag>
        </el-form-item>
        <el-form-item label="审核模板" required>
          <div style="display:flex">
            <el-select v-model="form.auditTemplateId" placeholder="请选择">
              <el-option v-for="item in templateList" :key="item.id" :label="item.templateName" :value="item.id">
              </el-option>
            </el-select>
            <el-button style="margin-left:20px" size="small" @click="goAdd">新增</el-button>
            <el-button size="small" @click="getTemplate">刷新</el-button>
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeShow">取 消</el-button>
        <el-button type="primary" @click="createClick">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<style>
.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>
<script>
import filter from '../../common/filter.js'
import { post, get } from "@/api/common";
import { mapState } from 'vuex';
export default {
  data () {
    return {
      imgUrl: process.env.VUE_APP_BASE_IMG_URL,
      imgapi: process.env.VUE_APP_BASE_IMG_API,
      activityShow: false,
      searchForm: {
        campaignName: "",
        pageNum: 1,
        pageSize: 10,
      },
      total: 0,
      form: {
        campaignName: "",
        campaignContent: "",
        campaignStatus: 1,
        effectiveStartTime: "",
        effectiveEndTime: "",
        auditTemplateId: null,
        fileUrl: '',
        draft: 1,
        createId: ""
      },
      tableData: [],
      loading: true,
      templateList: [],
      fileList: [],
      arr: [],
      userList: [],
      editForm: {},
      isEdit: 0,
      fileName: []
    }
  },
  computed: {
    ...mapState(['user'])
  },
  mounted () {
    this.getActivityList()
    this.getTemplate()
    this.getUserList()
  },
  methods: {
    downLoad (fileUrl, index) {
      let fileArr = fileUrl.split(',')
      window.open(fileArr[index])
    },
    goAdd () {
      const routeUrl = this.$router.resolve({ path: '/examine/flowPath/index' })
      window.open(routeUrl.href, '_blank')
    },
    init () {
      this.searchForm = {
        campaignName: "",
        pageNum: 1,
        pageSize: 10,
      }
      this.getActivityList()
    },
    switchChange (e, row) {
      row.campaignStatus = e
      post('/campaign/update', row).then(res => {
        if (res.code == 10000) {
          this.$message.success('编辑成功!')
          this.getActivityList()
        }
      })
    },
    detailTemplate (row) {

    },
    editTemplate (row) {
      if (row.fileName != '' && row.fileName != null) {
        this.fileName = row.fileName.split(',')
      }
      this.activityShow = true
      this.isEdit = 1
      this.editForm = row
      for (let key in this.form) {
        this.form[key] = row[key]
      }
    },
    closeShow () {
      this.fileName = []
      for (let key in this.form) {
        if (key != 'createId' && key != 'draft') {
          this.form[key] = ''
        }
      }
      this.form.campaignStatus = 1
      this.form.auditTemplateId = null
      this.activityShow = false
      this.isEdit = 0
      this.fileList = []
    },
    // 创建
    createClick () {
      if (this.form.campaignName == '') {
        return this.$message.error('活动名称不能为空！')
      }
      if (this.form.auditTemplateId == '') {
        return this.$message.error('审核模板不能为空！')
      }
      let startTime = new Date(this.form.effectiveStartTime).getTime()
      let endTime = new Date(this.form.effectiveEndTime).getTime()
      if (startTime >= endTime) {
        return this.$message.error('活动开始时间不能大于结束时间')
      }
      if (this.isEdit == 0) {
        let urlarr = []
        let fileName = []
        if (this.fileList.length > 0) {
          this.fileList.forEach(val => {
            fileName.push(val.name)
            let url = this.arr.find(item => item.uid == val.uid).url
            urlarr.push(url)
          })
        }
        this.form.effectiveStartTime = filter.frDateTime(this.form.effectiveStartTime)
        this.form.effectiveEndTime = filter.frDateTime(this.form.effectiveEndTime)
        if (urlarr.length > 0) {
          this.form.fileUrl = urlarr.join(',')
          this.form.fileName = fileName.join(',')
        }
        post('/campaign/create', this.form).then(res => {
          if (res.code == 10000) {
            this.$message.success('创建成功!')
            this.getActivityList()
            this.closeShow()
          }
          // console.log(res)
        })
      } else {
        for (let key in this.form) {
          this.editForm[key] = this.form[key]
        }
        if (this.editForm.effectiveStartTime != this.form.effectiveStartTime) {
          this.editForm.effectiveStartTime = filter.frDateTime(this.form.effectiveStartTime)
        }
        if (this.editForm.effectiveEndTime != this.form.effectiveEndTime) {
          this.editForm.effectiveEndTime = filter.frDateTime(this.form.effectiveEndTime)
        }
        post('/campaign/update', this.editForm).then(res => {
          if (res.code == 10000) {
            this.$message.success('编辑成功!')
            this.getActivityList()
            this.closeShow()
          }
        })
      }

    },
    // 文件选择
    onChange (file, fileList) {
      this.fileList = fileList
      let formData = new FormData
      formData.append('file', file.raw)
      formData.append('type', 1)
      if (file.raw) {
        post(this.imgapi, formData).then(res => {
          let obj = {
            uid: file.uid,
            url: this.imgUrl + res.data
          }
          this.arr = [obj]

        }).catch(err => {
          if (err.data.code == 500) {
            this.fileList = []
          }
          // console.log(err)
        })
      }
    },
    // 删除文件
    handleRemove (file, fileList) {
      this.fileList = fileList
    },
    getUserList () {
      get("/sysUser/page", {}).then((res) => {
        this.userList = JSON.parse(JSON.stringify(res.data.list))
        res.data.list.forEach(val => {
          if (val.name == this.user.name) {
            this.form.createId = val.id
          }
        })
      })
    },
    getUser (id) {
      let name = this.userList.find(val => id == val.id)
      if (name != undefined) {
        return name.name
      } else {
        return ''
      }
    },
    // 获取审核模板
    getTemplate () {
      post('/auditTemplate/page', { pageNum: 1, pageSize: 9999 }).then(res => {
        this.templateList = res.data.records
      })
    },
    getActivityList () {
      post('/campaign/page', this.searchForm).then(res => {
        // console.log(res)
        if (res.code == 10000) {
          this.loading = false
          this.tableData = res.data.records
          this.total = res.data.total
        }
      })
    },
    handleSizeChange (val) {
      this.searchForm.pageNum = 1
      this.searchForm.pageSize = val
      this.getActivityList()
    },
    handleCurrentChange (val) {
      this.searchForm.pageNum = val
      this.getActivityList()
    },
  }
}
</script>

<style>
.activity {
  padding: 20px !important;
}
</style>