<template>
  <div class="app-container">
    <el-card style="margin-top: 20px;">
        <!-- 查询类别 -->
      <el-form :inline="true" :model="queryParams">
            <el-form-item label="品类名称" prop="name">
                <el-input v-model="queryParams.name" placeholder="请输入品类名称" clearable  @keyup.enter.native="handleQuery"></el-input>
            </el-form-item>
            <el-form-item label="状态">
                <el-select v-model="queryParams.status" placeholder="请选择品类状态" clearable >
                    <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="onQuery">搜索</el-button>-->
<!--                <el-button @click="resetForm" icon="el-icon-refresh" >重置</el-button>-->
<!--            </el-form-item>-->
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card style="margin-top: 15px;">
      <el-button
        type="primary"
        icon="el-icon-plus"
        @click="handleAdd"
      >添加品类</el-button>
<!--          <div class="tTop">品类列表-->
<!--              <el-button  type="primary" @click="insertGoods" >添加品类</el-button>-->
<!--          </div>-->
      <!-- default-expand-all二级菜单默认展开 -->
      <!-- 品类列表 -->
<!--      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"-->
      <el-table ref="tables" v-loading="loading" :data="list" row-key="id">
<!--                @selection-change="handleSelectionChange" :default-sort="defaultSort"-->
<!--                @sort-change="handleSortChange">-->
        <el-table-column type="expand" >
          <template slot-scope="props">
            <el-table ref="tables" :data="props.row.goodsVoList">
              <el-table-column type="index" width="80" align="center" label="序号"/>
              <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="250"/>
              <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="状态" align="center" prop="status">
                <template slot-scope="scope">
                  <el-tag v-if="scope.row.status=='qy'">上架</el-tag>
                  <el-tag type="info" v-if="scope.row.status=='jy'">下架</el-tag>
                  <!--            <dict-tag :options="dict.type.zhzt" :value="scope.row.status"/>-->
                </template>
              </el-table-column>
              <el-table-column label="创建时间" align="center" width="160" prop="createTime"/>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column type="index" width="80" align="center" label="序号"/>
        <el-table-column label="品类名称" align="center" prop="name"/>
        <el-table-column label="商品编号" align="center" prop="code"/>
        <el-table-column label="排序" align="center" prop="sorted" />
        <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" prop="createTime">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建人" align="center" prop="createBy">
          <template slot-scope="scope">
            <span>{{ getName(scope.row.createBy) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="300" fixed='right'>
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-plus"
              @click="addGoods(scope.row)"
            >添加商品信息</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
            >修改品类信息</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @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 :title="title" :visible.sync="open" class="roll-dialog"
               :close-on-click-modal="false" append-to-body width="500px">
        <el-form :model="form" :inline="true" :rules="rules" ref="form" >
<!--            <el-form-item label="上级品类" >-->
<!--                <el-select v-model="form.pid" placeholder="请选择上级品类">-->
<!--                  <el-option label="无上级" :value="0">无上级</el-option>-->
<!--                  <el-option-->
<!--                    v-for="item in goodsOptions"-->
<!--                    :label="item.name"-->
<!--                    :value="item.id">-->
<!--                  </el-option>-->
<!--                </el-select>-->
<!--            </el-form-item>-->
            <el-form-item label="品类名称" prop="name" style="margin-left: -8px;">
                <el-input v-model="form.name" style="width: 300px;"></el-input>
            </el-form-item>
            <el-form-item label="排序规则">
                <el-input-number v-model="form.sorted" @change="handleChange" :min="0" :max="10" style="width: 300px;"></el-input-number>
            </el-form-item>
            <el-form-item >
                <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-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改对话框 -->
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="openGoods" append-to-body>
      <el-form ref="form1" :model="form1" :rules="rules1" label-width="90px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="商品条码" prop="goodsNo">
              <el-input v-model="form1.goodsNo"
                        @keydown.enter.native="getGoods(form1)"
                        :disabled="title == '编辑商品'"

                        clearable
                        placeholder="商品的条码信息">
                <el-button slot="append" @click="getGoods(form1)">查询</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="form1.name" @input="pinyin" placeholder="请输入商品名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属分类" prop="cvsGoodId">
              <el-select
                v-model="form1.cvsGoodId"
                placeholder="全部"
                clearable
                style="width: 300px"
              >
                <el-option v-for="item in goodsOptions" :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="pinyinCode">
              <el-input v-model="form1.pinyinCode" placeholder="输入商品名称自动回填"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="单位" prop="unit">
              <el-input v-model="form1.unit" placeholder="如：个、瓶、包"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="货架号" prop="shelfNumber">
              <el-input v-model="form1.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="form1.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-row>-->
        <el-row>
          <el-col :span="24">
            <el-form-item label="供应商" prop="supplierId">
              <el-select
                v-model="form1.supplierId"
                filterable
                placeholder="请选择供应商"
                clearable
                style="width: 80%">
                <el-option v-for="item in supplierList" :key="item.id" :label="item.name" :value="item.id"/>
              </el-select>
              <el-button type="info" plain @click="handleAdd1">添加供应商</el-button>
<!--              <el-autocomplete-->
<!--                popper-class="my-autocomplete"-->
<!--                style="width: 94%"-->
<!--                v-model="supplier"-->
<!--                :fetch-suggestions="querySearch"-->
<!--                placeholder="供应商名称，如果是未添加的供应商，输完名称点回车即可自动添加"-->
<!--                @change="addSupplier"-->
<!--                @select="selectSupplier">-->
<!--                <template slot-scope="{ item }">-->
<!--                  <div style="display: flex;justify-content: space-between">-->
<!--                    <span class="name">{{ item.name }}</span>-->
<!--                    &lt;!&ndash;                    <span class="addr">{{ item.memberPrice }}</span>&ndash;&gt;-->
<!--                  </div>-->
<!--                </template>-->
<!--              </el-autocomplete>-->
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="排序" prop="sort">
              <el-input-number v-model="form1.sort" :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="form1.status" disabled="">
<!--                <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>
          </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="submitForm1">确 定</el-button>
        <el-button @click="cancel1">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :close-on-click-modal="false" :title="title" width="600px" style="margin-top: 5%" :visible.sync="open2" append-to-body>
      <el-form ref="form2" :model="form2" :rules="rules2" label-width="90px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="供应商" prop="name" style="width: 420px">
              <el-input v-model="form2.name" placeholder="请输入供应商名称" maxlength="30" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系人" prop="contacts">
              <el-input v-model="form2.contacts" placeholder="供应商联系人" maxlength="30"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="mobile">
              <el-input v-model="form2.mobile" placeholder="供应商联系电话" maxlength="30"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="联系地址" prop="address">
              <el-input v-model="form2.address" placeholder="供应商联系地址" maxlength="30" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form2.remark" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm2">确 定</el-button>
        <el-button @click="open2 = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  selectTree,
  list,
  insertCvsGoods,
  deleteBYId,
  selectParentById,
  updateCevGood
} from "@/api/convenienceStore/goods.js";
import {getAccount} from "@/api/system/account";
import {addLJGoods, createGoodsNo, queryGoodsVoList, queryLJGoods, scanCode} from "@/api/convenienceStore/ljgoods";
import pinyin from "js-pinyin";
import {getSysConfig} from "@/api/staff/user/sysconfig";
import {addSupplier, listSuppliers, updateSupplier} from "@/api/convenienceStore/supplier";
export default {
  dicts:['zhzt','yes_or_no'],
  data() {
      return {
        creatName:'',
        // 标题
        title: "",
        // 是否显示弹出层
        open: false,
        open2: false,
        openGoods: false,
        // 遮罩层
        loading: true,
        supplier: "",
        // 总条数
        total: 0,
        // 表格数据
        list: [],
        goodsList: [],
        stockType: [],
        //是否修改一二级菜单
        isShow:false,
        // 默认排序
        defaultSort: {prop: 'updateTime', order: 'descending'},
        //编辑表单
        editForm:{
          pid:'',
          name:'',
          status:'qy',
          sorted:0,
        },
        //父级菜单列表
        goodsOptions:[],
        //查询表单
        goodsQueryForm: {
          name: '',
          status: '',
          pid:"",
          pageNum:'1',
          pageSize:'5'
        },
        // 添加对话框
        dialogFormVisible:false,
        //修改对话框
        editDialogFormVisible:false,
        //对话框表单
        form:{
          pid:'',
          name:'',
          status:'qy',
          sorted:0,
        },
        //对话框表单
        form1:{
          status:'jy',
          canUsePoint:'no',
          stock:0,
          sort:0,
          buyingPrice:0,retailPrice:0,memberPrice:0
        },
        form2:{},
        tableData: [{
          id: '',
          pid:'',
          name: '',
          sorted: '',
          status:'',
          createdTime:'',
          children: []
        }],
        // 查询参数
        queryParams: {
          page: 1,
          pageSize: 10,
          name:'',
          status: '',
        },
        aa:[],
        supplierList:[],
        //校验规则
        rules: {
          name: [
            { required: true, message: '请输入品类名称', trigger: 'blur' },
          ],
        },
        //校验规则
        rules1: {
          goodsNo: [
            { required: true, message: "商品条码不能为空", trigger: "blur" },
          ],
          name: [
            { required: true, message: "商品名称不能为空", trigger: "blur" },
          ],
          cvsGoodId: [
            { 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: "change" },
          ],
          status: [
            { required: true, message: "请选择商品状态", trigger: "blur" },
          ],
        },

        // 表单校验
        rules2: {
          name: [
            { required: true, message: "供应商名称不能为空", trigger: "blur" },
          ],
        }

      };
  },
  created(){
    this.getList();
    this.getFirstMenu();
    this.getType();
    this.getSuppilers();
  },
  methods: {
    // 提交按钮
    submitForm2: function() {
      this.$refs["form2"].validate(valid => {
        if (valid) {
          if (!this.form2.id) {
            addSupplier(this.form2).then(response => {
              if (response.data==1){
                this.$modal.msgSuccess("供应商新增成功");
                this.open2 = false;
                this.getSuppilers();
              }else {
                this.$modal.msgError("供应商名称已存在");
              }
            });
          }
        }
      });
    },
    // 新增按钮操作
    handleAdd1() {
      this.reset2();
      this.open2 = true;
      this.title = "新增供应商";
    },
    // 表单重置
    reset2() {
      this.resetForm("form2");
      this.form2= {}
    },
    getSuppilers(val){
      listSuppliers({ifDelete:'0'}).then(response => {
        this.supplierList = response.data
        if (val){
          this.supplierList.forEach(item => {
            if (item.name == val){
              this.form1.supplierId = item.id
            }
          })
        }
      })
    },
    // 获取分类名称
    getType(){
      getSysConfig('stock_type').then(response => {
        this.stockType = response.data.split(";")
      });
    },
    // 扫描识别商品信息
    getGoods(form1){
      if (form1.goodsNo!=""){
        scanCode(form1.goodsNo).then(response => {
          if (response.data!=null && response.data!=""){
            this.form1.goodsNo = response.data.barcode;
            this.form1.name = response.data.goodsName;
            this.pinyin();
            this.$forceUpdate()
          }
        })
      }
    },
    // 生成13位数字条码信息
    createGoodNo(){
      createGoodsNo().then(response => {
        this.form1.goodsNo = response.data
        this.$forceUpdate()
      })
    },
    // 获取中文首字母拼音
    pinyin(){
      let pinyin = require("js-pinyin");
      pinyin.setOptions({ checkPolyphone: false, charCase: 1 });
      this.form1.pinyinCode = pinyin.getCamelChars(this.form1.name)
    },
    // 模糊查询商品信息
    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.form1.supplierId = data.id
      this.$set(this.form1,'supplierId',data.id)
      // this.$forceUpdate()
    },
    addSupplier(val){
      if (!val){
        return;
      }
      addSupplier({name:val,remark:"添加商品自动添加",ifDelete:'0'}).then(async res => {
        if (res.data == 1) {
          this.supplier = val;
          this.$modal.msgSuccess("已为您自动添加此供应商")
          await this.getSuppilers(val)
        }
      })
    },
    // 提交按钮
    submitForm1: function() {
      this.$refs["form1"].validate(valid => {
        if (valid) {
          if (this.form1) {
            queryLJGoods({goodsNo: this.form1.goodsNo}).then(response => {
              if (response.data != null) {
                this.$modal.msgError("商品已存在");
              } else {
                addLJGoods(this.form1).then(response => {
                  if (response.data == 1) {
                    this.$modal.msgSuccess("商品信息新增成功");
                    this.openGoods = false;
                    this.getList();
                  } else {
                    this.$message.error("商品信息新增失败")
                  }

                });
              }
            })
          }

        }
      });
    },
    // 取消按钮
    cancel1() {
      this.openGoods = false;
      this.reset1();
    },
    // 表单重置
    reset1() {
      this.form1 = {
        status:'jy',
        canUsePoint:'no',
        stock:0,
        sort:0,
      }
    },
    // 表单重置
    reset() {
      this.form = {
        pid:'',
        name:'',
        status:'qy',
        sorted:0,
      }
    },
    // 获取添加者姓名
    getName(id){
      getAccount(id).then(response=>{
        this.creatName = response.data.account.realName
      })
      return this.creatName;
    },
    // 新增按钮操作
    handleAdd() {
      this.reset()
      this.open = true;
      this.title = "新增品类";
    },
    //获取父类
    getFirstMenu(){
        list(this.form).then(response=>{
            this.goodsOptions = response.data
        })
    },
    // 搜索按钮操作
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    handleChange(){
    },
    //提交商品类别
    dooSubmit(){
        this.$refs['form'].validate(valid => {
            if (valid) {
                //新增一级品类
                if(this.form.pid == '' || this.form.pid == undefined ){
                    this.form.pid = 0
                }
                //新增二级
                insertCvsGoods(this.form).then(response=>{
                    if (response.code === 200) {
                       this.rest()
                        this.$message('新增成功');
                    }else{
                        this.$message('新增失败 请联系管理员');
                    }

                })


            }
        })
    },
    rest(){
        this.dialogFormVisible = false
        this.resetForm();
        this.goodsOptions = []
    },
    // 取消提交
    cancelSubmit(){
        this.$refs.form.resetFields();//清空
        this.form.name = ''
        this.form.pid = ''
        this.form.status = ''
        this.form.sorted = 0
        this.dialogFormVisible = false
    },
    // 分页查询
    getList(){
      this.loading = true;
      selectTree(this.queryParams).then(response => {
        if (response.data!=null){
          this.list = response.data.records;
          this.total = response.data.total;
        }else {
          this.list = [];
          this.total = 0;
        }
        this.loading = false;
      });
    },
    onExpand(row){
// 判断当前展开行
        // debugger
        // this.getGoodsList(row.id)  // 获取列表
    },
    getGoodsList(cvsGoodsId){
      queryGoodsVoList({cvsGoodId:cvsGoodsId}).then(res => {
        this.goodsList = res.data
      })
    },
    // 取消查询
    resetForm(){
        this.goodsQueryForm.name = ''
        this.goodsQueryForm.status = ''
        this.getList()
    },
    // 提交按钮
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if(this.form.pid==""){
            this.form.pid = 0
          }
          if (this.form.id) {
            updateCevGood(this.form).then(response => {
              if (response.data==1){
                this.$modal.msgSuccess("品类更新成功");
                this.open = false;
                this.getList();
                this.getFirstMenu();
              }else {
                this.$modal.msgError("品类名称已存在，修改失败");
              }

            });
          } else {
            insertCvsGoods(this.form).then(response => {
              if (response.data == -1){
                this.$modal.msgError("品类名称已存在，添加失败");
              }else {
                this.$modal.msgSuccess("品类添加成功");
                this.open = false;
                this.getList();
                this.getFirstMenu();
              }
            });
          }
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 添加商品信息
    addGoods(data){
      this.openGoods = true
      this.form1 = {status:'jy', canUsePoint:'no', stock:0, sort:0, buyingPrice:0, retailPrice:0, memberPrice:0, cvsGoodId:data.id}
      // this.form1.cvsGoodId = data.id
      this.supplier = ""
      this.title = "添加商品信息"
    },
    // 修改按钮操作
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      selectParentById(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 deleteMember(row.id);
        return deleteBYId(row.id);
      }).then(() => {
        this.queryParams.page = 1
        this.getList();
        this.getFirstMenu();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    // 多选框选中数据
    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>
  .tTop{
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
  }
  .pageSty{
    display: flex;
    justify-content: center;
    margin-left: 250px;
  }
  .app-container{
    width: 100%;
    height: 100%;
    background: #f6f8f9;
  }
</style>
