<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page.sync="page"
               :permission="permissionList"
               :upload-error="uploadError"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">

      <template slot="isPerfect" slot-scope="scope" >
        <el-tag v-if="scope.row.isPerfect === 1" type="success">已完善</el-tag>
        <el-tag v-if="scope.row.isPerfect === 0">待完善</el-tag>
      </template>

      <template slot="menuLeft">

      </template>
      <template slot-scope="scope" slot="menu">

      </template>

      <!--  添加商品插槽    -->
      <template slot="goodsForm">
        <avue-crud :option="goodsTableOption"
                   :data="tableData"
                   ref="crudGoods">
          <template #menu="{row,index,size}">
            <el-button type="danger"
                       size="mini"
                       @click="rowDelGoods(row,index)">删除</el-button>
          </template>
          <template slot="grouponPrice" slot-scope="scope" >
            <avue-input-number precision="2" v-model="scope.row.grouponPrice"></avue-input-number>
          </template>
        </avue-crud>
      </template>

    </avue-crud>
  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove, perfect} from "@/api/groupon/groupon";
  import {mapGetters} from "vuex";
  import {goodsTableOption} from "../../option/groupon/grouponPerfact"

  export default {
    data() {
      return {
        goodsTableOption: goodsTableOption,
        tableData: [],
        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          height:'auto',
          calcHeight: 30,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: false,
          addBtn: false,
          viewBtn: true,
          editBtn: true,
          editBtnText: '完善信息',
          delBtn: false,
          selection: true,
          dialogClickModal: false,
          column: [
            {
              label: "主标题",
              prop: "mainTitle",
              labelWidth: 120,
              editDisplay: false,
              search: true,
              rules: [{
                required: true,
                message: "请输入团购名称",
                trigger: "blur"
              }]
            },
            {
              label: "副标题",
              prop: "subTitle",
              labelWidth: 120,
              editDisplay: false,
              hide: true,
            },
            {
              label: "团购开始时间",
              labelWidth: 120,
              editDisplay: false,
              prop: "grouponStartTime",
              rules: [{
                required: true,
                message: "请输入团购开始时间",
                trigger: "blur"
              }]
            },
            {
              label: "团购结束时间",
              prop: "grouponEndTime",
              labelWidth: 120,
              editDisplay: false,
              rules: [{
                required: true,
                message: "请输入团购结束时间",
                trigger: "blur"
              }]
            },
            {
              label: "信息是否完善",
              prop: "isPerfect",
              editDisplay: false,
              viewDisplay: false,
            },
            {
              labelWidth: 120,
              label: '团购分享图',
              prop: 'shareImage',
              type: 'upload',
              listType: 'picture-img',
              loadText: '上传中，请稍等',
              accept: 'image/png, image/jpeg',
              fileSize: 500,
              tip: '建议尺寸：800×640；只能上传jpg/png文件，且不超过500kb',
              span: 24,
              hide: true,
              propsHttp: {
                res: 'data',
                url: 'link',
              },
              action: "/api/blade-resource/oss/endpoint/put-file-attach"
            },
            {
              label: '团购轮播图',
              labelWidth: 120,
              prop: 'slideshow',
              type: 'upload',
              dataType: 'array',
              listType: 'picture-card',
              loadText: '上传中，请稍等',
              accept: 'image/png, image/jpeg',
              fileSize: 500,
              tip: '建议尺寸：750×420；只能上传jpg/png文件，且不超过500kb',
              span: 24,
              hide: true,
              propsHttp: {
                res: 'data',
                url: 'link',
              },
              action: "/api/blade-resource/oss/endpoint/put-file-attach"
            },
            {
              label: '团购详情图',
              labelWidth: 120,
              prop: 'detailImage',
              type: 'upload',
              dataType: 'array',
              listType: 'picture-card',
              loadText: '上传中，请稍等',
              accept: 'image/png, image/jpeg',
              fileSize: 1024,
              tip: '只能上传jpg/png文件，且不超过1M',
              limit: 25,
              span: 24,
              hide: true,
              propsHttp: {
                res: 'data',
                url: 'link',
              },
              action: "/api/blade-resource/oss/endpoint/put-file-attach"
            },
            {
              label: "团购商品",
              prop: "goods",
              labelWidth: 120,
              span: 24,
              fromslot: true,
              // editDisplay: false,
              // viewDisplay: false,
              hide: true
            },
          ]
        },
        data: []
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.groupon_add, false),
          viewBtn: this.vaildData(this.permission.groupon_view, false),
          delBtn: this.vaildData(this.permission.groupon_delete, false),
          editBtn: this.vaildData(this.permission.groupon_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
      rowSave(row, done, loading) {
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        this.tableData.forEach(e => {
          e.sort = e.$index;
        })
        console.log("2--", this.tableData)
        row.goodsList = this.tableData;
        perfect(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          this.tableData = [];
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
            res.data.data.goodsList.forEach(e => {
              let goods = {
                id: e.id,
                goodsId: e.id,
                goodsName: e.goodsName,
                goodsCover: e.goodsCover,
                goodsSpec: e.goodsSpec,
                supplierName: e.supplierName,
                grouponPrice: e.grouponPrice
              }
              this.tableData.push(goods)
            })
            console.log("1--", this.tableData)
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      },
      uploadError(error, column) {
        this.$message.error('上传失败：' + error)
        console.log(error, column)
      },
      /**
       * 删除商品
       * @param row
       * @param index
       */
      rowDelGoods(row, index) {
        this.tableData.splice(index, 1);
      },
    }
  };
</script>

<style>
</style>
