<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page.sync="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               :upload-error="uploadError"
               :upload-after="uploadAfter"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-click="handleRowClick"
               @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="isSale" slot-scope="scope" >
        <el-tag v-if="scope.row.$isSale === '上架'" type="success">{{scope.row.$isSale}}</el-tag>
        <el-tag v-if="scope.row.$isSale === '下架'" type="danger">{{scope.row.$isSale}}</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-scope="scope" slot="menu">
        <el-button v-if="scope.row.isSale == 1"
            type="text"
            size="small"
            @click="modifyGoodsState(scope.row.id, 0)"
        >下架</el-button>
        <el-button v-if="scope.row.isSale == 0"
            type="text"
            size="small"
            @click="modifyGoodsState(scope.row.id, 1)"
        >上架
        </el-button>
        <el-button v-if="scope.row.auditStatus == 0"
                   type="text"
                   size="small"
                   @click="openAuditBox(scope.row.id)"
        >审核</el-button>
      </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>
  </basic-container>
</template>


<script>
  import {getList, getDetail, add, update, remove, modifyState, audit} from "@/api/mall/goodsinfo";
  import {mapGetters} from "vuex";
  import {getByParentId} from "../../api/mall/categoryinfo";

  export default {

    data() {
      var validatePass = (rule, value, callback) => {
        if (value>=10 || value <=0) {
          callback(new Error('非法的折扣'));
        } else {
          callback();
        }
      }
      return {
        option:  {
          height: 'auto',
          calcHeight: 30,
          border: true,
          index: false,
          viewBtn: true,
          delBtn:false,
          editBtn: true,
          // selection: true,
          dialogClickModal: false,
          labelWidth: 150,
          searchIcon: true,
          searchIndex: 3,
          column: [
            {
              label: "商品编号",
              search: true,
              prop: "id",
              overHidden: true,
              addDisplay: false,
              editDisplay: false,
              editDisabled: true,
              width: 160
            },
            {
              label: "商品封面",
              width: 80,
              prop: "goodsCover",
              addDisplay: false,
              viewDisplay: false,
              editDisplay: false,
              type: 'img',
            },
            {
              label: "商品名称",
              prop: "goodsName",
              search: true,
              width: 280,
              overHidden: true,
              rules: [{
                required: true,
                message: "请输入商品名称",
                trigger: "blur"
              }]
            },
            {
              label: "规格",
              prop: "goodsSpec",
              editDisplay: false,
              rules: [{
                required: true,
                message: "请输入规格",
                trigger: "blur"
              }]
            },
            {
              label: "供应商",
              prop: "supplierId",
              editDisplay: true,
              viewDisplay: false,
              remote: true,
              hide: true,
              type: "select",
              dicUrl: "/api/mall/store/list?name={{key}}&state=1&auditState=1&size=30",
              props: {
                label: "name",
                value: "id"
              },
              dicFormatter: function (res) {
                return res.data.records;
              },
              rules: [{
                required: true,
                message: "请选择供应商",
                trigger: "blur"
              }]
            },
            {
              label: "供应商",
              prop: "supplierName",
              search: true,
              addDisplay: false,
              editDisplay: false,
            },
            {
              label: "品牌",
              prop: "brandDesc",
              hide: true,
              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: "discount",
              hide: true,
              precision: 2,
              type: "number",
              rules: [{
                required: true,
                message: "请输入折扣",
                trigger: "blur"
              },{ validator: validatePass, trigger: 'blur' }],
            },
            {
              label: "价格",
              prop: "salePrice",
              precision: 2,
              type: "number",
              formatter:(val,value)=>{
                return Number(value).toFixed(2);
              },
              rules: [{
                required: true,
                message: "请输入销售价",
                trigger: "blur"
              }],
            },
            {
              label: "状态",
              prop: "isSale",
              search: true,
              slot:true,
              rules: [{
                required: true,
                message: "请输入是否上架",
                trigger: "blur"
              }],
              type: "select",
              dicUrl: "/api/blade-system/dict-biz/getEnumDict?enumName=GoodsStateEnum",
              props: {
                label: "name",
                value: "value"
              },
              dataType: "number",
            },
            {
              label: "审核状态",
              prop: "auditStatus",
              search: true,
              slot:true,
              type: "select",
              dicUrl: "/api/blade-system/dict-biz/getEnumDict?enumName=AuditStatusEnum",
              props: {
                label: "name",
                value: "value"
              },
              dataType: "number",
            },
            {
              label: "上架时间",
              prop: "saleTime",
              hide: true,
              addDisplay: false,
              viewDisplay: false,
              editDisplay: false,
              editDisabled: true,
            },
            {
              label: "总库存",
              prop: "totalStock",
              type: "number",
              hide: true,
              min: 1,
              rules: [
                {required: true, message: "请输入总库存", trigger: "blur"},
              ]
            },
            {
              label: "总销量",
              prop: "totalSales",
              hide: true,
              addDisplay: false,
              editDisplay: false,
            },
            {
              label: "总浏览量",
              prop: "totalViews",
              hide: true,
              addDisplay: false,
              editDisplay: false,
            },
            {
              label: "单位",
              prop: "unit",
              hide: true,
              rules: [{
                required: true,
                message: "请选择单位",
                trigger: "blur"
              }],
              type: "select",
              remote: true,
              dicUrl: "/api/mall/unit/all-list",
              props: {
                label: "name",
                value: "id"
              },
              dataType: "string",
            },
            {
              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',
              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: '图文详情',
              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"
            },
          ]
        },
        range: {
          from: '',
          to: ''
        },
        categoryData: [],
        props: {
          label: "title",
          value: "key"
        },
        categoryIdArr: [],
        auditBox: false,
        auditForm: {
          auditStatus: '',
          id: '',
          remark: ''
        },
        form: {

        },
        goodsParamForm: {},
        goodsSpecForm: {},
        scForm: {},
        query: {},
        goodsParamQuery: {},
        viewSpecQuery: {},
        loading: true,
        paramLoading: true,
        box: false,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        data: [],
        goodsParamData: [],
        viewSpecData: [],
        scData: [],

        viewDialog: false,
        auditList: [
          {name: '通过', value: 1},{name: '驳回', value: 2}
        ]
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.goodsinfo_add, false),
          viewBtn: this.vaildData(this.permission.goodsinfo_view, false),
          delBtn: this.vaildData(this.permission.goodsinfo_delete, false),
          editBtn: this.vaildData(this.permission.goodsinfo_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      },
      specIds() {
        let ids = [];
        this.specSelectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
      viewDialogShow(row) {
        this.viewDialog = true;
        this.demoModelSrc = `${this.demoModelSrcYuan}?aa=${JSON.stringify(row)}`

      },
      rowSave(row, done, loading) {
        row.goodsCategoryId = row.categoryIdArr.join("-");
        if (row.promotionRateRange == '') {
          delete row.promotionRateRange;
        }
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        row.goodsCategoryId = row.categoryIdArr.join("-") + "-";
        if (row.promotionRateRange == '') {
          delete row.promotionRateRange;
        }
        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.form.uploadCover = res.data.data.goodsCover;
            this.form.goodsVideo = res.data.data.videoUrl;
            this.form.slideshowList = res.data.data.slideshowList;
            this.form.detailImgUrlList = res.data.data.detailImgUrlList;
            this.form.categoryIdArr = this.form.goodsCategoryId.split("-");
          });
          console.log(this.form.goodsCategoryId.split("-"));
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.range = {
          from: '',
            to: ''
        };
        this.activityDate = '';
        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;
        if (this.query.categoryIdArr) {
          this.query.goodsCategoryId = this.query.categoryIdArr.join("-");
          this.query.categoryIdArr = null;
        }
        this.query.activityDate = this.activityDate;
        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.success('上传失败:' + error)
        console.log(error, column)
      },
      uploadAfter(res, done, loading,column) {
        console.log(res,column)
        if(column.prop == "uploadCover") {
          this.form.goodsCover = res.link;
        }
        if (column.prop == "goodsVideo") {
          this.form.videoUrl = res.link;
        }
        done()
      },
      paramConfig(row) {
        this.box = true;
        this.goodsParamQuery.goodsId = row.id;
        this.onLoadParam();
      },

      handleRowClick(row, event, column, loading) {
        if (event.label == '是否上架') {
          const param = {id:row.id, isSale:row.saleSwitch ? 1 : 0}
          update(param).then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: row.saleSwitch ? "上架成功" : "下架成功"
            });
          }, error => {
            loading();
            console.log(error);
          });
        }
      },

      handleClose() {
        this.categoryIdArr = [];
        this.auditBox = false;
        this.auditForm = {
          auditStatus: '',
              id: '',
              remark: ''
        };
      },
      modifyGoodsStateBatch(state) {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定修改数据?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            const loading = this.$loading({
              lock: true,
              text: '修改中，请稍等...',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.7)'
            });
            modifyState(this.ids, state).then(() => {
              loading.close();
              this.onLoad(this.page, this.query);
              this.$message({
                type: "success",
                message: "操作成功!"
              });
              this.selectionClear()
            });
          })
      },
      modifyGoodsState(id, state) {
        let title = state === 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)'
          });
          modifyState(id, state).then(() => {
            loading.close();
            this.onLoad(this.page, this.query);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            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);
        });
      }
    }
  };
</script>

<style>
</style>
