<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
<!--      <el-form-item label="分类名称" prop="materialTypeName">-->
<!--        <el-input-->
<!--          v-model="queryParams.materialTypeName"-->
<!--          placeholder="请输入物资分类名称"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="供应商名称" prop="vendorName">
        <el-input
          v-model="queryParams.vendorName"
          placeholder="请输入供应商名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物资编码" prop="materialCode">
        <el-input
          v-model="queryParams.materialCode"
          placeholder="请输入物资编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物资名称" prop="materialName">
        <el-input
          v-model="queryParams.materialName"
          placeholder="请输入物资名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物资规格" prop="materialSpecifications">
        <el-input
          v-model="queryParams.materialSpecifications"
          placeholder="请输入物资规格"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否启用" prop="isEnable">
        <el-select v-model="queryParams.isEnable" placeholder="是否启用" clearable>
          <el-option
            v-for="dict in dict.type.sys_is_enable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否盘点" prop="isCheck">
        <el-select v-model="queryParams.isCheck" placeholder="是否盘点" clearable>
          <el-option
            v-for="dict in dict.type.sys_is_enable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否通用" prop="isUniversal">
        <el-select v-model="queryParams.isUniversal" placeholder="是否通用" clearable>
          <el-option
            v-for="dict in dict.type.sys_is_enable"
            :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" 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="['business:material:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:material:edit']"
        >修改</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="['business:material:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['business:material:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['business:material:import']"
        >导入</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="materialList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" fixed="left" align="center" />
      <el-table-column label="物资编码" align="center" fixed="left" prop="materialCode" />
      <el-table-column label="物资名称" align="center" fixed="left" prop="materialName" />
      <el-table-column label="物资规格" align="center" fixed="left" prop="materialSpecifications" />
      <el-table-column label="物资品牌" align="center" fixed="left" prop="materialBrand" />
      <el-table-column label="物资单位" align="center" fixed="left" prop="materialUnit">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.material_unit" :value="scope.row.materialUnit" />
        </template>
      </el-table-column>
<!--      <el-table-column label="所在仓库" align="center" prop="warehouseName" />-->
<!--      <el-table-column label="分类名称" align="center" prop="materialTypeName" />-->
      <el-table-column label="供应商" align="center" prop="vendorName" show-overflow-tooltip />
      <el-table-column label="采购标的" align="center" prop="procurementSubject" />
      <el-table-column label="适用车型" align="center" prop="compatibleWith" />
      <el-table-column label="物资图片" align="center" prop="materialUrl">
        <template slot-scope="scope">
          <image-preview :src="scope.row.materialUrl" style="width: 50px; height: 50px" />
        </template>
      </el-table-column>
      <el-table-column label="质保期(月)" align="center" prop="materialWarrantyPeriod" />
      <el-table-column label="参考价" align="center" prop="referencePrice" />
      <el-table-column label="销售价" align="center" prop="sellingPrice" />
<!--      <el-table-column label="库存" align="center" prop="inventory" />-->
      <el-table-column label="是否启用" align="center" prop="isEnable">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_is_enable" :value="scope.row.isEnable"/>
        </template>
      </el-table-column>
<!--      <el-table-column label="盘点中" align="center" prop="isCheck">-->
<!--        <template slot-scope="scope">-->
<!--          <dict-tag :options="dict.type.sys_is_enable" :value="String(scope.row.isCheck)"/>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column label="是否通用" align="center" prop="isUniversal">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_is_enable" :value="scope.row.isUniversal"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="120px" fixed="right" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:material:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:material: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="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="物资编码" prop="materialCode">
              <el-input v-model="form.materialCode" placeholder="请输入物资编码" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="物资名称" prop="materialName">
              <el-input v-model="form.materialName" placeholder="请输入物资名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="物资规格" prop="materialSpecifications">
              <el-input v-model="form.materialSpecifications" placeholder="请输入物资规格" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
