<template>
<!--  -->
  <div class="app-container">
    <el-form :model="queryParams" size="mini"  ref="queryParams" :inline="true" v-show="showSearch" label-width="70px">
      <el-form-item label="库位名称" prop="warehouseName">
        <el-input
          v-model="queryParams.warehouseName"
          placeholder="请输入库位名称"
          clearable
          size="mini"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item :class="['treeselectForm',{borderRed:!validTree}]" label="组织架构" prop="orgIds">
        <tree @treeselectFn="treeselectFn" :treeval="queryParams.orgIds" :ismultiple="true"></tree>
      </el-form-item>
      <el-form-item label="库位代码" prop="warehouseCode">
        <el-input
          v-model="queryParams.warehouseCode"
          placeholder="请输入库位代码"
          clearable
          size="mini"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="库位级别" prop="inventoryLeavel">
        <el-select
          v-model="queryParams.inventoryLeavel"
          placeholder="库位级别"
          clearable
        >
          <el-option
            v-for="dict in dict.type.material_level_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value">
          <p style="margin: 0"  @click="inventoryLeavelFn">{{dict.label}}</p>
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="库位类型" prop="warehouseType">
        <el-select
          v-model="queryParams.warehouseType"
          placeholder="库位类型"
          clearable
        >
          <el-option
            v-for="dict in wlwarehouseType"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="状态"
          clearable
        >
          <el-option
            label="正常"
            value="0"
          />
          <el-option
            label="冻结"
            value="2"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="物料类型" prop="materialTypeName">
        <el-select v-model="queryParams.materialTypeName" size="mini" clearable filterable @change="materialTypeChangeQuery">
          <el-option
            v-for="item in materialTypeOption"
            :key="item.signType"
            :label="item.signType"
            :value="item.signType"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="物料名称" prop="materialDataName">
        <el-select v-model="queryParams.materialDataName" size="mini" clearable filterable @change="onInput()">
          <el-option
            v-for="item in materialNameOptionQuery"
            :key="item.signName"
            :label="item.signName"
            :value="item.signName"
          />
        </el-select>
      </el-form-item>
