<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="物品名称" prop="goodsName">
        <el-input
          v-model="queryParams.goodsName"
          placeholder="请输入物品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="入库年限" prop="upTime">
        <el-date-picker clearable
          v-model="queryParams.queryUpTime"
          type="daterange"
          value-format="yyyy-MM-dd"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>


      <el-form-item label="所属仓库" prop="kufangId">
        <el-select v-model="queryParams.kufangId" placeholder="请选择所属仓库" style="width: 100%">
          <el-option
            v-for="item in kfSelect"
            :label="item.kfName"
            :value="item.id">
          </el-option>
        </el-select>

      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:goods:add']"
        >新增</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:goods:remove']"
        >删除</el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="goodsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index" />
      <el-table-column label="物品名称" align="center" prop="goodsName" />
      <el-table-column label="型号规格" align="center" prop="goodsType" />
      <el-table-column label="单位" align="center" prop="goodsUnit" />
      <el-table-column label="装备数量" align="center" prop="goodsNum" />
      <el-table-column label="入库年限" align="center" prop="upTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.upTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="存储年限" align="center" prop="saveYear" />
      <el-table-column label="报废数量" align="center" prop="scrapNum" />
      <el-table-column label="剩余数量" align="center" prop="leaveNum" />
      <el-table-column label="盘库时间" align="center" prop="makeTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.makeTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属仓库" align="center" prop="kufangId" >
        <template slot-scope="scope">
          <p>{{ kfMap[scope.row.kufangId] }}</p>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleQrCode(scope.row)"
          >二维码</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:goods:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:goods:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 添加或修改物品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="goodsForm" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="物品名称" prop="goodsName">
          <el-input v-model="form.goodsName" placeholder="请输入物品名称" />
        </el-form-item>
        <el-form-item label="型号/规格" prop="goodsType">
          <el-input v-model="form.goodsType" placeholder="请输入型号/规格" />
        </el-form-item>
        <el-form-item label="单位" prop="goodsUnit">
          <el-input v-model="form.goodsUnit" placeholder="请输入单位" />
        </el-form-item>
        <el-form-item label="装备数量" prop="goodsNum">
          <el-input v-model="form.goodsNum" placeholder="请输入装备数量" type="number" min="0" />
        </el-form-item>
        <el-form-item label="入库年限" prop="upTime">
          <el-date-picker clearable
            v-model="form.upTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择入库年限" style="width: 100%">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="存储年限" prop="saveYear">
          <el-input v-model="form.saveYear" placeholder="请输入存储年限" type="number" min="1" />
        </el-form-item>
        <el-form-item label="报废数量" prop="scrapNum">
          <el-input v-model="form.scrapNum" placeholder="请输入报废数量" type="number" min="0" />
        </el-form-item>
        <el-form-item label="剩余数量" prop="leaveNum">
          <el-input v-model="form.leaveNum" placeholder="请输入剩余数量" type="number" min="0" />
        </el-form-item>
        <el-form-item label="盘库时间" prop="makeTime">
          <el-date-picker clearable
            v-model="form.makeTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择盘库时间" style="width: 100%">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="所属仓库" prop="kufangId">
          <el-select v-model="form.kufangId" placeholder="请选择所属仓库" style="width: 100%">
            <el-option
              v-for="item in kfSelect"
              :label="item.kfName"
              :value="item.id">
            </el-option>
          </el-select>
        </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 title="二维码" :visible.sync="codeOpen" width="500px" append-to-body>
      <div id="qrcode" ref="qrcode" style="display: flex;justify-content: center;"></div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="codeCancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import QRCode from 'qrcodejs2';
import {listGoods, getGoods, delGoods, addGoods, updateGoods, getKuFangList} from "@/api/system/goods";

export default {
  name: "Goods",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 物品表格数据
      goodsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      codeOpen: false,
      qrcode: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        goodsName: null,
        queryUpTime: null,
        kufangId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        goodsName: [
          { required: true, message: "物品名称不能为空", trigger: "blur" }
        ],
        goodsNum: [
          { validator: (rule, value, callback) => {
              if (value < 0) {
                callback(new Error('请输入正整数'));
              } else if (value > 0) {
                if (!/^\d+$/.test(value)) {
                  callback(new Error('请输入正整数'));
                }
              }
              callback()
            }, trigger: "blur" }
        ],
        upTime: [
          { required: true, message: "请选择入库年限", trigger: "blur" }
        ],
        saveYear: [
          { validator: (rule, value, callback) => {
              if (value <= 0) {
                callback(new Error('请输入大于0的数'));
              } else if (value > 0) {
                if (!/^\d+$/.test(value)) {
                  callback(new Error('请输入整数'));
                }
              }
              callback()
            }, trigger: "blur" }
        ],
        scrapNum: [
          { validator: (rule, value, callback) => {
              if (value < 0) {
                callback(new Error('请输入正整数'));
              } else if (value > 0) {
                if (!/^\d+$/.test(value)) {
                  callback(new Error('请输入正整数'));
                }
              }
              callback()
            }, trigger: "blur" }
        ],
        leaveNum: [
          { validator: (rule, value, callback) => {
              if (value < 0) {
                callback(new Error('请输入正整数'));
              } else if (value > 0) {
                if (!/^\d+$/.test(value)) {
                  callback(new Error('请输入正整数'));
                }
              }
              callback()
            }, trigger: "blur" }
        ],
        makeTime: [
          { required: true, message: "请选择入库年限", trigger: "blur" }
        ],
      },
      kfSelect: [],
      kfMap: {}
    };
  },
  created() {
    getKuFangList().then(json => {
      this.kfSelect = json.data || []
      if (json.data && json.data.length) {
        for (let i = 0; i < json.data.length; i++) {
          this.kfMap[json.data[i].id] = json.data[i].kfName
        }
      }
      this.getList();
    })
  },
  methods: {
    /** 查询物品列表 */
    getList() {
      this.loading = true;
      if (this.queryParams.queryUpTime && this.queryParams.queryUpTime[0]) {
        this.queryParams.startTime = this.queryParams.queryUpTime[0]
        this.queryParams.endTime = this.queryParams.queryUpTime[1]
      }
      listGoods(this.queryParams).then(response => {
        this.goodsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    codeCancel() {
      this.codeOpen = false;
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        goodsName: null,
        goodsType: null,
        goodsUnit: null,
        goodsNum: null,
        upTime: null,
        saveYear: null,
        scrapNum: null,
        leaveNum: null,
        makeTime: null,
        remark: null,
        kufangId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("goodsForm");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.queryUpTime = null
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加物品";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getGoods(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改物品";
      });
    },
    handleQrCode(row) {
      this.codeOpen = true
      setTimeout(function () {
        if (document.getElementById('qrcode')) {
          document.getElementById('qrcode').innerHTML = ''; //防止重复生成二维码
          // this.$nextTick(function () {
            new QRCode(document.getElementById('qrcode'), {
              width: 256,
              height: 256,
              text: process.env.VUE_APP_BASE_API + '/page/goods/detail.html?id=' + row.id,
              colorDark: '#333333', // 二维码颜色
              colorLight: '#ffffff', // 二维码背景色
              correctLevel: QRCode.CorrectLevel.L,
            })
          // })
        }
      }, 100)



    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["goodsForm"].validate(valid => {
        console.log(this.form)


        if (valid) {
          if (this.form.id != null) {
            updateGoods(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addGoods(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除物品编号为"' + ids + '"的数据项？').then(function() {
        return delGoods(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/goods/export', {
        ...this.queryParams
      }, `goods_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
