<template>
  <div class="app-container">
    <div class="card-change">
      <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="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入商品名称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="" prop="cvsGoodId">
          <el-select
            v-model="queryParams.cvsGoodId"
            placeholder="请选择品类名称"
            clearable
          >
            <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=""
          >
            <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="shelfNumber">
          <el-input
            v-model="queryParams.shelfNumber"
            placeholder="请输入货架号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="请选择状态"
            clearable
          >
            <el-option label="上架" value="qy"/>
            <el-option label="下架" value="jy"/>
          </el-select>
        </el-form-item>
        <el-form-item style="float: right;margin-right: 0px">
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
          <el-button
            type="primary"
            @click="batchGrounding('qy')"
            v-hasPermi="['convenienceStore:goodsFile:up']"
          >商品上架
          </el-button>
          <el-button
            type="primary"
            @click="batchGrounding('jy')"
            v-hasPermi="['convenienceStore:goodsFile:down']"
          >商品下架
          </el-button>
          <el-button type="primary" @click="handleAdd">新增商品</el-button>
        </el-form-item>
      </el-form>

      <div>
        <div style="font-size: 12px;color: red;margin: 5px 0">注：库存为0或未设置零售价和会员价的商品不可上架</div>
      </div>

      <div style="height: 68vh;overflow: auto">
        <el-table ref="tables" v-loading="loading" :data="list"
                  @selection-change="handleSelectionChange"
                  border
                  tooltip-effect="dark">
          <el-table-column type="selection" width="40"/>
          <el-table-column type="index" width="60" align="center" label="序号"/>
          <el-table-column label="品类名称" prop="cvsGoodName" align="center">
            <template slot-scope="scope">
              <span>{{ scope.row.cvsGoodName || "--" }}</span>
            </template>
          </el-table-column>
          <el-table-column label="商品名称" prop="name" align="center"/>
          <el-table-column label="供应商" prop="supplierName" align="center"/>
          <el-table-column label="条形码" prop="goodsNo" align="center" width="140"/>
          <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="goodsSpecs" 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="排序" prop="sort" align="center"/>
          <el-table-column label="状态" align="center" prop="status">
            <template slot-scope="scope">
              <div style="color: #0DC291" v-if="scope.row.status=='qy'">已上架</div>
              <div style="color: #F44522" v-if="scope.row.status=='jy'">已下架</div>
            </template>
          </el-table-column>
          <el-table-column label="操作人" prop="realName" align="center"/>
          <el-table-column label="操作时间" align="center" width="154" prop="updateTime">
            <template slot-scope="scope">
              <span>
                {{ scope.row.updateTime ? parseTime(scope.row.updateTime) : parseTime(scope.row.createTime) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="130" fixed='right'>
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['convenienceStore:goodsFile:weih']"
              >商品维护
              </el-button>

              <el-button
                size="mini"
                type="text"
                @click="handleDelete(scope.row)"
                v-hasPermi="['convenienceStore:goodsFile:del']"
              >删除
              </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"
                @click="isRecoveryBin(scope.row,0)"
                v-hasPermi="['convenienceStore:goodsFile:move']"
              >移出至商品档案
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="isRecoveryBin(scope.row,1)"
                v-hasPermi="['convenienceStore:goodsFile:movedel']"
              >移至回收站
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.page"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <!-- 添加或修改对话框 -->
    <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="100px">
        <div style="display: flex;justify-content: space-between">
          <div style="width: 50%">
            <el-form-item label="商品名称" prop="name">
              <el-input v-model="form.name" @input="pinyin" placeholder="请输入商品名称"/>
            </el-form-item>
            <el-form-item label="品类名称" prop="cvsGoodId">
              <el-select
                v-model="form.cvsGoodId"
                placeholder="请选择品类名称"
                clearable
                style="width: 100%"
              >
                <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="pinyinCode">
              <el-input v-model="form.pinyinCode" disabled placeholder="输入商品名称自动回填"/>
            </el-form-item>
            <el-form-item label="商品规格" prop="goodsSpecs">
              <el-input v-model="form.goodsSpecs" placeholder="输入商品规格，如：500ml，50g"/>
            </el-form-item>
            <el-form-item label="单位" prop="unit">
              <el-input v-model="form.unit" placeholder="如：个、瓶、包"/>
            </el-form-item>
            <el-form-item label="初始库存" prop="stock" v-if="form.id">
              <el-input v-model="form.stock" oninput="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')"
                        maxlength="10" :disabled="true" placeholder="0"/>
            </el-form-item>
            <el-form-item label="排序" prop="sort">
              <el-input-number v-model="form.sort" :min="0" label="0" style="width: 100%"></el-input-number>
            </el-form-item>
            <el-form-item label="状态" prop="status" v-if="form.id">
              <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 label="qy" value="qy">上架</el-radio>
                <el-radio label="jy" value="jy">下架</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>
          <div style="width: 50%">
            <el-form-item label="商品条形码" prop="goodsNo">
              <el-input v-model="form.goodsNo"
                        @keydown.enter.native="getGoods(form)"
                        :disabled="form.id"
                        v-focus
                        clearable
                        placeholder="请用扫描枪扫码或输入条形码或自动生成条形码">
                <el-button :disabled="form.id" slot="append" @click="createGoodNo" icon="el-icon-refresh"></el-button>
              </el-input>
            </el-form-item>
            <el-form-item label="成本价" prop="buyingPrice" v-if="form.id">
              <el-input disabled v-model="form.buyingPrice" maxlength="10"
                        oninput="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')">
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
            <el-form-item label="零售价" prop="retailPrice" v-if="form.id">
              <el-input v-model="form.retailPrice" maxlength="10" @input="getPrice"
                        oninput="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')">
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
            <el-form-item label="会员价" prop="memberPrice" v-if="form.id">
              <el-input v-model="form.memberPrice" maxlength="10"
                        oninput="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')">
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
            <el-form-item label="货架号" prop="shelfNumber">
              <el-input v-model="form.shelfNumber" placeholder="请输入货架号，如：1-2-2"/>
            </el-form-item>
            <el-form-item label="供应商" prop="supplierId">
              <el-select
                v-model="form.supplierId"
                filterable
                placeholder="请选择供应商"
                @visible-change="changeSupplier"
                clearable
                style="width: 100%">
                <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="description">
              <el-input v-model="form.description" placeholder="请输入商品简介" type="textarea"/>
            </el-form-item>
          </div>
        </div>

      </el-form>
      <div class="dialog-footer" style="text-align: center">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>


import {cvsGoodsAll, cvsGoodsTree, selectTree} from "@/api/convenienceStore/goods";
import {addSupplier, listSuppliers} from "@/api/convenienceStore/supplier";
import {
  addLJGoods,
  createGoodsNo,
  delLJGoods, editStatus,
  getLJGoods,
  listLJGoods, queryLJGoods, scanCode,
  updateLJGoods
} from "@/api/convenienceStore/ljgoods";
import {getSysConfig} from "@/api/staff/user/sysconfig";
import pinyin from "js-pinyin";
import Vue from 'vue'

Vue.directive('focus', {
  inserted(el, binding, vnode) {
    el.querySelector('input').focus()
  },
})
export default {
  dicts: ['zhzt', 'yes_or_no'],
  data() {
    return {
      // 供应商信息
      supplier: "",
      // 商品分类id
      cvsGoodId: [],
      cvsGoodOptions: [],
      isAdd: false,
      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',
        canUseExchange: '1',
        stock: 0,
        supplierId: '',
        sort: 0,
        status: 'qy'
      },
      // 显示搜索条件
      showSearch: true,
      ids: [],
      // 表单校验
      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"},
        ],
        goodsSpecs: [
          {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.getSuppilers();
    this.getType();
    this.getTree();
  },
  computed: {},
  methods: {
    // 修改供应商
    changeSupplier(val) {
      if (val) {
        listSuppliers({ifDelete: '0'}).then(response => {
          this.supplierList = response.data
        })
      } else {
        this.getSuppilers();
      }
    },
    // 模糊查询商品信息
    querySearch(queryString, cb) {
      let _this = this;
      let results = _this.supplierList;
      if (queryString != "") {
        results = [];
        let falg = false;
        _this.supplierList.forEach(item => {
          if (item.name.includes(queryString)) {
            results.push(item)
            falg = true
          }
        })
        if (!falg) {

        }
      }
      cb(results);
    },
    // 查询供应商信息
    selectSupplier(data) {
      this.supplier = data.name;
      this.form.supplierId = data.id
      // console.log(data,this.form)
    },
    addSupplier(val) {
      // console.log(val,222)
      addSupplier({name: val, remark: "添加商品自动添加", ifDelete: '0'}).then(res => {
        // console.log(res)
        if (res.data == 1) {
          this.$modal.msgSuccess("已为您自动添加此供应商")
          this.supplier = val;
          this.getSuppilers(val)
        }
      })
    },
    // 获取分类菜单
    getTree() {
      cvsGoodsTree().then(response => {
        this.cvsGoodOptions = response.data
      })
    },
    // 价格填写
    getPrice() {
      this.form.memberPrice = this.form.retailPrice
    },
    // 点击标签页
    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) {
      if (form.goodsNo != "") {
        scanCode(form.goodsNo).then(response => {
          if (response.data != null && response.data != "") {
            this.form.goodsNo = response.data.barcode;
            this.form.name = response.data.goodsName;
            this.form.buyingPrice = response.data.price;
            this.form.retailPrice = response.data.price;
            this.form.memberPrice = response.data.price;
            this.pinyin();
          }
        })
      }
    },
    // 生成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, this.form.sort);
    },
    // 获取分类名称
    getType() {
      getSysConfig('stock_type').then(response => {
        this.stockType = response.data.split(";")
      });
    },
    // 查询搜索列表信息
    getQueryList() {
      cvsGoodsAll().then(response => {
        this.cvsGoodList = response.data
      });
    },
    getSuppilers(val) {
      listSuppliers().then(response => {
        this.supplierList = response.data
        if (val) {
          this.supplierList.forEach(item => {
            if (item.name = val) {
              this.form.supplierId = item.id
            }
          })
        }
      })
    },
    // 查询列表
    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;
      // if (this.cvsGoodId.length==1){
      //   this.queryParams.cvsGoodId = this.cvsGoodId[0]
      // }else {
      //   this.queryParams.cvsGoodId = this.cvsGoodId[1]
      // }
      this.getList();
    },
    // 重置按钮操作
    resetQuery() {
      this.cvsGoodId = ""
      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',
        canUseExchange: '1',
        stock: 0,
        supplierId: '',
        sort: 0,
        status: 'qy'
      }
    },
    // 是否移至回收站
    isRecoveryBin(form, recovery) {
      let name = ""
      let prompt = ''
      if (recovery == 1) {
        name = "确定要将此商品移至回收站吗?移出后将无法售卖当前商品！"
        prompt = "商品已移至回收站,收银台商品信息页面刷新后实时生效！"
        form.status = 'jy'
      } else {
        name = "确定要将此商品从回收站移至商品档案里吗?移出后将可售卖当前商品！"
        prompt = "商品已移至商品档案,收银台商品信息页面刷新后实时生效！"
      }
      this.$modal.confirm(name).then(function () {
        form.isRecovery = recovery;
        return updateLJGoods(form).then(response => {
          // this.getList();
        });
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess(prompt);
      }).catch(() => {
      });

    },
    // 新增按钮操作
    handleAdd() {
      if (this.cvsGoodList.length > 0) {
        this.reset();
        this.open = true;
        this.isAdd = false;
        this.title = "新增商品";
      } else {
        this.$modal.msgError("请先添加商品分类")
      }
    },
    // 修改按钮操作
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      getLJGoods(id).then(response => {
        this.form = response.data;
        // this.cvsGoodOptions.forEach(item => {
        //   if (item.value == response.data.cvsGoodId){
        //     this.cvsGoodId.push(item.value)
        //   }else {
        //     if (item.children.length>0){
        //       item.children.forEach(i => {
        //         if (i.value == response.data.cvsGoodId){
        //           this.cvsGoodId.push(item.value)
        //           this.cvsGoodId.push(i.value)
        //         }
        //       })
        //     }
        //   }
        // })
        console.log(this.supplierList)
        this.supplierList.forEach(item => {
          if (item.id == response.data.supplierId) {
            this.supplier = item.name
          }
        })
        // this.cvsGoodId = response.data.cvsGoodId
        this.open = true;
        this.isAdd = true;
        this.title = "商品维护";
      });
    },
    // 删除按钮操作
    handleDelete(row) {
      const name = row.name
      this.$modal.confirm('是否删除本条数据，删除后无法恢复！').then(function () {
        return delLJGoods(row.id);
      }).then(() => {
        this.queryParams.page = 1
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    // 提交按钮
    submitForm: function () {
      // if (this.cvsGoodId.length==1){
      //   this.form.cvsGoodId = this.cvsGoodId[0]
      // }else {
      //   this.form.cvsGoodId = this.cvsGoodId[1]
      // }
      if (this.form.status=='qy' && this.form.stock==0 || this.form.memberPrice==0 ||this.form.retailPrice==0){
        this.$message.error("请确保上架的商品库存大于0且为商品设置零售价和会员价")
        return;
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          // if (this.form.stock==0){
          //   this.$modal.msgError("库存不可为0");
          //   return;
          // }
          if (this.form.id) {
            updateLJGoods(this.form).then(response => {
              this.$modal.msgSuccess("商品信息更新成功");
              this.open = false;
              this.getList();
            });
          } else {
            queryLJGoods({goodsNo: this.form.goodsNo}).then(response => {
              if (response.data != null) {
                this.$modal.msgError("商品已存在");
              } 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)
    },
    // 批量上架
    batchGrounding(val) {
      let name = ""
      if (val == 'qy') {
        name = '上架'
      } else {
        name = '下架'
      }
      if (this.ids && this.ids.length > 0) {
        editStatus({ids: this.ids.toString(), status: val}).then(res => {
          if (val == 'qy') {
            if (res.data > 0) {
              this.$message.success(name + "成功")
              this.getList();
            } else {
              this.$message.error("请确保上架的商品库存大于0且为商品设置零售价和会员价")
            }
          } else {
            this.$message.success(name + "成功")
            this.getList();
          }
        })
      } else {
        this.$message.error("请选择需要" + name + "的商品")
      }
    },
    // 排序触发事件
    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: 100%;
  background: #f6f8f9;
}

.app-container .el-form--inline .el-form-item {
  margin-right: 20px;
}
</style>
