<template>
  <div>
    <p class="text-2xl font-bold mb-5">Banner管理</p>
    <!-- timepicker -->
    <span class="font-semibold">发布时间：</span>
    <timerange
      class="mr-3"
      @getNewTime="getNewTime"
      :startTime="queryParam.startTime"
      :endTime="queryParam.endTime"
    />
    <a-button type="primary" style="margin-right: 10px;" @click="handleClickQuery">
      查询
    </a-button>
    <!-- 新增 -->
    <a-button type="primary" @click="showModal">新增</a-button>
    <!-- 上传弹窗 -->
    <a-modal
      :afterClose="afterAddNewBannerModalClose"
      title="新增"
      v-model="visible"
      :centered="true"
      footer=""
      :closable="false"
    >
      <a-form-model
        :model="form"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 10 }"
        ref="ruleForm"
        :rules="rules"
      >
        <a-form-model-item label="Banner名称" prop="name">
          <a-input
            style="width: 200px;"
            v-model="form.name"
            placeholder="请输入名称"
          />
        </a-form-model-item>
        <a-form-model-item label="Banner位置">
          <span class="text-sm text-black">首页</span>
        </a-form-model-item>
        <a-form-model-item label="上传图片" :required="true" prop="fileList">
          <a-upload
            :beforeUpload="beforeUpload"
            name="uploadFile"
            action="/proxyApi/api/v1/image/upload"
            :accept="ACCEPT_IMAGE_TYPE"
            :file-list="form.fileList"
            @change="handleChange"
            required
          >
            <a-button style="width: 200px;" :disabled="alreadlyHasOneImage">
              <a-icon type="upload" />
              点击上传
            </a-button>
          </a-upload>
        </a-form-model-item>
        <a-form-model-item :wrapper-col="{ span: 9, offset: 5 }">
          <a-button type="primary" @click="onSubmit">发布</a-button>
          <a-button style="margin-left: 10px;" @click="visible = false">
            取消
          </a-button>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <!-- banner列表 -->
    <a-table
      :columns="columns"
      :data-source="bannerList"
      :loading="tableLoading"
      :pagination="false"
      style="text-align: center; margin-top: 40px;"
      bordered
    >
      <template #created_at="text">
        {{ text | formatDate }}
      </template>
      <template #banner_status="text">
        {{ text | filtereBannerStatus }}
      </template>
      <template #location="text">
        {{ text | filterBannerLocation }}
      </template>
      <span slot="file_name" slot-scope="text, record">
        <a-icon
          type="picture"
          @click="preview(record.file_name)"
          style="fontsize: 20px; color:#3E4FAF"
        />
        <el-image-viewer
          v-if="showViewer"
          fit="scale-down"
          :on-close="closeViewer"
          :url-list="[url]"
        />
      </span>
      <span slot="action" slot-scope="text, record">
        <span v-if="record.banner_status == eBannerStatus.editable">
          <a @click="addBanner(record)">上架</a>
          <a-divider type="vertical" />
          <a @click="deleteBanner(record)">删除</a>
        </span>
        <a
          v-else-if="(record.banner_status == eBannerStatus.published)"
          @click="removeBanner(record)"
        >
          下架
        </a>
      </span>
    </a-table>
    <a-pagination
      class="text-right mt-4"
      :current="current"
      :total="total"
      :pageSize="PAGE_SIZE"
      @change="handlePaginationChange"
    ></a-pagination>
    <!-- 操作Modal -->
    <a-modal
      :title="title"
      v-model="show"
      :centered="true"
      :closable="false"
      :confirmLoading="modalLoading"
      @ok="handleOk"
      @cancle="show = false"
    >
      <p class="text-center">{{ text }}</p>
    </a-modal>
  </div>
</template>
<script lang="ts">
import Vue from 'vue'
import { FormModel, message } from 'ant-design-vue'
import timerange from '@/components/TimePicker/index.vue'
import { bannerList } from '@/mock/index'
import { columns } from '@/const/columns/bannerColumns'
import { modalType } from './const'
import {
  bannerQuery,
  bannerModify,
} from '@/service/BannerManagementService/index'
import {
  ACCEPT_IMAGE_TYPE,
  isAcceptImageType,
  TOAST_TEXT,
  TOAST_TEXT2,
  MAX_IMAGE_SIZE,
} from '@/const/config/upload'
import { bannerAdd } from '@/service/BannerManagementService/index'
import { PAGE_SIZE } from '@/const/config/page'
import { iBannerItem } from '@/service/BannerManagementService/types'
import { eBannerStatus } from '@/types/banner'
import FileService from '@/service/FileService/index'

