<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-click="handleRowClick"
               @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
                   v-if="permission.goodsspec_delete"
                   @click="handleDelete">删 除
        </el-button>
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove} from "@/api/redenvelopemall/goodsspec";
  import {mapGetters} from "vuex";

  export default {
    data() {
      return {
        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          labelWidth: 170,
          height:'auto',
          calcHeight: 30,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: false,
          viewBtn: true,
          selection: true,

          dialogClickModal: false,
          column: [
            {
              label: "主键",
              prop: "id",
              hide: true,
              addDisplay: false,
              viewDisplay: false,
              editDisplay: false,
              editDisabled: true,
            },
            {
              label: "规格名称",
              prop: "spceName",
              search: true,
              rules: [{
                required: true,
                message: "请输入规格名称",
                trigger: "blur"
              }]
            },
            {
              label: "规格编号",
              overHidden: true,
              addDisplay: false,
              editDisabled: true,
              search: true,
              prop: "spceNo",
              rules: [{
                required: true,
                message: "请输入规格编号",
                trigger: "blur"
              }]
            },
            {
              label: "商品编号",
              prop: "goodsNo",
              overHidden: true,
              search: true,
              editDisabled: true,
              rules: [{
                required: true,
                message: "请输入商品id",
                trigger: "blur"
              }]
            },
            {
              label: "商品封面",
              prop: "coverShow",
              addDisplay: false,
              viewDisplay: false,
              editDisplay: false,
              type: 'upload',
              listType: 'picture-img',
            },
            {
              label: "是否默认规格",
              prop: "isDefault",
              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: "marketPrice",
              precision: 2,
              type: "number",
              hide: true,
              formatter:(val,value,label)=>{
                return Number(value).toFixed(2);
              },
              rules: [{
                required: true,
                message: "请输入市场价",
                trigger: "blur"
              }]
            },
            {
              label: "指导价",
              prop: "guidePrice",
              precision: 2,
              type: "number",
              hide: true,
              formatter:(val,value,label)=>{
                return Number(value).toFixed(2);
              },
            },
            {
              label: "协议价",
              prop: "agreementPrice",
              precision: 2,
              type: "number",
              formatter:(val,value,label)=>{
                return Number(value).toFixed(2);
              },
            },
            {
              label: "营销价",
              prop: "activityPrice",
              precision: 2,
              type: "number",
              hide: true,
              formatter:(val,value,label)=>{
                return Number(value).toFixed(2);
              },
              rules: [{
                required: true,
                message: "请输入营销价",
                trigger: "blur"
              }]
            },
            {
              label: "销售价",
              prop: "salePrice",
              precision: 2,
              type: "number",
              formatter:(val,value,label)=>{
                return Number(value).toFixed(2);
              },
              rules: [{
                required: true,
                message: "请输入销售价",
                trigger: "blur"
              }]
            },
            {
              label: "成本价",
              prop: "costPrice",
              precision: 2,
              type: "number",
              hide: true,
              formatter:(val,value,label)=>{
                return Number(value).toFixed(2);
              },
              rules: [{
                required: true,
                message: "请输入成本价",
                trigger: "blur"
              }]
            },
            {
              label: "毛利率",
              prop: "promotionRate",
              addDisplay: false,
              editDisplay: false,
              editDisabled: true,
            },
            {
              label: "所需积分",
              prop: "exchangeNeedIntegral",
              addDisplay: false,
              editDisplay: false,
              hide: true
            },
            {
              label: "所需金额",
              prop: "needAmount",
              addDisplay: false,
              editDisplay: false,
              hide: true
            },
            {
              label: "营销利润率",
              prop: "activityRate",
              hide: true,
              addDisplay: false,
              editDisplay: false,
              editDisabled: true,
            },
            {
              label: "库存",
              prop: "stock",
              type: "number",
              rules: [{
                required: true,
                message: "请输入库存",
                trigger: "blur"
              }]
            },
            {
              label: "销量",
              prop: "sale",
              addDisplay: false,
              editDisplay: false,
              rules: [{
                required: true,
                message: "请输入销量",
                trigger: "blur"
              }]
            },
            {
              label: "是否能积分抵扣",
              prop: "isIntegralDeduction",
              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: "needIntegral",
              type: "number",
              hide: true,
              rules: [{
                required: true,
                message: "请输入抵扣所需积分",
                trigger: "blur"
              }]
            },
            {
              label: "购买时获得的积分数",
              hide: true,
              prop: "obtainIntegral",
              type: "number",
              rules: [{
                required: true,
                message: "请输入购买时获得的积分数",
                trigger: "blur"
              }]
            },
            {
              label: "是否为套装",
              prop: "isPackage",
              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: "套装商品数量",
              hide: true,
              prop: "packageNum",
              type: "number",
              rules: [{
                required: true,
                message: "请输入购买时获得的积分数",
                trigger: "blur"
              }]
            },
            {
              label: "专区类型",
              prop: "zoneType",
              search: true,
              addDisplay: false,
              viewDisplay: false,
              editDisplay: false,
              editDisabled: 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: 'saleSwitch',
              type:'switch',
              cell: true,
              addDisplay: false,
              viewDisplay: false,
              editDisplay: false,
              editDisabled: true,
            },
            {
              label: "是否上架",
              prop: "isSale",
              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: "rate",
              precision: 2,
              type: "number",
              hide: true,
              formatter:(val,value,label)=>{
                return Number(value).toFixed(2);
              },
            },
            {
              label: '规格图片',
              prop: 'cover',
              type: 'upload',
              listType: 'picture-img',
              loadText: '上传中，请稍等',
              accept: 'image/png, image/jpeg',
              fileSize: 500,
              tip: '只能上传jpg/png文件，且不超过500kb',
              span: 24,
              hide: true,
              propsHttp: {
                res: 'data',
                url: 'link',
              },
              action: "/api/blade-resource/oss/endpoint/put-file-attach"
            },
          ]
        },
        data: []
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.goodsspec_add, false),
          viewBtn: this.vaildData(this.permission.goodsspec_view, false),
          delBtn: this.vaildData(this.permission.goodsspec_delete, false),
          editBtn: this.vaildData(this.permission.goodsspec_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) {
        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.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad: function (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;
          const needAmount = this.findObject(this.option.column, "needAmount");
          const exchangeNeedIntegral = this.findObject(this.option.column, "exchangeNeedIntegral");
          if (this.query.zoneType == 2) {
            needAmount.hide = false;
            exchangeNeedIntegral.hide = false;
          } else {
            needAmount.hide = true;
            exchangeNeedIntegral.hide = true;
          }
          this.data.forEach(e => {
            e.coverShow = e.cover;
            e.$cellEdit = true;
            if (e.isSale == "1") {
              e.saleSwitch = true;
            } else {
              e.saleSwitch = false;
            }
          })
          this.loading = false;
          this.selectionClear();
        });
      },
      handleRowClick(row, event, column, loading) {
        if (event.label == '是否上架') {
          row.isSale = row.saleSwitch ? 1 : 0;
          update(row).then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: row.saleSwitch ? "上架成功" : "下架成功"
            });
          }, error => {
            loading();
            console.log(error);
          });
        }
      }
    }
  };
</script>

<style>
</style>
