<template>
  <div>
    <basic-container>
      <avue-crud
          :option="option"
          :search.sync="search"
          v-model="form"
          :table-loading="loading"
          :data="dataList"
          ref="crud"
          :key="key"
          @on-load="onLoad"
          @selection-change="selectionChange"
          :before-open="beforeOpen"
          @row-update="rowUpdate"
          @search-change="searchChange"
          @refresh-change="refreshChange"
          @resetColumn="resetColumnTwo('crud','option','optionList',249)"
          @saveColumn="saveColumnTwo('crud','option','optionList',249)"
          :page.sync="page">
        <template slot-scope="{type,size,row,$index}" slot="menu">
          <el-button icon="el-icon-edit" :size="size" :type="type" @click="$refs.crud.rowEdit(row,index)">编辑
          </el-button>
<!--          <el-button icon="el-icon-view" :size="size" :type="type" @click="check(row)">-->
<!--            {{ row.upperFrame == 0 ? '上架' : '下架' }}-->
<!--          </el-button>-->
          <el-tooltip :content="`${row.upperFrame == 0?'上架':'下架'}`" placement="top">
            <el-switch
                style="margin-left: 10px"
                v-model="row.upperFrame"
                @change="check(row)"
                active-value="1"
                inactive-value="0">
            </el-switch>
          </el-tooltip>
        </template>
        <template slot-scope="{type,size,row,$index}" slot="menuLeft">
          <el-button class="el-icon-document-copy" :disabled="selectionList.length === 0" type="primary" size="small"
                     @click="change(row,'up')">批量上架
          </el-button>
          <el-button class="el-icon-document-copy" :disabled="selectionList.length === 0" type="danger" size="small"
                     @click="change(row,'down')">批量下架
          </el-button>
          <el-button class="el-icon-document-copy" :disabled="selectionList.length === 0" type="warning" size="small"
                     @click="dialogVisible = true">
            批量标签
          </el-button>
        </template>
      </avue-crud>
    </basic-container>
    <el-dialog
        title="批量标签"
        :visible.sync="dialogVisible"
        v-if="dialogVisible"
        append-to-body
        :close-on-click-modal="false"
        :before-close="(done)=>{
          this.dialogVisible = false
          done()
        }"
        width="40%">
      <span>
        <avue-form :option="optionTwo" v-model="formTwo"></avue-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="change(formTwo,'label')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {getList, submit} from "@/api/productLaunch/index.js";