export default Vue.extend({
  components: {
    'el-image-viewer': () =>
      import('element-ui/packages/image/src/image-viewer.vue'),
    timerange,
  },
  computed: {
    columns() {
      return columns
    },
    current(): number {
      return this.queryParam.offset / this.queryParam.limit + 1
    },
    alreadlyHasOneImage(): boolean {
      return this.form.fileList.length == 1
    },
  },
  mounted() {
    this.fetchList()
  },
  data() {
    let list = bannerList
    return {
      uuid: '',
      eBannerStatus,
      ACCEPT_IMAGE_TYPE,
      visible: false,
      show: false,
      modalLoading: false,
      title: '',
      text: '',
      modalType: modalType.on,
      queryParam: {
        startTime: undefined as undefined | number,
        endTime: undefined as undefined | number,
        limit: PAGE_SIZE,
        offset: 0,
        location: 0,
      },
      tableLoading: false,
      bannerList: [] as iBannerItem[],
      total: 0,
      form: {
        name: '',
        file_hash: '',
        fileList: [],
      },
      rules: {
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        fileList: [
          { required: true, message: '请上传文件', trigger: 'change' },
        ],
      },
      PAGE_SIZE,
      showViewer: false,
      url: '',
      list,
      img: require('../../../assets/pic.png'),
    }
  },
  methods: {
    handleClickQuery(){
      this.queryParam.offset = 0;
      this.fetchList();
    },
    handlePaginationChange(current: number) {
      this.queryParam.offset = (current - 1) * this.queryParam.limit
      this.fetchList()
    },
    async fetchList() {
      this.tableLoading = true
      const ret = await bannerQuery({
        end_time: this.queryParam.endTime,
        start_time: this.queryParam.startTime,
        limit: this.queryParam.limit,
        offset: this.queryParam.offset,
        location: this.queryParam.location,
        banner_status: 0,
      })
      if (ret.code === 200) {
        this.bannerList = ret.data.items
        this.total = ret.data.total
        this.tableLoading = false
      }
    },
    afterAddNewBannerModalClose() {
      const ref = this.$refs.ruleForm as FormModel
      ref.resetFields()
    },
    getNewTime(startTime: number, endTime: number) {
      this.queryParam.startTime = startTime
      this.queryParam.endTime = endTime
    },
    addBanner(record: any) {
      this.uuid = record.uuid
      this.modalType = modalType.on
      this.show = true
      this.title = '上架Banner'
      this.text = '确定上架该Banner吗？'
    },
    removeBanner(record: any) {
      this.uuid = record.uuid
      this.modalType = modalType.off
      this.show = true
      this.title = '下架Banner'
      this.text = '确定下架该Banner吗？'
    },
    deleteBanner(record: any) {
      this.uuid = record.uuid
      this.modalType = modalType.delete
      this.show = true
      this.title = '删除Banner'
      this.text = '确定删除该Banner吗？'
    },
    async handleOk(record: any) {
      this.modalLoading = true
      try {
        if (this.modalType == modalType.on) {
          await bannerModify({
            banner_status: eBannerStatus.published,
            uuid: this.uuid,
          })
        } else if (this.modalType == modalType.off) {
          await bannerModify({
            banner_status: eBannerStatus.editable,
            uuid: this.uuid,
          })
        } else if (this.modalType == modalType.delete) {
          await bannerModify({
            banner_status: eBannerStatus.delete,
            uuid: this.uuid,
          })
        }
        this.show = false
        this.fetchList()
      } catch (err) {}
      this.modalLoading = false
    },
    beforeUpload(file: File) {
      const isAccpet = isAcceptImageType(file)
      if (!isAccpet) {
        message.error(TOAST_TEXT)
      }
      const isLt4M = file.size < MAX_IMAGE_SIZE
      if (!isLt4M) {
        message.error(TOAST_TEXT2)
      }
      console.log(isAccpet && isLt4M)

      return isAccpet && isLt4M
    },
    handleChange(info: any) {
      console.log(info, 'show info')
      const fileList = (info.fileList || []).filter((item: any) => {
        return item.status !== undefined
      })
      this.form.fileList = fileList

      if (info.file.status !== 'uploading') {
      }
      if (info.file.status === 'done') {
        if (info.file.response.code === 200) {
          this.form.file_hash = info.file.response.data
        }
      } else if (info.file.status === 'error') {
      }
    },
    showModal() {
      this.visible = true
    },
    preview(file_name: string) {
      this.showViewer = true
      const src = FileService.getInstance().getImageSrc(file_name)
      this.url = src
    },
    closeViewer() {
      this.showViewer = false
    },
    handleCancel(e: Event) {
      this.visible = false
    },
    onSubmit() {
      ;(this.$refs.ruleForm as FormModel).validate((valid) => {
        if (valid) {
          this.visible = false
          bannerAdd({
            file_name: this.form.file_hash,
            location: 1,
            title: this.form.name,
          }).then((ret) => {
            if (ret.code === 200) {
              this.fetchList()
              message.success('发布成功')
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
  },
})
</script>
