<template>
  <div id="activity_list" class="app-container">
    <div v-loading.fullscreen.lock="loadingFull" />
    <el-button
      type="primary"
      size="small"
      style="margin-bottom: 20px"
      @click="visible.type = 'add'; visible.activity = true"
    >
      添加活动
    </el-button>
    <el-table
      :data="table"
      :header-cell-style="{ background: '#f8fbfc' }"
      class="tableBorder"
      border
      stripe
    >
      <el-table-column
        prop="id"
        label="#"
        width="70"
        align="center"
      />
      <el-table-column
        prop="title"
        label="活动名称"
        align="center"
      />
      <el-table-column
        label="持续时间"
        align="center"
        width="400"
      >
        <template
          slot-scope="{ row }"
        >
          {{ `${row.start_time} - ${row.end_time}` }}
        </template>
      </el-table-column>
      <el-table-column
        label="荣誉门槛"
        align="center"
      >
        <template slot-scope="{ row }">
          <p
            v-for="item in row.activity_limit_honor"
            :key="item.id"
          >
            {{ item.title }}({{ item.account }})
          </p>
        </template>
      </el-table-column>
      <!-- <el-table-column
        label="降级门槛"
        align="center"
      >
        <template slot-scope="{ row }">
          <p
            v-for="item in row.activity_limit_down"
            :key="item.id"
          >
            {{ item.title }}({{ item.account }})
          </p>
        </template>
      </el-table-column> -->
      <!-- <el-table-column
        prop="big_gift"
        label="大礼包门槛"
        align="center"
      />
      <el-table-column
        prop="honor_wall"
        label="荣誉墙门槛"
        align="center"
      />-->
      <el-table-column
        prop="crown_down"
        label="代理公司降级门槛"
        align="center"
      />
      <!-- <el-table-column
        prop="top_down"
        label="销售经理降级门槛"
        align="center"
      /> -->
      <el-table-column
        label="活动状态"
        align="center"
        width="100"
      >
        <template slot-scope="{ row }">
          <el-tag :type="activityStatus(row).type">{{ activityStatus(row).name }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="disabled"
        label="状态"
        width="100"
        align="center"
      >
        <template
          slot-scope="{ row }"
        >
          <el-tag :type="row.disabled !==0 ? 'danger' : 'success'">{{ row.disabled === 0 ? '正常' : '已禁用' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="160"
        align="center"
      >
        <template
          slot-scope="{ row }"
        >
          <el-button
            type="primary"
            size="mini"
            @click="handleEdit(row)"
          >
            修改
          </el-button>
          <!-- <el-button
            size="mini"
            @click="handleDisable(row)"
          >
            {{ row.disabled === 0 ? '禁用' : '启用' }}
          </el-button> -->
          <!-- <el-button
            size="mini"
            @click="handleDelete(row)"
          >
            删除
          </el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <pagination
      :total="tableTotal"
      :limit="searchParams.page_size"
      :page="searchParams.page_index"
      @pagination="changePagination"
      @update:limit="changePagination"
    />
    <!-- 添加 -->
    <el-dialog
      :title="visible.type === 'add' ? '添加活动' : '修改活动'"
      :visible.sync="visible.activity"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      :before-close="handleCancel"
    >
      <el-form
        ref="level"
        :model="level"
        :rules="levelRules"
        label-width="150px"
      >
        <el-form-item label="活动标题:" prop="title">
          <el-input
            v-model="level.title"
          />
        </el-form-item>
        <el-form-item
          label="活动持续时间:"
          prop="time"
        >
          <el-date-picker
            v-model="level.time"
            type="datetimerange"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="荣誉门槛: ">
          <el-button type="primary" size="mini" @click="getHonorList">添加</el-button>
          <ul class="zengpin_list">
            <li v-for="(item, i) in level.honor" :key="i">
              <p>{{ item.title }} - {{ item.account }}</p>
              <i class="el-icon-minus gift_icon" @click="deleteHonor(i)" />
              <i class="el-icon-edit-outline gift_icon" @click="editHonor(item, i)" />
            </li>
          </ul>
        </el-form-item>
        <!-- <el-form-item label="降级门槛: ">
          <el-button type="primary" size="mini" @click="visible.down_type = true; visible.down = true;">添加</el-button>
          <ul class="zengpin_list">
            <li v-for="(item, i) in level.down" :key="i">
              <p>{{ item.title }} - {{ item.account }}</p>
              <i class="el-icon-minus gift_icon" @click="deleteDown(i)" />
              <i class="el-icon-edit-outline gift_icon" @click="editDown(item)" />
            </li>
          </ul>
        </el-form-item> -->
        <el-form-item label="代理公司降级门槛: " prop="crown_down">
          <el-input v-model="level.crown_down" type="text" />
        </el-form-item>
        <!-- <el-form-item label="销售经理降级门槛: ">
          <el-input v-model="level.top_down" type="text" />
        </el-form-item> -->
        <el-form-item label="添加赠品:">
          <el-button type="primary" size="small" @click="addGift">添加</el-button>
          <ul class="zengpin_list">
            <li v-for="item in level.gifts" :key="item.id">
              <el-image
                style="width: 38px; height: 38px;margin-right:10px;"
                :src="item.img"
                fit="fill"
              />
              <p>{{ item.name }} - {{ item.num }}套 - (起送数量: {{ item.limit_num || 1 }}套)</p>
              <i class="el-icon-minus gift_icon" @click="deleteGiftItem(item.id)" />
              <i class="el-icon-edit-outline gift_icon" @click="editGiftItem(item)" />
            </li>
          </ul>
        </el-form-item>
        <el-form-item label="活动介绍: ">
          <el-input v-model="level.contents" type="textarea" :autosize="{ minRows: 10, maxRows: 99}" />
        </el-form-item>
        <el-form-item>
          <el-button
            size="small"
            @click="handleCancel"
          >
            取消
          </el-button>
          <el-button
            type="primary"
            size="small"
            @click="handleSubmit"
          >
            提交
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog
      :title="visible.honor_type ? '添加荣誉门槛' : '修改荣誉门槛'"
      :visible.sync="visible.honor"
      width="420px"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <el-form label-width="100px">
        <el-form-item label="名称: ">
          <el-select v-model="honorForm.title" style="width: 100%;">
            <el-option
              v-for="(v, k, i) in honorList"
              :key="`${k}_${i}`"
              :label="v"
              :value="v"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="金额: ">
          <el-input v-model="honorForm.account" type="text" />
        </el-form-item>
        <el-form-item>
          <el-button size="small" @click="resetHonorForm">取消</el-button>
          <el-button type="primary" size="small" @click="addHonorForm">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog
      :title="visible.down_type ? '添加降级门槛' : '修改降级门槛'"
      :visible.sync="visible.down"
      width="420px"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <el-form label-width="100px">
        <el-form-item label="名称: ">
          <el-input v-model="downForm.title" type="text" />
        </el-form-item>
        <el-form-item label="金额: ">
          <el-input v-model="downForm.account" type="text" />
        </el-form-item>
        <el-form-item>
          <el-button size="small" @click="resetDownForm">取消</el-button>
          <el-button type="primary" size="small" @click="addDownForm">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog
      :title="visible.gift_type ? '添加赠品' : '修改赠品'"
      :visible.sync="visible.gift"
      width="420px"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <el-form label-width="120">
        <el-form-item label="赠品图片:">
          <el-upload
            class="avatar-uploader"
            action=""
            :show-file-list="false"
            :http-request="giftImgUpload"
          >
            <img v-if="giftForm.img" :src="giftForm.img" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
            <i class="el-icon-info">宽高比列为: 1比1</i>
          </el-upload>
        </el-form-item>
        <el-form-item label="赠品名称:">
          <el-input v-model="giftForm.name" type="text" style="width: 300px" />
        </el-form-item>
        <el-form-item label="要求数量:">
          <el-input v-model="giftForm.num" type="text" style="width: 300px" />
        </el-form-item>
        <el-form-item label="起送数量:">
          <el-input v-model="giftForm.limit_num" type="text" style="width: 300px" />
        </el-form-item>
        <el-form-item>
          <el-button size="small" @click="resetFigtForm">取消</el-button>
          <el-button type="primary" size="small" @click="submitGift">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
// api
import {
  getActivityList,
  addActivity,
  disableActivity,
  deleteActivity,
  editActivity,
  uploadGift,
  getHonorList
} from '@/api/activity/list'
// 图片压缩
import compress from '@/utils/compress'

export default {
  data() {
    return {
      loadingFull: false,
      searchParams: {
        page_size: 20,
        page_index: 1,
        search_name: ''
      },
      table: [],
      tableTotal: 0,
      visible: {
        activity: false,
        type: 'add',
        gift: false,
        gift_type: true,
        honor_type: true,
        honor: false,
        down_type: true,
        down: false
      },
      level: {
        time: '',
        title: '',
        id: '',
        gifts: [],
        contents: '',
        honor: [],
        down: [],
        crown_down: '',
        top_down: ''
      },
      levelRules: {
        title: [
          { required: true, message: '请输入活动标题', trigger: 'blur' }
        ],
        time: [
          { required: true, message: '请选择活动持续时间', trigger: 'blur' }
        ],
        crown_down: [
          { required: true, message: '请设置代理公司降级门槛', trigger: 'blur' }
        ],
        top_down: [
          { required: true, message: '请设置销售经理降级门槛', trigger: 'blur' }
        ]
      },
      setPickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7
        }
      },
      giftForm: {
        img: '',
        name: '',
        num: '',
        id: '',
        limit_num: ''
      },
      honorForm: {
        title: '',
        account: ''
      },
      downForm: {
        title: '',
        account: ''
      },
      oldGiftId: [],
      oldHonorId: [],
      oldDownId: [],
      editActivityIsGonging: false,
      honorList: [],
      editHonorId: -1
    }
  },
  created() {
    this.getActivityList()
  },
  methods: {
    getHonorList() {
      const loading = this.$loading()
      getHonorList().then(res => {
        loading.close()
        if (res.code === 200) {
          this.honorList = res.data
          this.visible.honor_type = true
          this.visible.honor = true
        } else {
          this.$message.error(res.message || '获取荣誉门槛设置失败')
        }
      }).catch(() => {
        loading.close()
        this.$message.error('获取荣誉门槛设置失败')
      })
    },
    deleteDown(i) {
      this.level.down.splice(i, 1)
    },
    editDown(data) {
      const { title, account } = data
      this.downForm.title = title
      this.downForm.account = account
      this.visible.down_type = false
      this.visible.down = true
    },
    resetDownForm() {
      this.downForm.title = ''
      this.downForm.account = ''
      this.visible.down = false
      this.visible.down_type = true
    },
    addDownForm() {
      const { title, account } = this.downForm
      if (!title) {
        this.$message.error('请填写门槛名称')
        return false
      }
      if (!account) {
        this.$message.error('请填写门槛金额')
        return false
      }
      this.level.down.push({ title, account })
      this.resetDownForm()
    },
    editHonor(data, i) {
      const { title, account } = data
      this.honorForm.title = title
      this.honorForm.account = account
      this.editHonorId = i
      this.visible.honor_type = false
      this.visible.honor = true
    },
    deleteHonor(i) {
      this.level.honor.splice(i, 1)
    },
    resetHonorForm() {
      this.honorForm.title = ''
      this.honorForm.account = ''
      this.visible.honor = false
      this.visible.honor_type = true
    },
    addHonorForm() {
      const { title, account } = this.honorForm
      if (!title) {
        this.$message.error('请填写门槛名称')
        return false
      }
      if (!account) {
        this.$message.error('请填写门槛金额')
        return false
      }
      this.editHonorId === -1 ? this.level.honor.push({ title, account }) : Object.assign(this.level.honor[this.editHonorId], { title, account })
      this.resetHonorForm()
    },
    // 活动状态
    activityStatus(data) {
      const now = Date.now()
      let { start_time, end_time } = data
      start_time = start_time.replace(/-/g, '/')
      end_time = end_time.replace(/-/g, '/')
      if (now < new Date(start_time).getTime()) {
        return {
          type: 'primary',
          name: '未开始'
        }
      } else if (now > new Date(end_time).getTime()) {
        return {
          type: 'info',
          name: '已结束'
        }
      } else {
        return {
          type: 'success',
          name: '进行中'
        }
      }
    },
    editGiftItem(item) {
      if (this.editActivityIsGonging) {
        this.$message.error('活动进行中,禁止修改赠品')
        return false
      }
      const { name, num, id, img, limit_num } = item
      this.giftForm = {
        name, num, id, img, limit_num
      }
      this.visible.gift = true
      this.visible.gift_type = false
    },
    addGift() {
      if (this.editActivityIsGonging) {
        this.$message.error('活动进行中,禁止添加赠品')
        return false
      }
      this.visible.gift = true
      this.visible.gift_type = true
    },
    deleteGiftItem(i) {
      if (this.editActivityIsGonging) {
        this.$message.error('活动进行中,禁止删除赠品')
        return false
      }
      const i1 = this.level.gifts.findIndex(({ id }) => id === i)
      this.level.gifts.splice(i1, 1)
    },
    async giftImgUpload({ file }) {
      const formdata = new FormData()
      formdata.append('file', await compress(file))
      uploadGift(formdata).then(res => {
        if (res.code === 200) {
          this.giftForm.img = res.data
        } else {
          this.$message.error(res.message)
        }
      }).catch(e => {
        console.log(e)
        this.$message.error('上传赠品图片失败')
      })
    },
    submitGift() {
      if (this.visible.gift_type) {
        if (this.level.gifts.length > 0) {
          this.level.gifts.sort((a, b) => b.id - a.id)
        }
        this.giftForm.id = this.level.gifts.length === 0 ? '0.1' : `${this.level.gifts[0].id + 1}.1`
        this.level.gifts.unshift(this.giftForm)
      } else {
        const index = this.level.gifts.findIndex(({ id }) => id === this.giftForm.id)
        this.level.gifts.splice(index, 1, this.giftForm)
      }
      this.resetFigtForm()
    },
    resetFigtForm() {
      this.giftForm = {
        img: '',
        name: '',
        num: '',
        id: '',
        limit_num: ''
      }
      this.visible.gift_type = true
      this.visible.gift = false
    },
    // 获取活动列表
    async getActivityList() {
      this.loadingFull = true
      try {
        const res = await getActivityList(this.searchParams)
        const { message, code } = res
        if (code === 200) {
          const { list, total } = res.data
          this.table = list
          this.tableTotal = total
        } else {
          this.$message.error(message)
        }
      } catch (e) {
        console.log(`获取系统设置活动失败:${e}`)
      }
      this.loadingFull = false
    },
    // 分页页码变化
    changePagination(data) {
      const { page, limit } = data
      this.listQuery.page_size = limit
      this.listQuery.page_index = page
      this.getActivityList()
    },
    // 取消添加
    handleCancel() {
      this.level = {
        time: '',
        honor_wall: '',
        big_gift: '',
        title: '',
        id: '',
        gifts: [],
        contents: '',
        honor: [],
        down: []
      }
      this.oldGiftId = []
      this.oldHonorId = []
      this.oldDownId = []
      this.editActivityIsGonging = false
      this.$refs.level.resetFields()
      this.visible.activity = false
    },
    // 添加
    handleSubmit() {
      this.$refs.level.validate((valid) => {
        if (valid) {
          const { id, time, title, gifts, contents, honor, down, top_down, crown_down } = this.level
          if (this.visible.type === 'add') {
            this.addActivity({
              title,
              start_time: time && time.length > 0 ? time[0] : '',
              end_time: time && time.length > 0 ? time[1] : '',
              gift: gifts,
              contents,
              honor,
              down,
              top_down,
              crown_down
            })
          } else {
            const old_i = this.level.gifts.filter(({ id }) => Number.isInteger(id)).map(({ id }) => id)
            const old = this.level.gifts.filter(({ id }) => Number.isInteger(id))
            const new_i = this.level.gifts.filter(({ id }) => !Number.isInteger(id))
            const del_i = this.oldGiftId.filter(i => old_i.indexOf(i) === -1)

            const old_i_h = this.level.honor.filter(({ id }) => Number.isInteger(id)).map(({ id }) => id)
            const old_h = this.level.honor.filter(({ id }) => Number.isInteger(id))
            const new_i_h = this.level.honor.filter(({ id }) => !Number.isInteger(id))
            const del_i_h = this.oldHonorId.filter(i => old_i_h.indexOf(i) === -1)

            const old_i_d = this.level.down.filter(({ id }) => Number.isInteger(id)).map(({ id }) => id)
            const old_d = this.level.down.filter(({ id }) => Number.isInteger(id))
            const new_i_d = this.level.down.filter(({ id }) => !Number.isInteger(id))
            const del_i_d = this.oldDownId.filter(i => old_i_d.indexOf(i) === -1)

            this.editActivity({
              title,
              start_time: time && time.length > 0 ? time[0] : '',
              end_time: time && time.length > 0 ? time[1] : '',
              id,
              new_gift: new_i,
              del_i,
              old_gift: old,
              contents,
              new_honor: new_i_h,
              del_i_honor: del_i_h,
              old_honor: old_h,
              new_down: new_i_d,
              del_i_down: del_i_d,
              old_down: old_d,
              down,
              top_down,
              crown_down
            })
          }
        } else {
          return false
        }
      })
    },
    // 添加
    async addActivity(data) {
      this.loadingFull = true
      await addActivity(data).then(res => {
        this.loadingFull = false
        if (res.code === 200) {
          this.$message.success(res.message)
          this.handleCancel()
          this.getActivityList()
        } else {
          this.$message.error(res.message)
        }
      }).catch(e => {
        this.loadingFull = false
      })
    },
    // 修改
    async editActivity(data) {
      this.loadingFull = true
      await editActivity(data).then(res => {
        this.loadingFull = false
        if (res.code === 200) {
          this.$message.success(res.message)
          this.handleCancel()
          this.getActivityList()
        } else {
          this.$message.error(res.message)
        }
      }).catch(e => {
        this.loadingFull = false
      })
    },
    // 点击删除
    handleDelete(row) {
      const { id, title } = row
      this.$confirm(`确认删除${title}?`, '删除活动', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteActivity(id)
      })
    },
    // 删除
    async deleteActivity(id) {
      const res = await deleteActivity({ id })
      try {
        const { message, code } = res
        if (code === 200) {
          this.$message.success(message)
          this.getActivityList()
        } else {
          this.$message.error(message)
        }
      } catch (e) {
        let message = res.message ? res.message : e.message
        message = e.message ? e.message : '请求失败'
        this.$message.error(message)
      }
    },
    // 禁用启用
    handleDisable(row) {
      const { id, status } = row
      if (status === 0) {
        this.$confirm('确认禁用该活动吗?', '禁用活动', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.disableActivity(id)
        })
      } else {
        this.disableActivity(id)
      }
    },
    // 禁用启用
    async disableActivity(id) {
      const res = await disableActivity({ id })
      try {
        const { message, code } = res
        if (code === 200) {
          this.$message.success(message)
          this.getActivityList()
        } else {
          this.$message.error(message)
        }
      } catch (e) {
        let message = res.message ? res.message : e.message
        message = e.message ? e.message : '请求失败'
        this.$message.error(message)
      }
    },
    // 修改
    handleEdit(row) {
      const { id, title, start_time, end_time, gift, contents, activity_limit_honor, top_down, crown_down } = row
      this.level.id = id
      this.level.title = title
      this.level.time = [start_time, end_time]
      this.level.gifts = gift
      this.level.contents = contents
      this.level.honor = activity_limit_honor
      // this.level.down = activity_limit_down
      this.oldGiftId = gift.map(item => item.id)
      this.oldHonorId = activity_limit_honor.map(item => item.id)
      // this.oldDownId = activity_limit_down.map(item => item.id)
      this.level.top_down = top_down
      this.level.crown_down = crown_down
      this.visible.type = 'edit'
      this.visible.activity = true
      this.editActivityIsGonging = !!((Date.now() > new Date(start_time).getTime() && Date.now() < new Date(end_time).getTime()))
    }
  }
}
</script>
<style lang="scss">
  #activity_list {
    .zengpin_list {
      padding: 0;
      margin: 0;
      list-style: none;
      li {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        margin-bottom: 10px;
        &:nth-of-type(1) {
          margin-top: 10px;
        }
        p {
          min-width: 200px;
          margin: 0;
        }
        .gift_icon {
          width: 20px;
          height: 20px;
          line-height: 20px;
          text-align: center;
          background: #606266;
          color: #ffffff;
          border-radius: 50%;
          cursor: pointer;
          margin-left: 10px;
          &:hover {
            background: #409EFF !important;
          }
        }
      }
    }
    .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: 130px;
      height: 130px;
      line-height: 130px;
      text-align: center;
    }
    .avatar {
      width: 130px;
      height: 130px;
      display: block;
    }
  }
</style>
