<template>
  <div class="app-container" ref="appPanel">
    <div ref="toolPanel" class="toolPanel">
      <el-row :gutter="10">
        <el-col :span="1.5">
          <div class="toolTitle">物料管理</div>
        </el-col>
        <el-col :span="1.5">
          <el-button
            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
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:goods:edit']"
            >修改</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:goods:remove']"
            >删除</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="info"
            plain
            icon="el-icon-upload2"
            size="mini"
            @click="handleImport"
            v-hasPermi="['system:goods:import']"
          >导入</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['system:goods:export']"
            >导出</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button icon="el-icon-search" size="mini" @click="handleQuery"
            >搜索</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >刷新</el-button
          >
        </el-col>
        <right-toolbar ref="toolBarRef" @customCols="customColsHandler" :showSearch.sync="showSearch"
                       showColumnsType="transfer" :columns="columns"></right-toolbar>
      </el-row>
    </div>
    <div class="search-container" ref="searchPanel">
      <el-form
        :model="queryParams"
        ref="queryForm"
        size="mini"
        :inline="true"
        v-show="showSearch"
        label-width="68px"
      >
        <el-form-item label="物料编号" prop="goodsId">
          <el-input
            v-model="queryParams.goodsId"
            placeholder="请输入物料编号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <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="goodsShortName">
          <el-input
            v-model="queryParams.goodsShortName"
            placeholder="请输入物料简称"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>-->
