<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page.sync="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               :upload-error="uploadError"
               :upload-after="uploadAfter"
               @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="status" slot-scope="scope">
        <el-tag v-if="scope.row.status === 1" type="success">{{ scope.row.$status }}</el-tag>
        <el-tag v-if="scope.row.status === 0" type="danger">{{ scope.row.$status }}</el-tag>
      </template>

      <template slot="auditStatus" slot-scope="scope">
        <el-tag v-if="scope.row.auditStatus === 0">{{ scope.row.$auditStatus }}</el-tag>
        <el-tag v-else-if="scope.row.auditStatus === 1" type="success">{{ scope.row.$auditStatus }}</el-tag>
        <el-tag v-else-if="scope.row.auditStatus === 2" type="danger">{{ scope.row.$auditStatus }}</el-tag>
      </template>

      <template slot="menu" slot-scope="scope">
        <el-button v-if="scope.row.auditStatus == 0"
                   type="text"
                   size="small"
                   @click="openAuditBox(scope.row.id)"
        >审核
        </el-button>
        <el-button v-if="scope.row.status == 0"
                   type="text"
                   size="small"
                   @click="modifyState(scope.row, 1)"
        >启用
        </el-button>
        <el-button v-if="scope.row.status == 1"
                   type="text"
                   size="small"
                   @click="modifyState(scope.row, 0)"
        >禁用
        </el-button>
      </template>

      <!--  添加商品插槽    -->
      <template slot="goodsForm">
        <el-button type="primary" size="mini" @click="addGoodsBox = true">添 加</el-button>
        <el-table
            :data="tableData"
            style="width: 100%">
          <el-table-column label="商品" width="280">
            <template slot-scope="scope">
              <el-row>
                <el-col :span="4">
                  <el-avatar shape="square" :size="45" fit="fit" :src="scope.row.goodsCover"></el-avatar>
                </el-col>
                <el-col :span="20">
                  <span style="line-height: 40px; margin-left: 10px">{{ scope.row.goodsName }}</span>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
          <el-table-column label="规格" width="180">
            <template slot-scope="scope">
              <el-row>
                <el-col :span="24">
                  <span style="line-height: 40px;">{{ scope.row.goodsSpec }}</span>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
          <el-table-column label="供应商">
            <template slot-scope="scope">
              <el-row>
                <el-col :span="24">
                  <span style="line-height: 40px;">{{ scope.row.supplierName }}</span>
                </el-col>
              </el-row>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                  size="mini"
                  type="danger"
                  @click="handleDeleteGood(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>


    </avue-crud>

    <el-dialog title="拼团审核" @close="refreshChange"
               append-to-body
               :visible.sync="auditBox"
               :before-close="handleClose"
               width="600px"
               heigh="40%">
      <el-form :model="auditForm" label-width="80px">
        <el-form-item label="审核意见:">
          <el-select v-model="auditForm.auditStatus" placeholder="请选择">
            <el-option
                v-for="item in auditList"
                :key="item.value"
                :label="item.name"
                :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="驳回描述:" v-if="auditForm.auditStatus == 2">
          <el-input type="textarea" v-model="auditForm.remark" :autosize="{ minRows: 3, maxRows: 5}"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="auditGoods()">确 定</el-button>
      </div>
    </el-dialog>

    <!--  商品列表dialog  -->
    <el-dialog title="添加商品"
               append-to-body
               :visible.sync="addGoodsBox"
               :before-close="handleClose"
               width="90%"
               heigh="70%">
      <avue-crud :option="grouponOption"
                 :table-loading="grouponLoading"
                 :data="grouponData"
                 :page.sync="grouponPage"
                 v-model="grouponForm"
                 ref="grouponCrud"
                 @search-change="grouponSearchChange"
                 @search-reset="grouponSearchReset"
                 @selection-change="grouponSelectionChange"
                 @current-change="grouponCurrentChange"
                 @size-change="grouponSizeChange"
                 @refresh-change="grouponRefreshChange"
                 @on-load="grouponOnLoad">

        <template slot="menuLeft">
          <el-button type="primary"
                     size="small"
                     @click="submit()">提 交
          </el-button>
        </template>
      </avue-crud>
    </el-dialog>
  </basic-container>
</template>

