<template>
  <div class="app-container">
    <el-card >
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="商品档案" name="goods"></el-tab-pane>
          <el-tab-pane label="商品回收站" name="recovery"></el-tab-pane>
        </el-tabs>
        <el-form-item label="商品分类" prop="cvsGoodId">
          <el-select
            v-model="queryParams.cvsGoodId"
            placeholder="全部"
            clearable
            style="width: 300px"
          >
            <el-option v-for="item in cvsGoodList" :key="item.id" :label="item.name" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="供应商" prop="supplierId">
          <el-select
            v-model="queryParams.supplierId"
            placeholder="全部"
            clearable
            style="width: 300px"
          >
            <el-option v-for="item in supplierList" :key="item.id" :label="item.name" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="商品名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入商品名称"
            clearable
            style="width: 240px;"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="拼音码" prop="pinyinCode">
          <el-input
            v-model="queryParams.pinyinCode"
            placeholder="请输入拼音码"
            clearable
            style="width: 240px;"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="条形码" prop="goodsNo">
          <el-input
            v-model="queryParams.goodsNo"
            placeholder="请输入商品条形码"
            clearable
            style="width: 240px;"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="货架号" prop="shelfNumber">
          <el-input
            v-model="queryParams.shelfNumber"
            placeholder="请输入商品所在货架号"
            clearable
            style="width: 240px;"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="等级状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="全部"
            clearable
            style="width: 240px"
          >
            <el-option
              v-for="dict in dict.type.zhzt"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card style="margin-top: 20px">
      <el-button
        type="primary"
        icon="el-icon-plus"
        @click="handleAdd"
        v-hasPermi="['member:add']"
      >新增商品</el-button>
      <el-table ref="tables" v-loading="loading" :data="list"
                @selection-change="handleSelectionChange" :default-sort="defaultSort"
                @sort-change="handleSortChange">
        <el-table-column label="ID" prop="id" align="center" width="60"/>
        <el-table-column label="分类名称" prop="cvsGoodId" align="center">
          <template slot-scope="scope">
            <span>{{ getName(cvsGoodList, scope.row.cvsGoodId) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="商品名称" prop="name" align="center" width="160"/>
        <el-table-column label="供应商" prop="supplierId" align="center">
          <template slot-scope="scope">
            <span>{{ getName(supplierList, scope.row.supplierId) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="条码" prop="goodsNo" align="center" width="160"/>
        <el-table-column label="拼音码" prop="pinyinCode" align="center"/>
        <el-table-column label="货架号" prop="shelfNumber" align="center"/>
        <el-table-column label="库存" prop="stock" align="center"/>
        <el-table-column label="单位" prop="unit" align="center"/>
        <el-table-column label="进货价" prop="buyingPrice" align="center"/>
        <el-table-column label="零售价" prop="retailPrice" align="center"/>
        <el-table-column label="会员价" prop="memberPrice" align="center"/>
        <el-table-column label="状态" align="center" prop="status">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.zhzt" :value="scope.row.status"/>
          </template>
        </el-table-column>
        <el-table-column label="更新时间" align="center" width="160" prop="updateTime">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.updateTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" v-if="activeName=='goods'" align="center" width="200" fixed='right'>
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              v-hasPermi="['member:add']"
              @click="handleUpdate(scope.row)"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              v-hasPermi="['member:add']"
              @click="isRecoveryBin(scope.row,1)"
            >移至回收站</el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" v-if="activeName=='recovery'" align="center" width="200" fixed='right'>
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-shopping-cart-full"
              v-hasPermi="['member:add']"
              @click="isRecoveryBin(scope.row,0)"
            >移出至商品档案</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              v-hasPermi="['member:add']"
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.page"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改对话框 -->
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="商品条码" prop="goodsNo">
              <el-input v-model="form.goodsNo"
                        @keydown.enter.native="getGoods(form)"
                        placeholder="商品的条码信息">
                <el-button slot="append">查询</el-button>
              </el-input>
              <div style="text-align: right;color: grey;font-size: 12px">
                商品无条码？您可以<span style="color: #00afff" @click="createGoodNo">生成条码</span>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="商品名称" prop="name">
              <el-input v-model="form.name" @input="pinyin" placeholder="请输入商品名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属分类" prop="cvsGoodId">
              <el-select
                v-model="form.cvsGoodId"
                placeholder="全部"
                clearable
                style="width: 300px"
              >
                <el-option v-for="item in cvsGoodList" :key="item.id" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="进货单价" prop="buyingPrice">
              <el-input v-model="form.buyingPrice">
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="零售价" prop="retailPrice">
              <el-input v-model="form.retailPrice">
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="会员价" prop="memberPrice">
              <el-input v-model="form.memberPrice">
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="拼音码" prop="pinyinCode">
              <el-input v-model="form.pinyinCode" placeholder="输入商品名称自动回填"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单位" prop="unit">
              <el-input v-model="form.unit" placeholder="如：个、瓶、包"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="货架号" prop="shelfNumber">
              <el-input v-model="form.shelfNumber" placeholder="如：1-2-2"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="是否使用积分抵扣" prop="canUsePoint" label-width="110">
              <el-radio-group v-model="form.canUsePoint">
                <el-radio  v-for="dict in dict.type.yes_or_no"  :label="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="初始库存" prop="stock">
              <el-input v-model="form.stock" placeholder="0"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="供应商" prop="supplierId">
              <el-select
                v-model="form.supplierId"
                placeholder="全部"
                clearable
                style="width: 300px"
              >
                <el-option v-for="item in supplierList" :key="item.id" :label="item.name" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="排序" prop="sort">
              <el-input-number v-model="form.sort" @change="handleChange" :min="0" label="0"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio  v-for="dict in dict.type.zhzt"  :label="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-alert
        type="error"
        style="margin-top: 15px"
        :closable="false">
        <p v-for="(item,index) in stockType" :id="index">
          {{item}}
        </p>
      </el-alert>
      <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 {selectTree} from "@/api/convenienceStore/goods";
import {listSupplier} from "@/api/convenienceStore/supplier";
import {
  addLJGoods,
  createGoodsNo,
  delLJGoods,
  getLJGoods,
  listLJGoods, scanCode,
  updateLJGoods
} from "@/api/convenienceStore/ljgoods";
import {getSysConfig} from "@/api/staff/user/sysconfig";
import pinyin from "js-pinyin";

export default {
  dicts: ['zhzt','yes_or_no'],
  data(){
    return {
      activeName: 'goods',
      // 关联库存类型
      stockType:'',
      cvsGoodName:'',
      // 遮罩层
      loading: true,
      // 标题
      title: "",
      // 总条数
      total: 0,
      // 表格数据
      list: [],
      // 是否显示修改对话框
      open: false,
      // 默认排序
      defaultSort: {prop: 'updateTime', order: 'descending'},
      // 商品分类列表
      cvsGoodList:[],
      // 供应商列表
      supplierList:[],
      // 查询参数
      queryParams: {
        page: 1,
        pageSize: 10,
        id: '',
        cvsGoodId: '',
        supplierId: '',
        name: '',
        pinyinCode: '',
        goodsNo: '',
        shelfNumber: '',
        status: '',
        isRecovery:0,
      },
      // 表单参数
      form: {
        id:'',goodsNo:'',name:'',cvsGoodId:"",buyingPrice:'',retailPrice:"",memberPrice:'',pinyinCode:"",
        unit:'',shelfNumber:'',canUsePoint:'no',stock:0,supplierId:'',sort:0,status:'qy'
      },
      // 显示搜索条件
      showSearch: true,
      // 表单校验
      rules: {
        goodsNo: [
          { required: true, message: "商品条码不能为空", trigger: "blur" },
        ],
        name: [
          { required: true, message: "商品名称不能为空", trigger: "blur" },
        ],
        cvsGoodId: [
          { required: true, message: "请选择商品分类", trigger: "blur" },
        ],
        buyingPrice: [
          { required: true, message: "请输入商品进货单价", trigger: "blur" },
        ],
        retailPrice: [
          { required: true, message: "请输入商品零售价", trigger: "blur" },
        ],
        memberPrice: [
          { required: true, message: "请输入商品会员价", trigger: "blur" },
        ],
        pinyinCode: [
          { required: true, message: "商品拼音码不能为空", trigger: "blur" },
        ],
        unit: [
          { required: true, message: "请输入商品单位", trigger: "blur" },
        ],
        canUsePoint: [
          { required: true, message: "请选择是否能使用积分抵扣", trigger: "blur" },
        ],
        supplierId: [
          { required: true, message: "请选择供应商", trigger: "blur" },
        ],
        status: [
          { required: true, message: "请选择商品状态", trigger: "blur" },
        ],
      }
    }
  },
  created() {
    this.getList();
    this.getQueryList();
    this.getType();
  },
  computed:{
  },
  methods:{
    // 点击标签页
    handleClick(tab, event) {
      if (this.activeName == 'goods'){
        this.queryParams = {
          page: 1,
          pageSize: 10,
          id: '',
          cvsGoodId: '',
          supplierId: '',
          name: '',
          pinyinCode: '',
          goodsNo: '',
          shelfNumber: '',
          status: '',
          isRecovery:0,
        };
        this.getList();
      }else {
        this.queryParams = {
          page: 1,
          pageSize: 10,
          id: '',
          cvsGoodId: '',
          supplierId: '',
          name: '',
          pinyinCode: '',
          goodsNo: '',
          shelfNumber: '',
          status: '',
          isRecovery:1,
        };
        this.getList();
      }
    },
    // 扫描识别商品信息
    getGoods(form){
      // console.log(form){goodsNo:form.goodsNo}
      scanCode({goodsNo:form.goodsNo}).then(response => {
        console.log(response)
        // this.form = response.data
      })
    },
    // 生成13位数字条码信息
    createGoodNo(){
      createGoodsNo().then(response => {
        this.form.goodsNo = response.data
      })
    },
    // 获取中文首字母拼音
    pinyin(){
      let pinyin = require("js-pinyin");
      pinyin.setOptions({ checkPolyphone: false, charCase: 1 });
      this.form.pinyinCode = pinyin.getCamelChars(this.form.name)
    },
    // 排序计步器
    handleChange(value) {
      console.log(value);
    },
    // 获取分类名称
    getType(){
      getSysConfig('stock_type').then(response => {
        this.stockType = response.data.split(";")
      });
    },
    // 查询搜索列表信息
    getQueryList(){
      selectTree().then(response => {
        this.cvsGoodList = response.data.records
      });
      listSupplier().then(response => {
        this.supplierList = response.data.records
      })
    },
    // 查询列表
    getList() {
      this.loading = true;
      listLJGoods(this.queryParams).then(response => {
        this.list = response.data.records;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 搜索按钮操作
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    // 重置按钮操作
    resetQuery() {
      this.resetForm("queryForm");
      this.$refs.tables.sort(this.defaultSort.prop, this.defaultSort.order);
      this.handleQuery();
    },
    // 表单重置
    reset() {
      this.resetForm("form");
      this.form= {
        id:'',goodsNo:'',name:'',cvsGoodId:"",buyingPrice:'',retailPrice:"",memberPrice:'',pinyinCode:"",
        unit:'',shelfNumber:'',canUsePoint:'no',stock:0,supplierId:'',sort:0,status:'qy'
      }
    },
    // 是否移至回收站
    isRecoveryBin(form,recovery){
      let name = ""
      let prompt = ''
      if (recovery==1){
        name = "确定要将此商品移至回收站吗?移出后将无法售卖当前商品！"
        prompt = "商品已移至回收站,收银台商品信息页面刷新后实时生效！"
      }else {
        name = "确定要将此商品从回收站移至商品档案里吗?移出后将可售卖当前商品！"
        prompt = "商品已移至商品档案,收银台商品信息页面刷新后实时生效！"
      }
      this.$modal.confirm(name).then(function() {
        form.isRecovery = recovery;
        updateLJGoods(form).then(response => {
          this.getList();
        });
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess(prompt);
      }).catch(() => {});

    },
    // 新增按钮操作
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增商品";
    },
    // 修改按钮操作
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getLJGoods(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "编辑商品";
      });
    },
    // 删除按钮操作
    handleDelete(row) {
      const name = row.name
      this.$modal.confirm('确定删除"' + name + '"的商品信息？').then(function() {
        return delLJGoods(row.id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    // 提交按钮
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id) {
            updateLJGoods(this.form).then(response => {
              this.$modal.msgSuccess("商品信息更新成功");
              this.open = false;
              this.getList();
            });
          } else {
            addLJGoods(this.form).then(response => {
              this.$modal.msgSuccess("商品信息新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.multiple = !selection.length
    },
    // 排序触发事件
    handleSortChange(column, prop, order) {
      this.queryParams.orderByColumn = column.prop;
      this.queryParams.isAsc = column.order;
      this.getList();
    },
  }
}
</script>

<style lang="scss" scoped>
.app-container{
  width: 100%;
  height: 100vh;
  background: #f6f8f9;
}
</style>