<!--          <el-col :span="8">-->
<!--            <el-form-item label="仓库" prop="warehouseId">-->
<!--              <el-select v-model="form.warehouseId" filterable placeHolder="请选择仓库">-->
<!--                <el-option v-for="item in warehouseList" :key="item.id" :value="item.id" :label="item.name" />-->
<!--              </el-select>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="8">-->
<!--            <el-form-item label="物资分类" prop="materialTypeId">-->
<!--              <treeselect v-model="form.materialTypeId" :options="materialTypeList" :show-count="true" @select="materialTypeIdChange" :normalizer="normalizer" placeholder="请选择" />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
          <el-col :span="8">
            <el-form-item label="供应商" prop="vendorId">
              <el-select v-model="form.vendorId" placeHolder="请选择供应商">
                <el-option v-for="item in materialVendorList" :key="item.id" :value="item.id" :label="item.vendorName" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="物资单位" prop="materialUnit">
              <el-select v-model="form.materialUnit" placeHolder="请选择物资单位">
                <el-option v-for="dict in dict.type.material_unit" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="质保期(月)" prop="materialWarrantyPeriod">
              <el-input-number v-model="form.materialWarrantyPeriod" :min="1" style="width: 100%" placeholder="请输入质保期" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="参考价" prop="referencePrice">
              <el-input-number v-model="form.referencePrice" :min="0" style="width: 100%" placeholder="请输入参考价" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="销售价" prop="sellingPrice">
              <el-input-number v-model="form.sellingPrice" :min="0" style="width: 100%" placeholder="请输入销售价" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="适用车型" prop="compatibleWith">
              <el-input v-model="form.compatibleWith" placeholder="请输入适用车型" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
<!--          <el-col :span="8">-->
<!--            <el-form-item label="仓库货位" prop="warehouseLocationId">-->
<!--              <el-select v-model="form.warehouseLocationId" placeHolder="请选择仓库货位">-->
<!--                <el-option v-for="item in warehouseLocationList" :key="item.id" :value="item.id" :label="item.locationType" />-->
<!--              </el-select>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
          <el-col :span="8">
            <el-form-item label="是否启用" prop="isEnable">
              <el-select v-model="form.isEnable" style="width: 100%" placeholder="请选择是否启用">
                <el-option v-for="dict in dict.type.sys_is_enable" :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="物资品牌" prop="materialBrand">
              <el-input v-model="form.materialBrand" placeholder="请输入物资品牌" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="采购标的" prop="procurementSubject">
              <el-input v-model="form.procurementSubject" placeholder="请输入采购标的" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
<!--          <el-col :span="8">-->
<!--            <el-form-item label="库存数量" prop="inventory">-->
<!--              <el-input-number v-model="form.inventory" :min="0" style="width: 100%" :disabled="form.id != null" placeholder="请输入库存数量" />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
          <el-col :span="8">
            <el-form-item label="是否通用" prop="isUniversal">
              <el-select v-model="form.isUniversal" style="width: 100%" placeholder="请选择是否通用">
                <el-option v-for="dict in dict.type.sys_is_enable" :key="dict.value" :label="dict.label" :value="dict.value"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="物资图片" prop="materialUrl">
              <imageUpload v-model="form.materialUrl" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" 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 { listMaterial, getMaterial, delMaterial, addMaterial, updateMaterial } from "@/api/business/material";
import { listMaterialType } from '../../../api/business/materialType'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { listWarehouseLocation } from '../../../api/business/warehouseLocation'
import { listMaterialVendor, listMaterialVendorAll } from '../../../api/business/materialVendor'
import { listSiteWarehouse, listWarehouseAll } from '@/api/business/siteWarehouse'
import {getToken} from "@/utils/auth";