<script>
import {getList, getDetail, add, update, remove, audit, modifyStatus} from "@/api/groupon/groupon";
import {getList as getGoodsList} from "@/api/mall/goodsinfo";
import {grouponOption} from "../../option/groupon/grouponOption"
import {mapGetters} from "vuex";

export default {
  data() {
    return {
      grouponOption: grouponOption,
      tableData: [],
      auditList: [
        {name: '通过', value: 1}, {name: '驳回', value: 2}
      ],
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      auditBox: false,
      addGoodsBox: false,
      auditForm: {
        auditStatus: '',
        id: '',
        remark: ''
      },
      selectionList: [],
      option: {
        height: 'auto',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: false,
        viewBtn: true,
        editBtn: true,
        delBtn: false,
        selection: true,
        dialogClickModal: false,
        addBtnText: '发布团购',
        column: [
          {
            label: "主标题",
            prop: "mainTitle",
            labelWidth: 120,
            search: true,
            rules: [{
              required: true,
              message: "请输入主标题",
              trigger: "blur"
            }]
          },
          {
            label: "副标题",
            prop: "subTitle",
            labelWidth: 120,
            hide: true,
            rules: [{
              required: true,
              message: "请输入副标题",
              trigger: "blur"
            }]
          },
          {
            label: "团购开始时间",
            prop: "grouponStartTime",
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            type: "datetime",
            labelWidth: 120,
            rules: [{
              required: true,
              message: "请输入团购开始时间",
              trigger: "blur"
            }]
          },
          {
            label: "团购结束时间",
            prop: "grouponEndTime",
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            type: "datetime",
            labelWidth: 120,
            rules: [{
              required: true,
              message: "请输入团购结束时间",
              trigger: "blur"
            }]
          },
          {
            label: "取货开始时间",
            prop: "takeStartTime",
            type: "datetime",
            labelWidth: 120,
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            hide: true,
            rules: [{
              required: true,
              message: "请输入取货开始时间",
              trigger: "blur"
            }]
          },
          {
            label: "取货结束时间",
            prop: "takeEndTime",
            labelWidth: 120,
            type: "datetime",
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            hide: true,
            rules: [{
              required: true,
              message: "请输入取货结束时间",
              trigger: "blur"
            }]
          },
          {
            label: "浏览量",
            prop: "views",
            labelWidth: 120,
            addDisplay: false,
            editDisplay: false,
            hide: true,
            width: 80,
            rules: [{
              required: true,
              message: "请输入浏览量",
              trigger: "blur"
            }]
          },
          {
            label: "状态",
            prop: "status",
            labelWidth: 120,
            search: true,
            slot: true,
            rules: [{
              required: true,
              message: "请选择状态",
              trigger: "blur"
            }],
            type: "select",
            dicUrl: "/api/blade-system/dict-biz/getEnumDict?enumName=StatusEnum",
            props: {
              label: "name",
              value: "value"
            },
            dataType: "number",
          },
          {
            label: "审核状态",
            prop: "auditStatus",
            labelWidth: 120,
            addDisplay: false,
            editDisplay: false,
            rules: [{
              required: true,
              message: "请输入审核状态",
              trigger: "blur"
            }],
            search: true,
            slot: true,
            type: "select",
            dicUrl: "/api/blade-system/dict-biz/getEnumDict?enumName=AuditStatusEnum",
            props: {
              label: "name",
              value: "value"
            },
            dataType: "number",
          },
          {
            label: "团长",
            prop: "organizerUserId",
            labelWidth: 120,
            rules: [{
              required: true,
              message: "请选择团长",
              trigger: "blur"
            }],
            hide: true,
            remote: true,
            editDisplay: false,
            viewDisplay: false,
            editDisabled: true,
            type: "select",
            dicUrl: "/api/platform/userApp/list?username={{key}}&state=1&livingHall=1&size100",
            props: {
              label: "username",
              value: "userId"
            },
            dicFormatter: function (res) {
              return res.data.records;
            },
          },
          {
            label: "自提点",
            prop: "selfTakeIds",
            labelWidth: 120,
            span: 24,
            rules: [{
              required: true,
              message: "请选择自提点",
              trigger: "blur"
            }],
            hide: true,
            editDisplay: false,
            viewDisplay: false,
            editDisabled: true,
            type: "select",
            multiple: true,
            remote: true,
            dicUrl: "/api/groupon/selftake/page?name={{key}}",
            props: {
              label: "name",
              value: "id"
            },
            dicFormatter: function (res) {
              return res.data.records;
            },
          },
          {
            label: "团购商品",
            prop: "goods",
            span: 24,
            fromslot: true,
            editDisplay: false,
            hide: true
          },
        ]
      },
      data: [],

      grouponPage: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      grouponData: [],
      grouponLoading: false,
      grouponForm: {},
      grouponQuery: {},
      grouponSelectionList: []
    };
  },
  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) {
      let goodsIds = [];
      this.tableData.forEach(e => {
        goodsIds.push(e.goodsId)
      })
      row.goodsIds = goodsIds;
      add(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        loading();
        window.console.log(error);
      });
    },
    rowUpdate(row, index, done, loading) {
      update(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)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });
      }
      this.tableData = [];
      this.grouponSelectionList = [];
      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();
      });
    },
    openAuditBox(id) {
      this.auditBox = true;
      this.auditForm.id = id;
    },
    auditGoods() {
      audit(this.auditForm).then(() => {
        this.auditBox = false;
        this.onLoad(this.page, this.query);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
      }, error => {
        loading();
        console.log(error);
      });
    },
    handleClose() {
      this.addGoodsBox = false;
      this.auditBox = false;
      this.auditForm = {
        auditStatus: '',
        id: '',
        remark: ''
      };
    },
    modifyState(row, status) {
      let title = status === 0 ? '确定禁用？' : '确定启用？';
      this.$confirm(title, {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        const loading = this.$loading({
          lock: true,
          text: '修改中，请稍等...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        row.status = status;
        modifyStatus(row).then(() => {
          loading.close();
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          loading.close();
          console.log(error);
        });
      })

    },
    uploadError(error, column) {
      this.$message.success('上传失败:' + error)
      // console.log(error, column)
    },
    uploadAfter(res, done, loading, column) {
      // console.log(res,column)
      done()
    },


    grouponSearchReset() {
      this.grouponQuery = {};
      this.grouponOnLoad(this.grouponPage);
    },
    grouponSearchChange(params, done) {
      this.grouponQuery = params;
      this.grouponPage.currentPage = 1;
      this.grouponOnLoad(this.grouponPage, params);
      done();
    },
    grouponSelectionChange(list) {
      this.grouponSelectionList = list;
    },
    grouponSelectionClear() {
      this.grouponSelectionList = [];
      this.$refs.grouponCrud.toggleSelection();
    },
    grouponCurrentChange(currentPage){
      this.grouponPage.currentPage = currentPage;
    },
    grouponSizeChange(pageSize){
      this.grouponPage.pageSize = pageSize;
    },
    grouponRefreshChange() {
      this.grouponOnLoad(this.grouponPage, this.grouponQuery);
    },
    grouponOnLoad(page, params = {}) {
      this.grouponLoading = true;
      if (this.grouponQuery.categoryIdArr) {
        this.grouponQuery.goodsCategoryId = this.grouponQuery.categoryIdArr.join("-");
        this.grouponQuery.categoryIdArr = null;
      }
      this.grouponQuery.auditStatus = 1;
      this.grouponQuery.isSale = 1;

      getGoodsList(page.currentPage, page.pageSize, Object.assign(params, this.grouponQuery)).then(res => {
        const data = res.data.data;
        this.grouponPage.total = data.total;
        this.grouponData = data.records;
        this.grouponLoading = false;
        this.selectionClear();
      });
    },
    submit() {
      if (this.grouponSelectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }

      let map = new Map();
      this.tableData.forEach(row => {
        map.set(row.goodsId, row.goodsId);
      })

      this.grouponSelectionList.forEach(e => {
        let g = map.get(e.id);
        if (!g) {
          let goods = {
            goodsId: e.id,
            goodsName: e.goodsName,
            goodsCover: e.goodsCover,
            goodsSpec: e.goodsSpec,
            supplierName: e.supplierName
          }
          this.tableData.push(goods);
        }
      })

      this.addGoodsBox = false;
    }
  }
};
</script>

<style>
</style>