<!--      <el-form-item label="物料种类" prop="materialTypeName">-->
<!--        <el-input-->
<!--          v-model="queryParams.materialTypeName"-->
<!--          placeholder="请输入物料种类"-->
<!--          clearable-->
<!--          size="small"-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="物料名称" prop="materialDataName">-->
<!--        <el-input-->
<!--          v-model="queryParams.materialDataName"-->
<!--          placeholder="请输入物料名称"-->
<!--          clearable-->
<!--          size="small"-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </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="listRresetQuery">重置</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="['sfa:materialInventory: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="['sfa:materialInventory: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="['sfa:materialInventory: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="['sfa:materialInventory:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="materialInventoryList">
      <el-table-column label="库位类型" align="center" prop="warehouseType" >
        <template slot-scope="scope">
          <dicts-tag :options="wlwarehouseType" :value="scope.row.warehouseType"/>
        </template>
      </el-table-column>
      <el-table-column label="库位名称" prop="warehouseName" width="180" :show-overflow-tooltip="true"/>
      <el-table-column label="库位代码"  prop="warehouseCode" />
      <el-table-column label="库位层次"  prop="inventoryLeavel" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.material_level_type" :value="scope.row.inventoryLeavel"/>
        </template>
      </el-table-column>

      <el-table-column label="状态" align="center" prop="status" width="90" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span v-if="scope.row.status==0" style="color:#67c23a">正常</span>
          <span v-if="scope.row.status==2" style="color:#e6a23c">冻结</span>
        </template>
      </el-table-column>
      <el-table-column label="物料类型"  prop="materialTypeName" />
      <el-table-column label="物料名称"  prop="materialDataName" :show-overflow-tooltip="true"/>
      <el-table-column label="物料编码"  prop="materialDataCode" width="130"/>
<!--      <el-table-column label="实时库存" align="center" prop="inventoryNum" />-->
      <el-table-column label="实时库存" width="80px" align="center" :show-overflow-tooltip="true">
        <template slot-scope="scope">
            <span class="linkks"  @click="inventoryLogDataFn(scope.row.inventoryId)">{{ scope.row.inventoryNum }}</span>
        </template>

      </el-table-column>
      <el-table-column label="公司"  prop="inventoryGsDeptName" :show-overflow-tooltip="true"/>
      <el-table-column label="大区"  prop="inventoryDqDeptName" :show-overflow-tooltip="true"/>
      <el-table-column label="销售部"   prop="inventoryMdDeptName" :show-overflow-tooltip="true"/>
<!--      <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-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['sfa:materialInventory:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['sfa:materialInventory: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="90%" append-to-body>
      <el-form :model="queryParamsRw" size="mini"  ref="queryParamsRw" :inline="true" v-show="showSearch" label-width="120px">
        <el-form-item label="操作人库位" prop="changeWarehouseName">
          <el-input
            v-model="queryParamsRw.changeWarehouseName"
            placeholder="请输入操作人库位"
            clearable
            size="small"
            @keyup.enter.native="handleQueryRw"
          />
        </el-form-item>
        <el-form-item label="变更类型" prop="changeType">
          <el-select
            v-model="queryParamsRw.changeType"
            placeholder="变更类型"
            clearable
            style="width: 240px"
          >
            <el-option
              v-for="dict in dict.type.material_change_log_type"
              :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="handleQueryRw">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="listRresetQueryRw">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="loadingRW" :data="materialInventoryLogList">
        <el-table-column label="操作人库位名称" align="center" prop="changeWarehouseName" />
        <el-table-column label="操作人库位代码" align="center" prop="changeWarehouseCode" />
<!--        <el-table-column label="操作人库位层次" align="center" prop="inventoryLeavel">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.material_level_type" :value="scope.row.inventoryLeavel"/>
          </template>
        </el-table-column>-->
        <el-table-column label="库存变更量" align="center" prop="inventoryNum" />
        <el-table-column label="变更类型" align="center" prop="changeType">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.material_change_log_type" :value="scope.row.changeType"/>
          </template>
        </el-table-column>
        <el-table-column label="变更时间" align="center" prop="createTime" />
<!--        <el-table-column label="公司" align="center" prop="inventoryGsDeptName" />
        <el-table-column label="大区" align="center" prop="inventoryDqDeptName" />
        <el-table-column label="销售部" align="center" prop="inventoryMdDeptName" />-->
      </el-table>
      <pagination
        v-show="totalRw>0"
        :total="totalRw"
        :page.sync="queryParamsRw.pageNum"
        :limit.sync="queryParamsRw.pageSize"
        @pagination="getMaterialInventoryLogData"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="open=false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import tree from "@/views/components/sfa/treeselectParentNo";
import treeSingle from "@/views/components/sfa/treeselectSingle";
import user from "@/views/components/sfa/user";
import { listMaterialInventory, getMaterialInventory, delMaterialInventory, addMaterialInventory, updateMaterialInventory } from "@/api/sfa/materialInventory";
import { listMaterialInventoryLog, getMaterialInventoryLog, addMaterialInventoryLog, updateMaterialInventoryLog, delMaterialInventoryLog } from "@/api/sfa/materialInventoryLog";
import {listDictype} from "@/api/sfa/dictype";

export default {
  name: "MaterialInventory",
  components: { treeSingle,user,tree},
  dicts: ['material_level_type','material_change_type','material_change_log_type'],
  data() {
    return {

      // 遮罩层
      loading: true,
      //遮罩层（变更记录）
      loadingRW: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      //总条数（变更记录）
      totalRw: 0,
      // 物料库存表格数据
      materialInventoryList: [],
      wlwarehouseType:[],
      materialTypeOption:[],
      materialNameOptionQuery:[],
      // 物料库存变更表格数据
      materialInventoryLogList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        inventoryGsDeptId: null,
        inventoryGsDeptName: null,
        inventoryDqDeptId: null,
        inventoryDqDeptName: null,
        inventoryMdDeptId: null,
        inventoryMdDeptName: null,
        materialTypeId: null,
        materialTypeName: null,
        materialDataId: null,
        materialDataName: null,
        inventoryNum: null,
        inventoryLeavel: null,
        status: null,
        orgIds:null,
        warehouseName:null,
        warehouseCode:null,
        inventoryLyUserId:null,
        inventoryLyUserName:null,
      },
      // 查询参数（变更记录）
      queryParamsRw: {
        pageNum: 1,
        pageSize: 10,
        materialInventoryId: null,
        changeWarehouseName:null,
        changeWarehouseCode:null,
        changeType:null,
      },
      validTree:true,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
    this.getMaterialTypeOption()
    this.getDicts("wl_warehouse_type").then(response => {
      this.wlwarehouseType = response.data;
    });
  },
  methods: {
    inventoryLeavelFn(val){
      setTimeout(()=>{
        if(this.queryParams.inventoryLeavel==0){
          this.queryParams.orgIds=undefined
        }
      })
    },
    materialTypeChangeQuery(val){
      this.queryParams.materialName = '';
      if(val != '' && val != null){
        let pid;
        this.materialTypeOption.forEach((item)=>{
          if(item.signType == val){
            pid = item.id;
            let obj = {
              type:1,
              pid,
            };
            this.getMaterialNameOption(obj,'materialNameOptionQuery');
          }
        })
      }else{
        this.materialNameOptionQuery = [];
      }
      this.$forceUpdate()
    },
    getMaterialTypeOption(){
      let obj = {
        type:0,
      };
      this.getMaterialNameOption(obj,'materialTypeOption');
    },
    onInput(){
      this.$forceUpdate()
    },
    getMaterialNameOption(obj,str) {
      let that = this;
      listDictype(obj).then(response => {
        if(str == 'materialNameOptionAll'){
          that.materialNameOptionAll = response.rows;
        }else if(str == 'materialTypeOption'){
          that.materialTypeOption = response.rows;
        }else if(str == 'materialNameOption'){
          that.materialNameOption = response.rows;
        }else if(str == 'materialNameOptionQuery'){
          that.materialNameOptionQuery = response.rows;
        }
      });
    },
    /** 查询物料库存列表 */
    getList() {
      this.loading = true;
      listMaterialInventory(this.queryParams).then(response => {
        this.materialInventoryList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询物料变更记录列表 */
    getListRw() {
      this.loadingRW = true;
      listMaterialInventoryLog(this.queryParamsRw).then(response => {
        this.materialInventoryLogList = response.rows;
        this.totalRw = response.total;
        this.loadingRW = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        inventoryId: null,
        inventoryGsDeptId: null,
        inventoryGsDeptName: null,
        inventoryDqDeptId: null,
        inventoryDqDeptName: null,
        inventoryMdDeptId: null,
        inventoryMdDeptName: null,
        materialTypeId: null,
        materialTypeName: null,
        materialDataId: null,
        materialDataName: null,
        inventoryNum: null,
        inventoryLeavel: null,
        status: "0",
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        warehouseName:null,
        warehouseCode:null,
        inventoryLyUserId:null,
        inventoryLyUserName:null,
      };
      this.resetForm("form");
    },
    // 变更记录表单重置
    resetRw() {
      this.form = {
        materialInventoryId: null,
        status: "0",
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        changeWarehouseName:null,
        changeWarehouseCode:null,
        changeType:null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 变更记录搜索按钮操作 */
    handleQueryRw() {
      this.queryParamsRw.pageNum = 1;
      this.getListRw();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 库存重置
    listRresetQuery(){
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        orgIds:null,
        warehouseCode:'',
        inventoryLeavel:'',
        materialTypeName:'',
        materialDataName:'',
      };
      this.handleQuery();
    },
    // 变更记录重置
    listRresetQueryRw(){
      this.queryParamsRw.pageNum=1
      this.queryParamsRw.pageSize=10
      this.queryParamsRw.changeType=""
      this.queryParamsRw.changeWarehouseName=""
      this.queryParamsRw.changeWarehouseCode=""
      this.handleQueryRw()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.inventoryId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加物料库存";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const inventoryId = row.inventoryId || this.ids
      getMaterialInventory(inventoryId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改物料库存";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.inventoryId != null) {
            updateMaterialInventory(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMaterialInventory(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const inventoryIds = row.inventoryId || this.ids;
      this.$modal.confirm('是否确认删除物料库存编号为"' + inventoryIds + '"的数据项？').then(function() {
        return delMaterialInventory(inventoryIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.downloads('sfa/materialInventory/export', {
        ...this.queryParams
      }, `materialInventory_${new Date().getTime()}.xlsx`)
    },
    treeselectFn(val){
      this.queryParams.orgIds = val;
      if(this.queryParams.inventoryLeavel==0&&this.queryParams.orgIds.length>0){
        this.queryParams.inventoryLeavel=undefined
      }
    },
    inventoryLogDataFn(id){
      this.queryParamsRw.materialInventoryId = id;
      this.queryParamsRw.pageNum=1
      this.queryParamsRw.changeType=""
      this.queryParamsRw.changeWarehouseName=""
      this.queryParamsRw.changeWarehouseCode=""
      this.getMaterialInventoryLogData()
    },
    //变更记录点击事件
    getMaterialInventoryLogData(materialInventoryId){
      this.loadingRW = true;
      listMaterialInventoryLog(this.queryParamsRw).then(response => {
        this.materialInventoryLogList = response.rows;
        this.loadingRW = false;
        this.totalRw = response.total;
        this.open = true;
        this.title = "库存变更记录";
      });
    },
  }
};
</script>
