<template>
  <div>
    <!--    <div class="title">{{menuDetail.menuName}}</div>-->
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      ref="crud"
      @refresh-change="refreshChange"
    >

      <template slot="menuLeft" slot-scope="{row}">
        <el-button type="primary" @click="add()">新增图片</el-button>
      </template>
      <template slot="image" slot-scope="{row}">
        <el-image
          style="width: 50px; height: 50px"
          fit="contain"
          :src="row.image"
        >
        </el-image>
      </template>
      <template slot="link" slot-scope="{row}">
        <p @click="openUrl(row)">{{ row.link }}</p>
      </template>
      <template slot="sort" slot-scope="{row}">
        <el-button type="text" v-if="row.sort !== 1" @click="move('up', row)">上移</el-button>
        <el-button type="text" v-if="data.length !== row.$index+1" @click="move('down', row)">下移</el-button>
        <el-button type="text" v-if="row.sort !== 1" @click="move('first', row)">置顶</el-button>
      </template>
      <template slot="isShow" slot-scope="{row}">
        <el-button type="text" @click="statusSelect(row)">{{ row.isShow === '1' ? "显示" : "不显示" }}</el-button>
      </template>
      <template slot="menu" slot-scope="{row}">
        <el-button type="text" @click="modify(row)">编辑</el-button>
        <el-button type="text" @click="del(row)">删除</el-button>
      </template>
    </avue-crud>

    <el-drawer :title="drawerTitle" :visible.sync="viewDrawer" size="60%">
      <avue-form :option="formOption" :upload-before="uploadBefore" v-model="formDrawer" @submit="handleSubmit"
                 ref="form">
      </avue-form>
    </el-drawer>

  </div>
</template>

<script>
import {putFile} from "@/api/resource/oss";
import {isURL} from '@/util/validate'
import {
  getCarouselList,
  getCarouselAdd,
  getCarouselEdit,
  getCarouselDel,
  getCarouselMoveup,
  getCarouselMovedown,
  getCarouselMoveFirst,
} from '@/api/help/advertisement/advertisementBody'

const wxStatus = process.env.VUE_APP_SITE

