<template>
  <div class="app-container">
    <div class="setting_title">轮播图管理</div>
    <el-divider></el-divider>

    <div class="mymain-container">
      <div class="btn-group clearfix">
        <div class="fl">
          <el-button size="small" type="primary" icon="el-icon-plus" @click="addOrEdit('add')">新增轮播图</el-button>
          <el-button size="small" type="danger" icon="el-icon-minus" @click="batchDelete()">批量删除</el-button>
        </div>
        <div class="fr">
          <el-select v-model="screenForm.state" placeholder="全部" size="small" style="width: 150px; margin-right: 10px;" @change="getListByScreen">
            <el-option label="全部状态" value=""></el-option>
            <el-option v-for="(item, index) in select_state" :key="index" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </div>
      </div>

      <div class="table">
        <el-table ref="multipleTable" v-loading="listLoading" :data="dataList" element-loading-text="Loading" border fit highlight-current-row stripe>
          <el-table-column type="selection" width="55" align="center"></el-table-column>
          <el-table-column align="center" label="操作" min-width="140">
            <template slot-scope="scope">
              <el-button type="text" style="margin-right: 10px;" @click="addOrEdit('edit', scope.row.id)">编辑</el-button>
              <el-popconfirm v-if="scope.row.state" title="确定隐藏吗？" @onConfirm="changeStatus(scope.row.id, 0)" >
                <el-button slot="reference" type="text">隐藏</el-button>
              </el-popconfirm>
              <el-popconfirm v-else title="确定显示吗？" @onConfirm="changeStatus(scope.row.id, 1)" >
                <el-button slot="reference" type="text">显示</el-button>
              </el-popconfirm>
              <el-popconfirm style="margin-left: 10px;" title="确定删除吗？" @onConfirm="handleDelete(scope.row.id)">
                <el-button slot="reference" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
          <el-table-column align="center" label="轮播图名称" prop="carouselName" min-width="140"></el-table-column>
          <el-table-column align="center" label="排序" prop="sortNum"></el-table-column>
          <el-table-column align="center" label="创建人" prop="adminNickName" min-width="160"></el-table-column>
          <el-table-column align="center" label="创建时间" prop="createTime" min-width="160"></el-table-column>
          <el-table-column align="center" label="状态" class-name="status-col">
            <template slot-scope="scope">
              <el-tag :type="scope.row.state ? 'success':'danger'">{{ scope.row.state ? '显示':'隐藏' }}</el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="pagination clearfix">
        <div class="fr">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="10"
            layout="total, sizes, prev, pager, next, jumper"
            :total="listTotal">
          </el-pagination>
        </div>
      </div>
    </div>

    <!-- 新增编辑 -->
    <el-dialog :title="addFormType === 'add' ? '新增轮播图':'编辑轮播图'" :visible.sync="addFormVisible" :show-close="false" width="50%" :close-on-click-modal="false">
      <el-form ref="addForm" :model="addForm" :rules="addFormRules" label-position="left" label-width="100px">
        <el-form-item label="轮播图名称" prop="bannerName">
          <el-input v-model="addForm.bannerName" autocomplete="off" placeholder="请输入轮播图名称"></el-input>
        </el-form-item>
        <el-form-item label="轮播图" prop="imgUrl">
          <el-upload
            class="avatar-uploader"
            :action="baseURL + 'common/upload'"
            :headers="myHeaders"
            :show-file-list="false"
            :on-success="uploadSuccess"
            :before-upload="beforeUpload">
            <img v-if="addForm.imgUrl" :src="addForm.imgUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <div class="tips">
            <span>支持上传jpg/png文件，尺寸比例为：710*350</span>
          </div>
        </el-form-item>
        <el-form-item label="排序" prop="sortNum">
          <el-input v-model="addForm.sortNum" autocomplete="off" placeholder="请输入整数(降序显示轮播顺序)"></el-input>
        </el-form-item>

        <el-form-item label="链接类型" prop="type">
          <el-radio-group v-model="addForm.type">
            <el-radio :label="1">商品链接</el-radio>
            <el-radio :label="2">凡科活动链接</el-radio>
            <el-radio :label="3">专区活动链接</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="链接商品" prop="goodsId" v-if="addForm.type === 1">
          <el-button @click="showGoods" size="small">查找商品</el-button>
          <el-button @click="clearGoodsId" size="small">清除</el-button>
        </el-form-item>
        <el-form-item label="链接商品名称" prop="goodsName" v-if="addForm.type === 1">
          <el-input disabled v-model="selGoodsName"></el-input>
        </el-form-item>
        <el-form-item label="活动APPID" prop="appid" v-if="addForm.type === 2">
          <el-input v-model="addForm.appid" autocomplete="off" placeholder="请输入活动APPID"></el-input>
        </el-form-item>
        <el-form-item label="活动路径" prop="link" v-if="addForm.type === 2">
          <el-input v-model="addForm.link" autocomplete="off" placeholder="请输入活动路径"></el-input>
        </el-form-item>
        <el-form-item label="选择活动" prop="goodsId" v-if="addForm.type === 3">
          <el-select v-model="addForm.goodsId" placeholder="请选择活动">
            <el-option
              v-for="item in activityList"
              :key="item.type"
              :label="item.name"
              :value="item.type">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>


      <el-dialog
        width="50%"
        title="商品列表"
        :visible.sync="innerVisible"
        append-to-body>
        <el-input v-model="search" placeholder="输入名称搜索">
          <el-button slot="append" icon="el-icon-search" @click="searchGoods()"></el-button>
        </el-input>
        <div class="table" style="margin-top: 10px">
          <el-table
            :data="goodsList"
            height="400px"
            style="width: 100%">
            <el-table-column align="center">
              <template slot="header"></template>
              <template slot-scope="scope">
                <el-button type="primary" size="small" @click="selGoods(scope.row)" :disabled="scope.row.promotionGroup" >选择</el-button>
              </template>
            </el-table-column>
            <el-table-column label="商品名称" prop="goodsName"></el-table-column>
            <el-table-column label="商品图片" prop="imgUrl" align="center">
              <template slot-scope="scope">
                <div class="demo-image__preview">
                  <el-image style="width: 40px; height: 40px" :src="scope.row.imgUrl" :preview-src-list="[scope.row.imgUrl]">
                    <div slot="error" class="image-slot">
                      <i class="el-icon-picture-outline"></i>
                    </div>
                  </el-image>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pagination clearfix">
          <div class="fr">
            <el-pagination
              @size-change="innerHandleSizeChange"
              @current-change="innerHandleCurrentChange"
              :current-page="innerCurrentPage"
              :page-sizes="[10, 20, 30, 50]"
              :page-size="10"
              layout="total, sizes, prev, pager, next, jumper"
              :total="innerListTotal">
            </el-pagination>
          </div>
        </div>
      </el-dialog>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelAddForm">取 消</el-button>
        <el-button type="primary" @click="submitAddForm">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getBannerList, changeBannerStatus, addBanner, editBanner, getBannerDetail, deleteBanner, getGoodsList, batchDeleteBanner } from '@/api/setting'