<!--        <el-form-item label="类别" prop="goodsTypeId">
          <el-input
            v-model="queryParams.goodsTypeId"
            placeholder="请输入类别"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>-->
        <el-form-item label="规格" prop="specification">
          <el-input
            v-model="queryParams.specification"
            placeholder="请输入规格"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <!-- <el-form-item label="型号" prop="model">
          <el-input
            v-model="queryParams.model"
            placeholder="请输入型号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item> -->
        <el-form-item label="物料描述" prop="recoil">
          <el-input
            v-model="queryParams.recoil"
            placeholder="请输入物料描述"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>

        <!-- <el-form-item label="供应商编号" prop="providerId">
          <el-input
            v-model="queryParams.providerId"
            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
              v-for="dict in dict.type.common_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item> -->

        <!-- <treeselect v-model="queryParams.goodsTypeId" :options="financialClassList" :normalizer="normalizer" placeholder="请选择分类" /> -->
        <!-- </el-form-item> -->
      </el-form>
    </div>

    <div class="table-container">
      <div ref="mainTablePanel" :style="{ height: mainTableDivHeight }">
        <el-table :key="rndKey" ref="providerTableRef" v-loading="loading" border size="mini" :height="mainTableHeight"
                  :data="goodsList" @selection-change="handleSelectionChange" @header-dragend="handleHeaderDragEnd">
          <el-table-column type="selection" width="55" align="center" />
          <template>
            <el-table-column v-for="item in columns" :key="item.key" :label="item.label" align="center"
                             :prop="item.columnName" v-if="item.visible" :width="item.width" />
          </template>
        </el-table>
        <div class="pagePanel">
          <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
                      :limit.sync="queryParams.pageSize" @pagination="getList" />
        </div>
      </div>
    </div>

    <!-- 添加或修改物料对话框 -->
    <el-dialog
      id="dialog-container"
      :title="title"
      :visible.sync="open"
      width="1000px"
      append-to-body
    >
      <div class="edit-container">
        <el-form ref="form" :model="form" :rules="rules" label-width="85px">
          <el-row>
            <el-col :span="6">
              <el-form-item label="物料编号" prop="goodsId">
                <el-input v-model="form.goodsId" placeholder="请输入物料编号" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="物料名称" prop="goodsName">
                <el-input
                  v-model="form.goodsName"
                  placeholder="请输入物料名称"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="规格" prop="specification">
                <el-input
                  v-model="form.specification"
                  placeholder="请输入规格"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="物料描述" prop="recoil">
                <el-input v-model="form.recoil" placeholder="请输入物料描述" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="物料单位" prop="unit">
                <el-select v-model="form.unit" placeholder="请选择物料单位">
                  <el-option
                    v-for="dict in dict.type.goods_unit"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="计划单价" prop="price">
                <el-input v-model="form.price" placeholder="请输入计划单价" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="库存上限" prop="warnUp">
                <el-input v-model="form.warnUp" placeholder="请输入库存上限" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="库存下限" prop="warnDown">
                <el-input
                  v-model="form.warnDown"
                  placeholder="请输入库存下限"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="ABC分类" prop="abc">
                <el-input v-model="form.abc" placeholder="请输入ABC分类" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="保质期" prop="period">
                <el-input v-model="form.period" placeholder="请输入保质期" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="保质期单位" prop="periodUnit">
                <el-select
                  v-model="form.periodUnit"
                  placeholder="请选择保质期单位"
                >
                  <el-option
                    v-for="dict in dict.type.shelf_life_unit"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="所属仓库" prop="storageId">
                <el-input
                  v-model="form.storageId"
                  placeholder="请输入所属仓库"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="备注" prop="remark">
                <el-input
                  v-model="form.remark"
                  type="textarea"
                  placeholder="请输入内容"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <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="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" />
            是否更新已经存在的物料数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate"
          >下载模板</el-link
          >
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCOLUMN } from "@/api/system/column";
import { listFinancialClass } from "@/api/system/financialClass";
import {
  addGoods,
  changeStatus,
  delGoods,
  disabled,
  enabled,
  getGoods,
  listGoods,
  updateGoods,
} from "@/api/system/goods";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { getToken } from "@/utils/auth";
export default {
  name: "Goods",
  components: { Treeselect },

  dicts: [
    "sys_yes_no",
    "common_status",
    "goods_unit",
    "goods_type",
    "shelf_life_unit",
  ],
  data() {
    return {
      rndKey:0,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 物料表格数据
      goodsList: [],
      // 财务分类树选项
      financialClassList: [],
      // 弹出层标题
      title: "",
      mainTableHeight: "0px",
      mainTableDivHeight: "0px",
      businessCodeTrk: "goods",
      rightToolbarShow: false,
      tableNo: 0,
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 100,
        goodsId: null,
        goodsName: null,
        goodsShortName: null,
        pyName: null,
        barcode: null,
        goodsTypeId: null,
        specification: null,
        model: null,
        recoil: null,
        gvolume: null,
        warnUp: null,
        warnDown: null,
        produceArea: null,
        grossWeight: null,
        netWeight: null,
        providerId: null,
        hsnumber: null,
        abc: null,
        hazardous: null,
        storageConditions: null,
        addtax: null,
        season: null,
        tariffrate: null,
        status: null,
        scFlag: null,
        customerId: null,
        isOpen: null,
        defaultStorageAreaId: null,
        materialCharacteristics: null,
        defaultStorageId: null,
        storageId: null,
        reinspectionDays: null,
        selectIds:[]
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        goodsId: [
          { required: true, message: "物料编号不能为空", trigger: "blur" },
        ],
        goodsName: [
          { required: true, message: "物料名称不能为空", trigger: "blur" },
        ],
        specification: [
          { required: true, message: "规格不能为空", trigger: "blur" },
        ],
        unit: [
          { required: true, message: "物料单位不能为空", trigger: "blur" },
        ],
      },
      columns: [],
      // 物料导入参数
      upload: {
        // 是否显示弹出层（物料导入）
        open: false,
        // 弹出层标题（物料导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的物料数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/goods/importData",
      },
    };
  },
  created() {
    this.getList();
    // this.getFinancialClassList();
  },
  mounted() {
    this.computedTableHeight();
  },
  watch: {
    showSearch: function () {
      this.computedTableHeight();
    },
  },
  methods: {

    /** 查询财务分类下拉树结构 */
    getFinancialClassList() {
      listFinancialClass(this.queryParams).then((response) => {
        this.financialClassList = this.handleTree(response.data, "id");
      });
    },
    /** 转换财务分类数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.materialClassName,
        children: node.children,
      };
    },
    /** 查询用户展示字段定义管理列表 */

    computedTableHeight() {
      this.$nextTick(() => {
        var totalHeight = this.$refs.appPanel.clientHeight;
        var toolHeight = this.$refs.toolPanel.clientHeight;
        var searchHeight = this.$refs.searchPanel.clientHeight;
        var tablePanelHeight = totalHeight - toolHeight - searchHeight - 14 - 5;
        this.mainTableDivHeight = tablePanelHeight + "px";
        this.mainTableHeight = tablePanelHeight - 25 + "px";
      });
    },
    /** 查询物料列表 */
    getList() {
      this.loading = true;
      listGoods(this.queryParams).then((response) => {
        this.goodsList = response.rows;
        this.total = response.total;
        if (this.columns.length == 0) this.columns = response.columns;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        goodsId: null,
        goodsName: null,
        goodsShortName: null,
        pyName: null,
        barcode: null,
        goodsTypeId: null,
        specification: null,
        model: null,
        price: null,
        glength: null,
        gwidth: null,
        gheight: null,
        recoil: null,
        gvolume: null,
        scaleUnit: null,
        unit: null,
        warnUp: null,
        warnDown: null,
        produceArea: null,
        grossWeight: null,
        netWeight: null,
        providerId: null,
        hsnumber: null,
        abc: null,
        hazardous: null,
        storageConditions: null,
        period: null,
        periodUnit: null,
        addtax: null,
        season: null,
        tariffrate: null,
        remark: null,
        status: null,
        version: null,
        img: null,
        createBy: null,
        createDate: null,
        updateDate: null,
        scFlag: null,
        costPrice: null,
        customerId: null,
        isOpen: null,
        defaultStorageAreaId: null,
        updateBy: null,
        materialCharacteristics: null,
        recheckDays: null,
        defaultStorageId: null,
        storageId: null,
        reinspectionDays: null,
        isSampling: null,
        isCheck: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
      this.queryParams.selectIds=this.ids;
    },
    /** 新增按钮操作 */
    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 = "修改物料";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        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(() => {
        });
    },

    /** 用户状态修改 */
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$modal
        .confirm('确认要"' + text + '"id为"' + row.id + '"数据项？')
        .then(function () {
          return changeStatus(row.id, row.status);
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.status = row.status === "0" ? "1" : "0";
        });
    },
    /** 启用按钮操作 */
    handleEnable(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认启用物料编号为"' + ids + '"的数据项？')
        .then(function () {
          return enabled(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("启用成功");
        })
        .catch(() => {
        });
    },
    /** 禁用按钮操作 */
    handleDisabled(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认禁用物料编号为"' + ids + '"的数据项？')
        .then(function () {
          return disabled(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("禁用成功");
        })
        .catch(() => {
        });
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/goods/export",
        {
          ...this.queryParams,
        },
        `goods_${new Date().getTime()}.xlsx`
      );
    },

    customColsHandler(columns) {
      this.columns = columns;
      this.rndKey = Math.random();
    },

    handleHeaderDragEnd(newWidth, oldWidth, column, event) {
      debugger
      // 当列宽发生变化时，将变化值写入到columns变量中。
      this.columns.map((obj) => {
        if (obj.columnName == column.property) obj.width = newWidth;
      });
      console.log(this.columns)
      this.$refs.toolBarRef.saveConfig(this.columns);
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "物料导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "system/goods/importTemplate",
        {},
        `goods_template_${new Date().getTime()}.xlsx`
      );
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
        response.msg +
        "</div>",
        "导入结果",
        { dangerouslyHTMLString: true }
      );
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },

  }
};
</script>
<style scoped>
.app-container {
  height: calc(100vh - 84px);
}
</style>