export default {
  name: "index",
  data() {
    return {
      loading: false,
      dialogVisible: false,
      search: {},
      form: {},
      formTwo: {},
      dataList: [],
      selectionList: [],
      optionTwo: {
        menuBtn:false,
        column: [
          {
            label: '标签',
            prop: 'label',
            width: 170,
            multiple: true,
            tags: true,
            filterable: true,
            type: 'select',
            span: 24,
            dicUrl: "/api/blade-system/dict-biz/dictionary?code=lable",
            props: {
              label: "dictValue",
              value: "dictKey"
            }
          }
        ]
      },
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0,
        pageSizes: [10, 20, 30, 40, 50, 100, 200, 300, 400, 500]
      },
      key: 0,
      option: {},
      optionList: {
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        addBtn: false,
        index: true,
        span: 8,
        border: true,
        selection: true,
        height: "auto",
        searchMenuPosition: "right",
        align: "center",
        menuWidth: 140,
        searchSpan: 8,
        searchIcon: true,
        searchIndex: 2,
        highlightCurrentRow: true,
        dialogWidth: "70%",
        column: [{
          label: '名称',
          prop: 'goods',
          overHidden: true,
          disabled: true,
          search: true,
        }, {
          label: '仓库',
          prop: 'storage',
          overHidden: true,
          disabled: true,
        }, {
          label: '库存',
          prop: 'balance',
          overHidden: true,
          disabled: true,
        }, {
          label: '库存单价',
          prop: 'stockPrice',
          disabled: true,
          overHidden: true,
        }, {
          label: '商城价格',
          prop: 'salesPrice',
          type: 'number',
          controls: false,
        }, {
          label: '标签',
          prop: 'label',
          searchProp: 'labels',
          multiple: true,
          tags: true,
          filterable: true,
          type: 'select',
          span: 16,
          dicUrl: "/api/blade-system/dict-biz/dictionary?code=lable",
          props: {
            label: "dictValue",
            value: "dictKey"
          }
        }, {
          label: '标签',
          prop: 'label',
          filterable: true,
          display:false,
          search: true,
          hide:true,
          showColumn:false,
          type: 'select',
          span: 16,
          dicUrl: "/api/blade-system/dict-biz/dictionary?code=label",
          props: {
            label: "dictValue",
            value: "dictKey"
          }
        }, {
          label: '产品状态',
          prop: 'upperFrame',
          filterable: true,
          display:false,
          search: true,
          hide:true,
          showColumn:false,
          type: 'select',
          span: 17,
          dicData:[{
            label: "上架",
            value: 1
          },{
            label: "下架",
            value: 0
          }]
        }]
      }
    }
  },
  activated() {
    this.onLoad(this.page, this.search)
  },
  async created() {
    this.option = await this.getColumnData(this.getColumnName(249), this.optionList);
    this.key++
    let i = 0;
    this.option.column.forEach(item => {
      if (item.search) i++
    })
    if (i % 3 !== 0) {
      const num = 3 - Number(i % 3)
      this.option.searchMenuSpan = num * 8;
      this.option.searchMenuPosition = "right";
    }
  },
  methods: {
    //刷新
    refreshChange() {
      this.onLoad(this.page, this.search)
    },
    searchChange(params, done) {
      done();
      this.onLoad(this.page, params)
    },
    selectionChange(list) {
      this.selectionList = list
    },
    //打开表单前
    beforeOpen(done, type) {
      if (this.form.label.includes('特价')) {
        this.$set(this.findObject(this.option.column, "salesPrice"), "disabled", false)
      } else {
        this.$set(this.findObject(this.option.column, "salesPrice"), "disabled", true)
      }
      done();
    },
    //编辑确定
    rowUpdate(form, index, done, loading) {
      submit({
        ...form,
        label: form.label.join(","),
        ids: form.goodsId,
        specialOffer: form.salesPrice,
      }).then(res => {
        this.onLoad(this.page, this.search)
        done()
      }).catch(() => {
        loading()
      })
    },
    check(row) {
      if (row.upperFrame == 0){
        if (!Number(row.salesPrice)) return this.$message.error("上架失败,商城价格不能为0")
      }
      submit({
        ...row,
        label: row.label.join(","),
        ids: row.goodsId,
        upperFrame: row.upperFrame,
        specialOffer: row.salesPrice,
      }).then(res => {
        this.onLoad(this.page, this.search)
      })
    },
    change(row, type) {
      let data = []
      for (let item of this.selectionList) {
        data.push(item.goodsId)
      }
      if (type === "up") {
        for (let item of this.selectionList) {
          if (!Number(item.salesPrice)) return this.$message.error("上架失败,商城价格不能为0")
        }
        this.$confirm('是否确认全部上架?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          submit({
            upperFrame: 1,
            ids: data.join(",")
          }).then(res => {
            this.onLoad(this.page, this.search)
          })
        }).catch(() => {
        });
      } else if (type === "down") {
        this.$confirm('是否确认全部下架?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          submit({
            upperFrame: 0,
            ids: data.join(",")
          }).then(res => {
            this.onLoad(this.page, this.search)
          })
        }).catch(() => {
        });
      }else if (type === "label"){
        this.$confirm('是否确认全部修改?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          submit({
            label: row.label.join(","),
            ids: data.join(",")
          }).then(res => {
            this.onLoad(this.page, this.search)
            this.dialogVisible = false
          })
        }).catch(() => {
        });
      }
    },
    onLoad(page, params = {}) {
      params = {
        ...params,
        current: page.currentPage,
        size: page.pageSize,
        ...Object.assign(params, this.search)
      }
      this.loading = true
      getList(params).then(res => {
        this.dataList = res.data.data.records
        this.page.total = res.data.data.total
        this.$nextTick(() => {
          this.$refs.crud.doLayout();
        });
        this.loading = false
      }).finally(() => {
        this.loading = false
      })
    },
//自定义列保存
    async saveColumnTwo(ref, option, optionBack, code) {
      /**
       * 已定义全局方法，直接使用，saveColumnData保存列数据方法,参数传值(表格名称，当前表格的option数据)
       * 已定义全局方法，直接使用，getColumnName方法用来获取枚举值，参数根据自己定义的code值获取中文名
       * 一定要执行异步操作，要等接口成功返回，才能执行下一行代码
       */
      const inSave = await this.saveColumnData(this.getColumnName(code), this[option]);
      if (inSave) {
        this.$message.success("保存成功");
        //关闭窗口
        this.$nextTick(() => {
          this.$refs.crud.doLayout();
        });
        this.$refs[ref].$refs.dialogColumn.columnBox = false;
      }
    },
//自定义列重置
    async resetColumnTwo(ref, option, optionBack, code) {
      this[option] = this[optionBack];
      const inSave = await this.delColumnData(this.getColumnName(code), this[optionBack]);
      if (inSave) {
        this.$message.success("重置成功");
        this.$refs[ref].$refs.dialogColumn.columnBox = false;
        this.$nextTick(() => {
          this.$refs.crud.doLayout();
        });
      }
    }
  }
}
</script>

<style scoped>

</style>
