<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"
               @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="menuLeft">
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   @click="handleDelete">删 除
        </el-button>
        <el-button type="primary"
                   size="small"
                   icon="el-icon-plus"
                   plain
                   @click="addGoodsOpen">添加秒杀商品
        </el-button>
      </template>
    </avue-crud>
    <el-drawer
        title="添加秒杀商品"
        append-to-body
        :visible.sync="setGoodsDialogVisible"
        size="84%"
        :before-close="handleClose">
      <basic-container>
        <avue-crud :option="goodsOption"
                   :data="goodsData"
                   :page="goodsPage"
                   v-model="goodsForm"
                   :table-loading="goodsLoading"
                   ref="crudGoods"
                   :before-open="beforeOpenGoods"
                   @search-change="searchChangeGoods"
                   @search-reset="searchResetGoods"
                   @selection-change="selectionChangeGoods"
                   @current-change="currentChangeGoods"
                   @size-change="sizeChangeGoods"
                   @on-load="onLoadGoods">
          <template slot="menuLeft">
            <el-button type="primary"
                       size="small"
                       plain
                       @click="submitGoods">提 交
            </el-button>
          </template>
        </avue-crud>
      </basic-container>
    </el-drawer>
  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove} from "@/api/mall/seckillgoods";
  import {getByParentId} from "@/api/mall/categoryinfo";
  import {getList as getGoodsList, getDetail as getGoodsDetail, getRoundList} from "@/api/mall/goodsinfo";
  import {mapGetters} from "vuex";

  export default {
    data() {
      return {
        setGoodsDialogVisible: false,
        roundName: JSON.parse(this.$route.query.startTime) + "~" + JSON.parse(this.$route.query.endTime),
        form: {},
        seckillRoundId: JSON.parse(this.$route.query.roundId),
        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: true,
          viewBtn: false,
          addBtn: false,
          selection: true,
          dialogClickModal: false,
          column: [
            {
              label: "秒杀场次",
              width: 140,
              prop: "seckillRound",
              disabled: true,
              rules: [{
                required: true,
                message: "请输入秒杀场次ID",
                trigger: "blur"
              }]
            },
            {
              label: "商品图片",
              prop: "goodsCover",
              width: 80,
              addDisplay: false,
              viewDisplay: false,
              editDisplay: false,
              type: 'upload',
              listType: 'picture-img'
            },
            {
              label: "商品名称",
              prop: "goodsName",
              disabled: true,
              rules: [{
                required: true,
                message: "请输入商品ID",
                trigger: "blur"
              }]
            },
            {
              label: "抢购商品数量",
              width: 120,
              prop: "goodsQuantity",
              rules: [{
                required: true,
                message: "请输入抢购商品数量",
                trigger: "blur"
              }]
            },
            {
              label: "已抢数量",
              prop: "rushNum",
              width: 80,
              disabled: true,
              rules: [{
                required: true,
                message: "请输入已抢数量",
                trigger: "blur"
              }]
            },
          ]
        },
        data: [],


        goodsOption: {
          height: 'auto',
          tip: false,
          border: true,
          viewBtn: true,
          delBtn:false,
          editBtn: false,
          addBtn: false,
          selection: true,
          index: true,
          // dialogClickModal: false,
          labelWidth: 150,
          searchIcon: true,
          searchIndex: 3,
          column: [
            {
              label: "商品ID",
              prop: "id",
              hide: true,
              overHidden: true,
              addDisplay: false,
              editDisplay: false,
              editDisabled: true,
            },
            {
              label: "商品名称",
              prop: "goodsName",
              search: true,
              width: 280,
              overHidden: true,
              rules: [{
                required: true,
                message: "请输入商品名称",
                trigger: "blur"
              }]
            },
            {
              label: "商品封面",
              prop: "goodsCover",
              addDisplay: false,
              viewDisplay: false,
              editDisplay: false,
              type: 'img',
            },
            {
              label: "品牌",
              prop: "brandDesc",
              addDisplay: false,
              viewDisplay: false,
              editDisplay: false,
            },
            {
              label: "分类",
              prop: "categoryIdArr",
              hide: true,
              search: true,
              lazy: true,
              rules: [{
                required: true,
                message: "请选择分类",
                trigger: "blur"
              }],
              type: "cascader",
              filterable: true,
              checkStrictly: true,
              lazyLoad(node, resolve) {
                let parentId;
                let stop_level = 2;
                let level = node.level;
                let list = [];

                if (node.level === 0) {
                  parentId = 0;
                  getByParentId(0).then((res) => {
                    list = res.data.data;
                    list = (list || []).map(ele => {
                      return Object.assign(ele, {
                        leaf: level >= stop_level
                      })
                    })
                    resolve(list)
                  })
                } else {
                  parentId = node.data.id;
                  getByParentId(node.data.id).then((res) => {
                    list = res.data.data;
                    list = (list || []).map(ele => {
                      return Object.assign(ele, {
                        leaf: level >= stop_level
                      })
                    })
                    resolve(list)
                  })
                }
              },
              props: {
                label: "title",
                value: "key"
              },
            },
            {
              label: "品牌",
              prop: "brandId",
              hide: true,
              search: true,
              rules: [{
                required: true,
                message: "请选择品牌",
                trigger: "blur"
              }],
              type: "select",
              remote: true,
              dicUrl: "/api/mall/brandsinfo/getByName?brandName={{key}}",
              props: {
                label: "brandName",
                value: "id"
              },
              dataType: "string",
            },
            {
              label: "排序",
              prop: "sort",
              type: "number",
              hide: true,
              rules: [{
                required: true,
                message: "请输入排序",
                trigger: "blur"
              }]
            },
            {
              label: "营销价",
              prop: "activityPrice",
              precision: 2,
              type: "number",
              hide: true,
              formatter:(val,value)=>{
                return Number(value).toFixed(2);
              }
            },
            {
              label: "销售价",
              prop: "salePrice",
              precision: 2,
              type: "number",
              formatter:(val,value)=>{
                return Number(value).toFixed(2);
              },
              rules: [{
                required: true,
                message: "请输入销售价",
                trigger: "blur"
              }],
            },
            {
              label: "秒杀价",
              prop: "seckillPrice",
              precision: 2,
              type: "number",
              formatter:(val,value)=>{
                return Number(value).toFixed(2);
              },
              rules: [{
                required: true,
                message: "请输入秒杀价",
                trigger: "blur"
              }],
            },
            {
              label: "秒杀商品总数",
              prop: "seckillNum",
              value: 1000,
              cell: true,
              type: "number",
              width: 130
            },
            {
              label: "成本价",
              prop: "costPrice",
              precision: 2,
              type: "number",
              hide: true,
              formatter:(val,value)=>{
                return Number(value).toFixed(2);
              },
              rules: [{
                required: true,
                message: "请输入成本价",
                trigger: "blur"
              }]
            },
            {
              label: "是否推荐",
              prop: "isRecom",
              hide: true,
              rules: [{
                required: true,
                message: "请选择是否推荐",
                trigger: "blur"
              }],
              type: "select",
              dicUrl: "/api/blade-system/dict/dictionary?code=yes_or_no",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              dataType: "number",
              search: true
            },
            {
              label: "是否上架",
              prop: "isSale",
              search: true,
              hide: true,
              rules: [{
                required: true,
                message: "请输入是否上架",
                trigger: "blur"
              }],
              type: "select",
              dicUrl: "/api/blade-system/dict/dictionary?code=yes_or_no",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              dataType: "number",
            },
            {
              label: "上架时间",
              prop: "saleTime",
              hide: true,
              addDisplay: false,
              viewDisplay: false,
              editDisplay: false,
              editDisabled: true,
            },

            {
              label: "是否包邮",
              prop: "isFreeShipping",
              hide: true,
              search: true,
              rules: [{
                required: true,
                message: "请选择是否包邮",
                trigger: "blur"
              }],
              type: "select",
              dicUrl: "/api/blade-system/dict/dictionary?code=yes_or_no",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              dataType: "number",
            },
            {
              label: "运费",
              prop: "freePrice",
              hide: true,
              precision: 2,
              type: "number",
              rules: [{
                required: true,
                message: "请输入运费",
                trigger: "blur"
              }]
            },
            {
              label: "总销量",
              prop: "totalSales",
              addDisplay: false,
              editDisplay: false,
              hide: true,
            },
            {
              label: "总浏览量",
              prop: "totalViews",
              addDisplay: false,
              editDisplay: false,
              hide: true,
            },
            {
              label: "单位",
              prop: "unit",
              hide: true,
              rules: [{
                required: true,
                message: "请输入单位",
                trigger: "blur"
              }]
            },
            {
              label: "营业类型",
              prop: "businessType",
              search: true,
              editDisabled: true,
              hide: true,
              rules: [{
                required: true,
                message: "请选择营业类型",
                trigger: "blur"
              }],
              type: "select",
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=business_type",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              dataType: "number",
            },
            {
              label: "专区类型",
              prop: "zoneType",
              search: true,
              hide: true,
              rules: [{
                required: true,
                message: "请选择专区类型",
                trigger: "blur"
              }],
              type: "select",
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=zone_type",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              dataType: "number",
            },
            {
              label: "是否热销",
              prop: "isHot",
              hide: true,
              rules: [{
                required: true,
                message: "请选择是否热销",
                trigger: "blur"
              }],
              type: "select",
              dicUrl: "/api/blade-system/dict/dictionary?code=yes_or_no",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              dataType: "number",
            },
            {
              label: "是否新品",
              prop: "isNew",
              hide: true,
              rules: [{
                required: true,
                message: "请选择是否新品",
                trigger: "blur"
              }],
              type: "select",
              dicUrl: "/api/blade-system/dict/dictionary?code=yes_or_no",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              dataType: "number",
            },
            {
              label: "产地",
              prop: "origin",
              hide: true,
            },
            {
              label: "创建时间",
              prop: "createTime",
              hide: true,
              addDisplay: false,
              editDisplay: false,
              editDisabled: false,
            },
            {
              label: '商品封面',
              prop: 'uploadCover',
              type: 'upload',
              listType: 'picture-img',
              loadText: '上传中，请稍等',
              accept: 'image/png, image/jpeg',
              fileSize: 1024,
              tip: '只能上传jpg/png文件，且不超过1M',
              span: 24,
              hide: true,
              propsHttp: {
                res: 'data',
                url: 'link',
              },
              action: "/api/blade-resource/oss/endpoint/put-file-attach"
            },
            {
              label: '商品轮播图',
              prop: 'slideshowList',
              viewDisplay: false,
              type: 'upload',
              dataType: 'array',
              listType: 'picture-card',
              loadText: '上传中，请稍等',
              accept: 'image/png, image/jpeg',
              fileSize: 1024,
              tip: '只能上传jpg/png文件，且不超过1M',
              span: 24,
              hide: true,
              propsHttp: {
                res: 'data',
                url: 'link',
              },
              action: "/api/blade-resource/oss/endpoint/put-file-attach"
            },
            {
              label: '图文详情',
              viewDisplay: false,
              prop: 'detailImgUrlList',
              type: 'upload',
              dataType: 'array',
              listType: 'picture-card',
              loadText: '上传中，请稍等',
              accept: 'image/png, image/jpeg',
              fileSize: 2048,
              tip: '只能上传jpg/png文件，且不超过2M',
              limit: 25,
              span: 24,
              hide: true,
              propsHttp: {
                res: 'data',
                url: 'link',
              },
              action: "/api/blade-resource/oss/endpoint/put-file-attach"
            },
            {
              label: "商品视频",
              hide: true,
              viewDisplay: false,
              prop: "goodsVideo",
              type: 'upload',
              fileSize: 20480,
              listType: 'picture-img',
              span: 24,
              accept: "video/mp4",
              loadText: '附件上传中，请稍等',
              tip: '只能上传mp4文件，且不超过20M',
              propsHttp: {
                res: 'data',
                url: 'link',
              },
              action: "/api/blade-resource/oss/endpoint/put-file-attach",
            },
          ]

        },
        goodsLoading: false,
        goodsData: [],
        goodsForm: {},
        goodsQuery: {},
        selectionListGoods: [],
        goodsPage: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.seckillgoods_add, true),
          viewBtn: this.vaildData(this.permission.seckillgoods_view, true),
          delBtn: this.vaildData(this.permission.seckillgoods_delete, true),
          editBtn: this.vaildData(this.permission.seckillgoods_edit, true)
        };
      },
      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) {
        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;
          });
        }
        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.selectionListGoods = [];
        this.$refs.crud.toggleSelection();
        this.$refs.crudGoods.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;
        this.query.seckillRoundId = this.seckillRoundId;
        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.data.forEach(e => {
            e.seckillRound = this.roundName;
          })
          this.loading = false;
          this.selectionClear();
        });
      },
      addGoodsOpen() {
        this.setGoodsDialogVisible = true;

      },
      handleClose() {
        this.setGoodsDialogVisible = false;
        this.onLoad(this.page);
      },
      onLoadGoods(page, params = {}) {
        this.goodsLoading = true;
        getGoodsList(page.currentPage, page.pageSize, Object.assign(params, this.goodsQuery)).then(res => {
          const data = res.data.data;
          this.goodsPage.total = data.total;
          this.goodsData = data.records;
          this.goodsData.forEach(e => {
            e.seckillNum = 1000;
            e.$cellEdit = true;
          })
          this.goodsLoading = false;
          this.selectionClear();
        });
      },
      selectionChangeGoods(list) {
        this.selectionListGoods = list;
      },
      searchChangeGoods(params, done) {
        this.goodsQuery = params;
        this.goodsPage.currentPage = 1;
        this.onLoadGoods(this.goodsPage, params);
        done();
      },
      currentChangeGoods(currentPage){
        this.goodsQuery.currentPage = currentPage;
      },
      sizeChangeGoods(pageSize){
        this.goodsQuery.pageSize = pageSize;
      },
      refreshChangeGoods() {
        this.onLoadGoods(this.goodsPage, this.goodsQuery);
      },
      searchResetGoods() {
        this.goodsQuery = {};
        this.onLoadGoods(this.goodsPage);
      },
      beforeOpenGoods(done, type) {
        if (["edit", "view"].includes(type)) {
          getGoodsDetail(this.goodsForm.id).then(res => {
            this.goodsForm = res.data.data;
            this.goodsForm.uploadCover = res.data.data.goodsCover;
            this.goodsForm.goodsVideo = res.data.data.videoUrl;
            this.goodsForm.slideshowList = res.data.data.slideshowList;
            this.goodsForm.detailImgUrlList = res.data.data.detailImgUrlList;
            this.goodsForm.categoryIdArr = this.goodsForm.goodsCategoryId.split("-");
          });
        }
        done();
      },
      submitGoods() {
        if (this.selectionListGoods.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        let param = [];
        this.selectionListGoods.forEach(e => {
          let obj = {
            seckillRoundId: this.seckillRoundId,
            goodsId: e.id,
            goodsQuantity: e.seckillNum,
            rushNum: 0
          };
          param.push(obj);

        });
        add(param).then(res => {
          this.$message.success("添加成功");
          this.onLoadGoods(this.goodsPage);
        })
      }
    }
  };
</script>

<style>
</style>