export default {
  name: "advertisementBody",
  inject: ["recommend"],
  props: {
    menuDetail: {}
  },
  watch: {},
  data() {
    return {
      wxStatus,
      viewDrawer: false,
      dialogShow: true,
      loading: false,
      option: {
        height: "auto",
        tip: false,
        searchShow: false,
        searchMenuSpan: 4,
        border: true,
        index: true,
        indexLabel: "序号",
        selection: false,
        viewBtn: false,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        columnBtn: false,
        menuWidth: 300,
        labelWidth: 151,
        dialogClickModal: false,
        dialogType: "drawer",
        dialogFullscreen: true,
        column: [
          {
            label: "图片名称",
            prop: "name",
            display: false,
          },
          {
            width: 80,
            label: "图片",
            prop: "image",
            display: false,
            slot: true
          },
          {
            width: 160,
            label: "链接",
            prop: "link",
            display: false,
            slot: true
          },
          {
            width: 160,
            label: "排序",
            prop: "sort",
            display: false,
            slot: true
          },
          {
            label: "状态",
            prop: "isShow",
            display: false,
            slot: true
          },
        ]
      },
      data: [],
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 100,
      },
      formOption: {
        labelWidth: 120,
        column: [
          {
            label: "广告位名称",
            prop: "name",
            span: 24,
            row: true,
            maxlength: 50,
            showWordLimit: true,
            rules: [
              {
                required: true,
                message: '请输入文章名称'
              }
            ]
          },

          {
            label: "广告图",
            prop: "image",
            type: "upload",
            action: putFile(),
            span: 12,
            showFileList: false,
            listType: "picture-img",
            multiple: false,
            canvasOption: {},
            headers: [],
            data: [],
            propsHttp: {
              // res: "data",
              url: "msg",
            },
            rules: [
              {
                required: true,
                message: '请上传首页图'
              }
            ]
          },
          {
            label: "链接地址",
            prop: "link",
            span: 24,
            row: true,
            showWordLimit: true
          },
          {
            label: "状态",
            prop: "isShow",
            span: 24,
            type: "radio",
            dicData: [{
              label: '显示',
              value: 1
            }, {
              label: '不显示',
              value: 2
            }],
            hide: true,
            mock: {
              type: 'dic',
            },
          },
        ]
      },
      query: {},
      formDrawer: {},
      drawerTitle: ''
    }
  },
  mounted() {
    this.bannerInit()
  },
  methods: {
    isURL,
    openUrl(row) {
      var url = row.link
      // 验证url是否存在http前缀
      var status = this.isURL(url)
      if (status) {
        window.open(url, "_blank")
      } else {
        window.open(`http://${url}`, "_blank")
      }
    },
    uploadBefore(file, done, loading, column) {
      this.formDrawer.image = ''
      done()
    },
    statusSelect(row) {
      row.status = !row.status
    },
    add() {
      this.drawerTitle = "新增图片"
      this.formDrawer = {
        isShow: 2,
        name: '',
        link: '',
        image: ''
      }
      this.viewDrawer = true
      this.$nextTick(() => {
        this.$refs.form.clearValidate();
      })
    },
    modify(row) {
      this.drawerTitle = "广告位编辑-订单管理"
      this.formDrawer = JSON.parse(JSON.stringify(row))
      this.formDrawer.isShow = Number(row.isShow)
      this.viewDrawer = true
    },
    del(row) {
      this.$confirm('是否删除此数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        getCarouselDel(JSON.stringify(row)).then(() => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.refreshChange()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 新增
    handleSubmit(form, done) {
      if (this.drawerTitle === '新增图片') {
        if (this.recommend.titleList[0].select) {
          this.pcAdd()
          this.$nextTick(() => {
            done()
          })
        } else if (this.recommend.titleList[1].select) {
          this.bannerAdd()
          this.$nextTick(() => {
            done()
          })
        }
      } else {
        // 修改
        console.log(this.formDrawer, this.recommend)
        getCarouselEdit(JSON.stringify(this.formDrawer)).then(() => {
          this.$message({
            type: 'success',
            message: '修改成功!'
          });
          done()
          this.viewDrawer = false
          this.refreshChange()
        })
      }
    },
    pcAdd() {
      var type = 5
      var menuId = this.recommend.menuDetail.menuId
      var params = {
        type,
        menuId,
        name: this.formDrawer.name,
        image: this.formDrawer.image,
        isShow: this.formDrawer.isShow,
        link: this.formDrawer.link,
      }
      return getCarouselAdd(params).then(res => {
        this.$message({
          type: 'success',
          message: '新增成功!'
        });
        this.viewDrawer = false
        this.refreshChange()
      })
    },
    bannerAdd() {
      var type = this.envType()
      var params = {
        type,
        name: this.formDrawer.name,
        image: this.formDrawer.image,
        isShow: this.formDrawer.isShow,
        link: this.formDrawer.link,
      }
      getCarouselAdd(params).then(res => {
        this.$message({
          type: 'success',
          message: '新增成功!'
        });
        this.viewDrawer = false
        this.refreshChange()
      })
    },
    /* 表格方法 */
    refreshChange() {
      if (this.recommend.titleList[0].select) {
        this.onLoad()
      } else if (this.recommend.titleList[1].select) {
        this.bannerInit()
      }
    },
    onLoad(page, params = {}) {
      this.data = []
      this.loading = true;
      var menuId = this.recommend.menuDetail.menuId
      getCarouselList(
        1,
        menuId,
      ).then((res) => {
        this.data = res.data.data;
        this.loading = false;
      });
    },
    bannerInit() {
      this.data = []
      this.loading = true;
      // var type = this.envType()
      var type = 1;
      getCarouselList(
        type,
      ).then((res) => {
        this.data = res.data.data;
        this.loading = false;
      });
    },

    envType() {
      var jlOrHs = (this.wxStatus === 'default' || this.wxStatus === 'fangzhen') ? 1 : 2;
      var type = 1;
      if (jlOrHs === 1) {
        type = this.recommend.menuDetail.name === '小程序、H5首页' ? 1 : 2;
      } else if (jlOrHs === 2) {
        type = this.recommend.menuDetail.name === '小程序、H5首页' ? 3 : 4;
      }
      return type
    },
    // 排序
    move(type, row) {
      if (type === 'up') {
        this.moveUp(JSON.stringify(row))
      } else if (type === 'down') {
        this.moveDown(JSON.stringify(row))
      } else if (type === 'first') {
        this.moveFirst(JSON.stringify(row))
      }
    },
    moveUp(row) {
      getCarouselMoveup(row).then(() => {
        this.$message({
          type: 'success',
          message: '上移成功!'
        });
        this.refreshChange()
      })
    },
    moveDown(row) {
      getCarouselMovedown(row).then(() => {
        this.$message({
          type: 'success',
          message: '下移成功!'
        });
        this.refreshChange()
      })
    },
    moveFirst(row) {
      getCarouselMoveFirst(row).then(() => {
        this.$message({
          type: 'success',
          message: '置顶成功!'
        });
        this.refreshChange()
      })
    }
  },
  computed: {}
}
</script>

<style scoped>
.title {
  height: 24px;
  font-size: 16px;
  font-weight: 500;
  color: rgba(0, 0, 0, 0.85);
  line-height: 24px;
  padding-bottom: 15px;
  margin-bottom: 10px;
  border-bottom: 1px solid #E9E9E9;
}
</style>