import { getToken } from '@/utils/auth'

export default {
  data() {
    let checkInt = (rule, value, callback) => {
      if ((Number(value)) && (value) % 1 === 0) {
        callback()
      } else {
        return callback(new Error('请输入整数!'))
      }
    }
    return {
      baseURL: process.env.VUE_APP_BASE_API,
      myHeaders: {'x-token': getToken()},
      dataList: null, // 列表数据
      listLoading: true, // 列表加载loading
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页数量
      listTotal: 0, // 列表总数
      innerCurrentPage: 1, // 内联当前页码
      innerPageSize: 10, // 内联每页数量
      innerListTotal: 0, // 内联列表总数
      editId:  null,
      addFormType: 'add',
      addFormVisible: false,
      addForm: {
        imgUrl: '', // 轮播图
        bannerName: '', // 轮播图名称
        state: true,
        goodsId: '',
        sortNum: '',
        type: 1,
        appid: '',
        link: '',
      },
      addFormRules: {
        imgUrl: [
          { required: true, message: '请上传轮播图', trigger: 'change' }
        ],
        bannerName: [
          { required: true, message: '请输入轮播图名称', trigger: 'blur' }
        ],
        sortNum: [
          { required: false, trigger: 'blur', validator: checkInt }
        ],
      },
      innerVisible: false,
      goodsList: [],
      search: '',
      selGoodsName: '',
      select_state: [
        { value: 1, label: '显示' },
        { value: 0, label: '隐藏' },
      ],
      screenForm : {
        state: ''
      },

      activityList: [
        {type: 2, name: '首页弹窗'},
        {type: 3, name: '胶囊图'},
        {type: 4, name: '活动专区2-左侧专区'},
        {type: 5, name: '活动专区2-右侧专区'},
        {type: 6, name: '专场专区-01'},
        {type: 7, name: '专场专区-02'},
        {type: 8, name: '专场专区-03'},
        {type: 9, name: '专场专区-04'},
        {type: 10, name: '专题精选-01'},
        {type: 11, name: '专题精选-02'},
        {type: 12, name: '专题精选-03'},
        {type: 13, name: '底部广告图'},
      ],
    }
  },
  computed: {
    ...mapGetters([
      'userid',
      'name'
    ])
  },
  created() {
    this.getList();
  },
  methods: {
    getList() {
      this.listLoading = true;

      let params = {
        state: this.screenForm.state,
        pageNum: this.currentPage,
        pageSize: this.pageSize
      };

      getBannerList(params).then(res => {
        this.dataList = res.data.records;
        this.listTotal = res.data.total;
        this.listLoading = false;
      })
    },
    // 筛选后重新获取列表
    getListByScreen() {
      this.currentPage = 1;
      this.getList();
    },
    // 更改每页数量
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.getList();
    },

    // 更改当前页
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getList();
    },

    // 更改内嵌每页数量
    innerHandleSizeChange(val) {
      this.innerPageSize = val;
      this.innerCurrentPage = 1;
      this.showGoodsList();
    },

    // 更改内嵌当前页
    innerHandleCurrentChange(val) {
      this.innerCurrentPage = val;
      this.showGoodsList();
    },

    // 操作 - 更改状态(type: 禁用0，启用1)
    changeStatus(id, type) {
      type = !!type
      changeBannerStatus({carouselMapId: id, state: type}).then(res => {
        this.getList();
        this.$successMsg();
      })
    },

    // 操作 - 删除
    handleDelete(id) {
      deleteBanner({carouselMapId: id}).then(res => {
        this.getList();
        this.$successMsg();
      })
    },

    // 新增编辑
    addOrEdit(type, id) {
      this.addFormType = type;
      this.addFormVisible = true;
      if(type == 'edit') {
        this.editId = id;
        getBannerDetail({id: id}).then(res => {
          this.addForm = {
            bannerName: res.data.carouselName,
            imgUrl: res.data.imgSrc,
            state: res.data.state,
            goodsId: res.data.goodsId,
            sortNum: res.data.sortNum,
            type: res.data.type,
            appid: res.data.appId,
            link: res.data.linkUrl,
          }
          if(this.addForm.type === 3) {
            this.addForm.goodsId = Number(this.addForm.goodsId);
          }
          if (this.addForm.goodsId && this.addForm.type === 1) {
            let params = {
              goodsId: this.addForm.goodsId,
              pageNum: 1,
              pageSize: 1
            };
            getGoodsList(params).then(res => {
              this.selGoodsName = res.data.records[0].goodsName;
            })
          }
        })
      }
    },

    // 取消 新增编辑
    cancelAddForm(){
      this.addFormVisible = false;
      this.$refs.addForm.resetFields();
      this.selGoodsName = ''
    },

    // 提交 新增编辑
    submitAddForm() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          let params = {
            carouselName: this.addForm.bannerName,
            imgSrc: this.addForm.imgUrl,
            state: this.addForm.state,
            goodsId: this.addForm.goodsId,
            sortNum: this.addForm.sortNum,
            type: this.addForm.type,
            appId: this.addForm.appid,
            linkUrl: this.addForm.link,
          }
          if(this.addFormType == 'edit') {
            params.id = this.editId;
            editBanner(params).then(res => {
              this.cancelAddForm();
              this.getList();
              this.$successMsg('编辑成功');
            })
          } else {
            params.adminNickName = this.name;
            params.adminUserId = this.userid;
            addBanner(params).then(res => {
              this.cancelAddForm();
              this.getList();
              this.$successMsg('新增成功');
            })
          }
        }
      })
    },

    uploadSuccess(res, file) {
      this.addForm.imgUrl = res.data.url;
    },

    beforeUpload(file) {
      const fileSuffix = file.name.substring(file.name.lastIndexOf(".") + 1);
      const whiteList = ['jpg', 'jpeg', 'png'];
      if (whiteList.indexOf(fileSuffix) === -1) {
        this.$errorMsg('只支持上传jpg/png文件!');
        return false;
      }
    },
    batchDelete() {
      if(this.$refs.multipleTable.selection && this.$refs.multipleTable.selection.length > 0) {
        this.$confirm('此操作将删除选中轮播图, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let ids = []
          this.$refs.multipleTable.selection.forEach(value => {
            ids.push(value.id)
          })
          batchDeleteBanner(ids).then(() => {
            this.$refs.multipleTable.clearSelection()
            this.getList()
            this.$successMsg('删除成功');
          })
        }).catch(() => {});
      } else {
        this.$errorMsg('请选择要删除的轮播图')
      }
    },
    showGoods() {
      this.search = '';
      this.innerVisible = true
      this.showGoodsList()
    },
    clearGoodsId() {
      this.addForm.goodsId = ''
      this.selGoodsName = ''
    },
    showGoodsList() {
      let params = {
        goodsName: this.search,
        pageNum: this.innerCurrentPage,
        pageSize: this.innerPageSize
      };
      getGoodsList(params).then(res => {
        this.goodsList = res.data.records;
        this.innerListTotal = res.data.total;
      })
    },
    searchGoods() {
      this.innerCurrentPage = 1;
      this.showGoodsList()
    },
    selGoods(row) {
      this.innerVisible = false
      this.search = ''
      this.addForm.goodsId = row.goodsId
      this.selGoodsName = row.goodsName
    }
  }
}
</script>

<style scoped lang="scss">
  .tips {
    margin-top: 10px;
    span {
      display: inline-block;
      width: 300px;
      text-align: center;
      line-height: 32px;
      background: #ffefef;
      font-size: 14px;
      color: #f66460;
    }
  }
</style>
<style>
  .demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    width: 80px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 100%;
  }
</style>
