<template>
  <div class="app-container">
    <div class="app-container-search main-bgcolor main-radius">
      <h1 class="">商品管理</h1>
      <br />
      <!-- 搜索工作栏 -->
      <SearchInfo
        ref="searchForm"
        :searchFormParam="{ queryParams, dataSource }"
        :showSearch.sync="showSearch"
        @handleQuery="handleQuery"
        @resetQuery="resetQuery"
      ></SearchInfo>
    </div>

    <div class="app-container-list main-bgcolor main-radius shopping">
      <div class="shopping-top">
        <div class="shopping-title">商品列表</div>
        <el-button
          class="shopping-add-btn"
          type="primary"
          plain
          @click="handleAdd"
          v-hasPermi="['basic:goods-info:create']"
          >新增商品</el-button
        >
      </div>

      <!-- 列表 -->
      <el-table v-loading="loading" :data="list">
        <el-table-column label="编号" align="center" type="index" width="80">
          <template v-slot="{ $index }">
            <span>{{
              $index + 1 + (queryParams.pageNo - 1) * queryParams.pageSize
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="商品名称" prop="goodsName" width="200" />
        <el-table-column
          label="商品图片"
          align="center"
          prop="goodsImgUrl"
          width="230"
        >
          <template slot-scope="{ row }">
            <template v-if="row.goodsImgUrl != '--'">
              <el-image
                style="width: 60px; height: 60px; margin: 5px"
                v-for="(item, index) in row.goodsImgUrl"
                :key="index"
                :src="item"
                :preview-src-list="row.goodsImgUrl"
                fit="fill"
              ></el-image>
            </template>
            <template v-else>
              <span>{{ row.goodsImgUrl }}</span>
            </template>
          </template>
        </el-table-column>
        <el-table-column label="商品编码" prop="goodsId" width="150">
          <template slot-scope="{ row }">
            <el-tooltip
              class="item"
              effect="dark"
              :content="row.goodsId"
              placement="top"
            >
              <div class="flex-acenter">
                <span class="more-width-20">{{ row.goodsId }}</span>
                <el-button
                  type="text"
                  icon="el-icon-copy-document"
                  @click.stop="copyContent(row.goodsId)"
                ></el-button>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="所属商户" prop="belongBusinessName" width="200">
          <template slot-scope="{ row }">
            <div>
              <span>{{ row.belongBusinessName }}</span>
              <el-button
                type="text"
                icon="el-icon-copy-document"
                @click.stop="copyContent(row.belongBusinessName)"
              ></el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="品类名称" prop="goodsType" width="200">
          <template slot-scope="{ row }">
            <div>
              <el-tooltip
                class="item"
                effect="dark"
                :content="row.goodsType"
                placement="top"
              >
                <span class="more-width-full">{{ row.goodsType }}</span>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="商品规格" prop="goodsSpecs" width="150" show-overflow-tooltip/>
        <el-table-column label="保质期(天)" prop="shelfLife" width="100" />
        <el-table-column label="商品说明" prop="goodsRemarks" width="150" />
        <el-table-column
          label="操作"
          fixed="right"
          class-name="small-padding fixed-width"
          width="150"
        >
          <template v-slot="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['basic:goods-info:update']"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['basic:goods-info:delete']"
              >删除</el-button
            >
          </template>
        </el-table-column>
        <div slot="empty">
          <EmptyTable />
        </div>
      </el-table>
      <!-- 分页组件 -->
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNo"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 对话框(添加) -->
    <el-dialog
      class="add-dialog"
      :title="title"
      :visible.sync="open"
      width="800px"
      append-to-body
      @open="handleDialogOpen"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="80px"
        label-position="top"
      >
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="商品名称" prop="goodsName">
              <el-input
                :disabled="isDisable"
                v-model="form.goodsName"
                placeholder="请输入商品名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属商户" prop="belongBusinessId">
              <el-select
                class="w100"
                ref="businessName"
                @change="handchangeBusiness"
                v-model="form.belongBusinessId"
                :placeholder="this.belongBusinessPlaceholder"
              >
                <el-option
                  v-for="item in businessNameList"
                  :key="item.id"
                  :label="item.businessName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="品类名称" prop="goodsType">
              <el-cascader
                ref="cascader"
                v-model="form.goodsTypeId"
                :options="categoryList"
                class="w100"
                :props="{
                  label: 'name',
                  value: 'id',
                }"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="保质期(天)" prop="shelfLife">
              <el-input
                v-model="form.shelfLife"
                placeholder="请输入保质期(天)"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="商品说明"
              prop="goodsRemarks"
              :show-overflow-tooltip="true"
            >
              <el-input
                v-model="form.goodsRemarks"
                placeholder="请输入商品说明"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="商品规格" prop="goodsSpecs">
              <el-input
                style="width: 500px"
                placeholder="请输入"
                v-model="form.goodsSpecs"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="商品图片(最多上传6张)" prop="goodsImgUrl">
              <imageUpload v-model="form.goodsImgUrl" :limit="6" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  createGoodsInfo,
  updateGoodsInfo,
  deleteGoodsInfo,
  getGoodsInfo,
  getGoodsInfoPage,
} from "@/api/basic/goodsInfo";
import { getBusinessNameList } from "@/api/basic/businessInfo";
import { getCategoryList } from "@/api/basic/goodsCategory";
import SearchInfo from "@/components/Customer/SearchForm";
import EmptyTable from "@/components/EmptyTable";
import ImageUpload from "@/components/ImageUpload";
export default {
  name: "GoodsInfo",
  components: {
    SearchInfo,
    EmptyTable,
    ImageUpload,
  },
  data() {
    return {
      //所属商户下拉框提示
      belongBusinessPlaceholder: "请选择所属商户",
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品列表
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //头部查询表单组件的参娄
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        goodsName: null,
        goodsId: null,
        belongBusinessName: null,
      },
      dataSource: [
        {
          key: "goodsName",
          itemType: "input",
          label: "商品名称",
          placeholder: "请输入商品名称",
          onEnterKeyUp: this.handleQuery,
        },
        {
          key: "goodsId",
          itemType: "input",
          label: "商品编码",
          placeholder: "请输入商品编码",
          onEnterKeyUp: this.handleQuery,
        },
        {
          key: "belongBusinessName",
          itemType: "input",
          label: "所属商户",
          placeholder: "请输入所属商户名称",
          onEnterKeyUp: this.handleQuery,
        },
      ],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        goodsName: [
          { required: true, message: "商品名称不能为空", trigger: "blur" },
        ],
        goodsId: [
          { required: true, message: "商品编码不能为空", trigger: "blur" },
        ],
        goodsType: [
          { required: true, message: "商品类型不能为空", trigger: "change" },
        ],
        belongBusinessId: [
          { required: true, message: "所属商户不能为空", trigger: "blur" },
        ],
        belongBusinessName: [
          { required: true, message: "所属商户不能为空", trigger: "blur" },
        ],
        goodsSpecs: [
          { required: true, message: "商品规格不能为空", trigger: "blur" },
          { max: 32, message: "商品规格不能超过32个字符", trigger: "blur" },
        ],
        shelfLife: [
          {
            required: true,
            message: "保质期天数不能为空",
            trigger: "blur",
          },
          {
            pattern: /(^[0-9]*$)/,
            message: "保质期天数只能为数字",
            trigger: "blur",
          },
        ],
      },
      // 所属商户列表
      businessNameList: [],
      // 品类名称列表
      categoryList: [],
      isDisable: false,
    };
  },
  //刷新重新获取数据
  created() {
    // 取到路由带过来的参数
    let businessName = this.$route.query.businessName;
    let name = this.$route.query.name;
    if (businessName !== undefined && name) {
      this.queryParams.belongBusinessName = businessName;
    }
    this.getList();
    this.initDate();
  },
  activated() {
    // 取到路由带过来的参数
    let businessName = this.$route.query.businessName;
    let name = this.$route.query.name;
    if (businessName !== undefined && name) {
      this.queryParams.belongBusinessName = businessName;
    }
    this.getList();
  },
  methods: {
    handleDialogOpen() {
      // this.getUnitPage();
    },
    // 初始化数据
    initDate() {
      getCategoryList().then((res) => {
        this.categoryList = res.data;
      });
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      this.list = [];
      if (this.queryParams.goodsId == "") {
        this.queryParams.goodsId = null;
      }
      // 执行查询
      getGoodsInfoPage(this.queryParams).then((response) => {
        let list = response.data.list;
        list.map((item) => {
          if (item.goodsImgUrl) {
            if (item.goodsImgUrl.indexOf(",") != -1) {
              item.goodsImgUrl = item.goodsImgUrl.split(",");
            } else {
              item.goodsImgUrl = [item.goodsImgUrl];
            }
          } else {
            item.goodsImgUrl = "--";
          }
        });
        this.list = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        goodsName: undefined,
        goodsId: undefined,
        goodsType: undefined,
        goodsTypeId: undefined,
        goodsUnit: undefined,
        goodsSpecs: undefined,
        goodsRemarks: undefined,
        goodsImgUrl: undefined,
        shelfLife: undefined,
        belongBusinessId: undefined,
        belongBusinessName: undefined,
        goodsSpecs: undefined, // 商品规格
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      if (this.$route.query.name) {
        this.$router.replace({ query: {} });
      }
      this.resetForm("queryForm", "searchForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getBusinessNameList();
      this.belongBusinessPlaceholder = "请选择所属商户";
      this.title = "添加商品";
      this.isDisable = false;
      this.open = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      this.getBusinessNameList();
      getGoodsInfo(id).then((response) => {
        this.form = response.data;

        //当商户被删除时，无法显示对应的商户名称，重新定义
        let isTip = true;
        for (var x = 0; x < this.businessNameList.length; x++) {
          if (this.businessNameList[x].id == this.form.belongBusinessId) {
            isTip = false;
          }
        }
        if (isTip) {
          this.form.belongBusinessId = undefined;
          this.form.belongBusinessName = undefined;
          this.belongBusinessPlaceholder = "所属商户已删除，请重新选择";
        } else {
          this.belongBusinessPlaceholder = "请选择所属商户";
        }

        this.open = true;
        this.title = "修改商品";
        this.isDisable = true;
      });
      //
    },
    /** 提交按钮 */
    submitForm() {
      console.log("提交", this.form);
      this.$refs["form"].validate((valid) => {
        if (!valid) {
          return;
        }
        let form = JSON.parse(JSON.stringify(this.form));
        form.goodsTypeId = form.goodsTypeId[2];
        // 修改的提交
        if (this.form.id != null) {
          updateGoodsInfo(form).then((response) => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
          return;
        }
        // 添加的提交
        createGoodsInfo(form).then((response) => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      const goodsId = row.goodsId;
      this.$modal
        .confirm("是否确认删除该商品?")
        .then(function () {
          return deleteGoodsInfo(id, goodsId);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    // 获取商户列表
    getBusinessNameList() {
      getBusinessNameList().then((res) => {
        this.businessNameList = res.data;
      });
    },
    // 品类名称修改
    handleChange(e) {
      if (!this.categoryList) return false;
      this.form.goodsType = this.$refs["cascader"]
        .getCheckedNodes()[0]
        .pathLabels.join("/");
    },
    handchangeBusiness(e) {
      this.$nextTick(() => {
        this.form.belongBusinessName = this.$refs.businessName.selected.label;
      });
    },
  },
};
</script>
<style scoped lang="scss">
.hide {
  ::v-deep .el-upload--picture-card {
    display: none !important;
  }
}
</style>