export default {
  name: "Material",
  dicts:['sys_is_enable', 'material_unit'],
  components: { Treeselect },
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      names: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 物资表格数据
      materialList: [],
      materialTypeList: [],
      materialVendorList: [],
      warehouseList: [],
      warehouseLocationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        materialTypeId: undefined,
        materialTypeName: undefined,
        warehouseLocationId: undefined,
        warehouseLocationType: undefined,
        vendorId: undefined,
        vendorName: undefined,
        materialCode: undefined,
        materialName: undefined,
        materialSpecifications: undefined,
        materialUnit: undefined,
        materialWarrantyPeriod: undefined,
        referencePrice: undefined,
        sellingPrice: undefined,
        inventory: undefined,
        isEnable: undefined,
        isUniversal: undefined,
        isCheck: undefined,
      },
      // 导入参数
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/business/material/importData"
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        warehouseId: [
          { required: false, message: "仓库不能为空", trigger: "change" }
        ],
        vendorId: [
          { required: true, message: "供应商不能为空", trigger: "change" }
        ],
        materialCode: [
          { required: true, message: "物资编码不能为空", trigger: "blur" }
        ],
        materialName: [
          { required: true, message: "物资名称不能为空", trigger: "blur" }
        ],
        materialSpecifications: [
          { required: true, message: "物资规格不能为空", trigger: "blur" }
        ],
        materialUnit: [
          { required: true, message: "物资单位不能为空", trigger: "blur" }
        ],
        materialWarrantyPeriod: [
          { required: true, message: "质保期不能为空", trigger: "blur" }
        ],
        referencePrice: [
          { required: true, message: "参考价不能为空", trigger: "blur" }
        ],
        sellingPrice: [
          { required: true, message: "销售价不能为空", trigger: "blur" }
        ],
        inventory: [
          { required: true, message: "库存数量不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询物资列表 */
    getList() {
      this.loading = true;
      listMaterial(this.queryParams).then(response => {
        this.materialList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询物资分类列表 */
    getTypeList() {
      listMaterialType().then(response => {
        this.materialTypeList = this.handleTree(response.data, "typeId");
      });
    },
    /** 查询仓库货位列表 */
    getWarehouseLocationList() {
      listWarehouseLocation({ pageNum:1, pageSize: 1000 }).then(response => {
        this.warehouseLocationList = response.rows;
      });
    },
    /** 查询物资供应商列表 */
    getVendorList() {
      listMaterialVendorAll({isEnable: 1}).then(response => {
        this.materialVendorList = response.data;
      });
    },
    /** 查询仓库列表 */
    getWarehouseList() {
      listWarehouseAll().then(response => {
        this.warehouseList = response.data;
      });
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.typeId,
        label: node.typeName,
        children: node.children
      };
    },
    /** 物资分类更改 */
    materialTypeIdChange() {
      this.$refs.form.clearValidate('materialTypeId')
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        materialTypeId: undefined,
        materialTypeName: undefined,
        warehouseLocationId: undefined,
        warehouseLocationType: undefined,
        vendorId: undefined,
        vendorName: undefined,
        materialCode: undefined,
        materialName: undefined,
        materialSpecifications: undefined,
        materialUnit: undefined,
        materialBrand: undefined,
        procurementSubject: undefined,
        compatibleWith: undefined,
        materialUrl: undefined,
        materialWarrantyPeriod: 1,
        referencePrice: 0,
        sellingPrice: 0,
        inventory: 0,
        isEnable: '1',
        isUniversal: '1',
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined
      };
      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.names = selection.map(item => item.materialName)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加物资";
      this.getVendorList();
      this.getWarehouseList();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getMaterial(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改物资";
        this.getTypeList();
        this.getVendorList();
        this.getWarehouseList();
        this.getWarehouseLocationList();
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateMaterial(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addMaterial(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      const names = row.materialName || this.names;
      this.$modal.confirm(`是否确认删除物资:` + names).then(() => {
        this.loading = true;
        return delMaterial(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/material/export', {
        ...this.queryParams
      }, `物资列表_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "物资导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('business/material/importTemplate', {}, `物资导入模板`)
    },
    // 文件上传中处理
    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>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
  }
};
</script>
