<template>
  <div class="app-container">
    <!-- 搜索工作栏 -->
    <el-form
      v-show="showSearch"
      ref="queryForm"
      :model="queryParams"
      size="small"
      label-width="68px"
    >
      <QueryFormWrapper>
        <el-col :span="8">
          <el-form-item label="仓库编号" prop="code">
            <el-input
              v-model="queryParams.code"
              placeholder="请输入仓库编号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="仓库名称" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入仓库名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="仓库地址" prop="address">
            <el-input
              v-model="queryParams.address"
              placeholder="请输入仓库地址"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>

        <div slot="right">
          <el-form-item label-width="0" class="text-right" style="word">
            <EasyAdvancedQuery
              class="mr10"
              label-width="98px"
              @advQuery="advQuery"
            >
              <template #default="{ model }">
                <el-row :gutter="10" type="flex">
                  <el-col :span="12">
                    <el-form-item label="仓库模式" prop="stockModel">
                      <el-select
                        v-model="model.stockModel"
                        placeholder="请选择仓库模式"
                        clearable
                        size="small"
                      >
                        <el-option
                          v-for="dict in getDictDatas(
                            DICT_TYPE.WMS_STOCK_MODES
                          )"
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="仓库类别" prop="stockCategory">
                      <el-select
                        v-model="model.stockCategory"
                        placeholder="请选择仓库类别"
                        clearable
                        size="small"
                      >
                        <el-option
                          v-for="dict in getDictDatas(
                            DICT_TYPE.WMS_STOCK_CATEGORIES
                          )"
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="管理员" prop="adminUser">
                      <el-input
                        v-model="model.adminUser"
                        placeholder="请输入管理员"
                        clearable
                        @keyup.enter.native="handleQuery"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="所属工厂" prop="factoryCode">
                      <FactorySelect
                        v-model="model.factoryCode"
                        filterable
                        placeholder="请选择所属工厂"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>
              </template>
            </EasyAdvancedQuery>
            <el-button type="primary" icon="el-icon-search" @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" @click="resetQuery"
              >重置</el-button
            >
          </el-form-item>
        </div>
      </QueryFormWrapper>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['wms:stock:create']"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['wms:stock:export']"
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :show-search.sync="showSearch"
        :columns="columnsList"
        @queryTable="getList"
        @saveSetting="getColumnsList"
      />
    </el-row>

    <!-- 列表 -->
    <AutoResizer :given-height="177">
      <template #default="{ height }">
        <el-table
          v-if="columnsList.length > 0"
          ref="table"
          v-loading="loading"
          :data="list"
          border
          :height="height"
        >
          <el-table-column
            v-if="columnsList[0].visible"
            :key="Math.random()"
            label="仓库编号"
            align="center"
            prop="code"
            fixed="left"
            width="150"
          >
            <!-- :data="list" prop="code" label="仓库编号"  -->

            <template #header>
              <TableColumnFilter
                :data="list"
                prop="code"
                label="仓库编号"
                @selectData="handleFilterData"
              />
            </template>
          </el-table-column>
          <el-table-column
            v-if="columnsList[1].visible"
            :key="Math.random()"
            label="仓库名称"
            align="center"
            prop="name"
            show-overflow-tooltip
            width="160"
          >
            <template #header>
              <TableColumnFilter
                :data="list"
                prop="name"
                label="仓库名称"
                @selectData="handleFilterData"
              />
            </template>
          </el-table-column>
          <el-table-column
            v-if="columnsList[2].visible"
            :key="Math.random()"
            label="仓库地址"
            align="center"
            prop="address"
            width="150"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columnsList[3].visible"
            :key="Math.random()"
            label="仓库模式"
            align="center"
            prop="stockModel"
          >
            <template slot-scope="scope">
              <dict-tag
                :type="DICT_TYPE.WMS_STOCK_MODES"
                :value="scope.row.stockModel"
              />
            </template>
          </el-table-column>
          <el-table-column
            v-if="columnsList[4].visible"
            :key="Math.random()"
            label="仓库类别"
            align="center"
            prop="stockCategory"
          >
            <template slot-scope="scope">
              <dict-tag
                :type="DICT_TYPE.WMS_STOCK_CATEGORIES"
                :value="scope.row.stockCategory"
              />
            </template>
          </el-table-column>
          <el-table-column
            v-if="columnsList[5].visible"
            :key="Math.random()"
            label="管理员"
            align="center"
            prop="adminUser"
          />
          <el-table-column
            v-if="columnsList[6].visible"
            :key="Math.random()"
            label="所属工厂"
            align="center"
            prop="factoryName"
            width="130"
          >
            <template #header>
              <TableColumnFilter
                :data="list"
                prop="factoryName"
                label="所属工厂"
                @selectData="handleFilterData"
              />
            </template>
          </el-table-column>
          <el-table-column
            v-if="columnsList[7].visible"
            :key="Math.random()"
            label="创建时间"
            align="center"
            prop="createTime"
            width="180"
          >
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
            fixed="right"
            width="220"
          >
            <template slot-scope="scope">
              <!-- :disabled="scope.row.erpMark === '0'" -->
              <el-button
                v-hasPermi="['wms:stock:update']"
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                >修改</el-button
              >
              <el-button
                v-hasPermi="['wms:stock:delete']"
                size="mini"
                type="text"
                icon="el-icon-delete"
                class="text-danger"
                :disabled="scope.row.erpMark === '0'"
                @click="handleDelete(scope.row)"
                >删除</el-button
              >
              <el-button
                size="mini"
                type="text"
                icon="el-icon-help"
                @click="handleMaintain(scope.row)"
                >维护区域</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </template>
    </AutoResizer>
    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNo"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 对话框(添加 / 修改) -->
    <el-dialog
      v-dialogDrag
      :title="title"
      :visible.sync="open"
      width="500px"
      append-to-body
      @close="dialogClose"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-form-item label="仓库编号" prop="code">
          <el-input
            v-model="form.code"
            placeholder="仓库编码自动生成"
            disabled
          />
        </el-form-item>
        <el-form-item label="仓库名称" prop="name">
          <el-input
            v-model="form.name"
            placeholder="请输入仓库名称"
            :disabled="editDisabled"
          />
        </el-form-item>
        <el-form-item label="仓库地址" prop="address">
          <el-input
            v-model="form.address"
            placeholder="请输入仓库地址"
            :disabled="editDisabled"
          />
        </el-form-item>
        <el-form-item label="仓库模式" prop="stockModel">
          <el-select
            v-model="form.stockModel"
            placeholder="请选择仓库模式"
            clearable
            size="small"
          >
            <el-option
              v-for="dict in getDictDatas(DICT_TYPE.WMS_STOCK_MODES)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="仓库类别" prop="stockCategory">
          <el-select
            v-model="form.stockCategory"
            placeholder="请选择仓库类别"
            clearable
            size="small"
          >
            <el-option
              v-for="dict in getDictDatas(DICT_TYPE.WMS_STOCK_CATEGORIES)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="管理员" prop="adminUser">
          <!-- <el-input v-model="form.adminUser" placeholder="请输入管理员" :disabled="editDisabled" /> -->
          <AdministratorsSelect
            v-model="form.adminUser"
            filterable
            :disabled="editDisabled"
            placeholder="请选择管理员"
          />
        </el-form-item>
        <el-form-item label="所属工厂" prop="factoryCode">
          <FactorySelect
            v-model="form.factoryCode"
            filterable
            placeholder="请选择所属工厂"
          />
        </el-form-item>
        <el-form-item label="倒冲仓" prop="factoryCode">
          <el-select
            v-model="form.reverseStockId"
            clearable
            filterable
            remote
            reserve-keyword
            placeholder="请输入关键词"
            :remote-method="handleSearchReverseStockList"
            :loading="loading"
          >
            <el-option
              v-for="item in reverseStockList"
              :key="item.id"
              :label="item.label"
              :value="item.id"
            >
              <span style="float: left">{{ item.label }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{
                item.value
              }}</span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>

    <!-- 对话框(维护区域) -->
    <StockArea ref="stockArea" :ids="ids" :code="code" :names="stockName" />
  </div>
</template>

<script>
import {
  createStock,
  updateStock,
  deleteStock,
  getStock,
  getStockPage,
  exportStockExcel,
  getReverseStockListPage,
} from "@/api/wms/base/stock";
import { getFormColumnsList } from "@/api/system/saveColumns/index";
import FactorySelect from "./components/FactorySelect.vue";
import StockArea from "./components/StockArea.vue";
import DictTag from "@/components/DictTag";
import AdministratorsSelect from "./components/AdministratorsSelect.vue";
import TableColumnFilter from "@/components/TableColumnFilter/index.vue";
import { mapGetters } from "vuex";
import { isArray } from "min-dash";

export default {
  name: "Stock",
  components: {
    FactorySelect,
    StockArea,
    DictTag,
    AdministratorsSelect,
    TableColumnFilter,
  },

  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 仓库列表
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openView: false,
      // 修改禁用状态
      editDisabled: false,
      // 传给区域的id
      ids: "",
      //  传给区域的编码code
      code: "",
      stockName: "",
      // 过滤数据
      filterData: [],
      // 显示隐藏列默认参数
      columns: [
        { key: 0, label: "仓库编码", visible: true },
        { key: 1, label: "仓库名称", visible: true },
        { key: 2, label: "仓库地址", visible: true },
        { key: 3, label: "仓库模式", visible: true },
        { key: 4, label: "仓库类别", visible: true },
        { key: 5, label: "管理员", visible: true },
        { key: 6, label: "所属工厂", visible: true },
        { key: 7, label: "创建时间", visible: true },
      ],
      // 显示隐藏持久化参数
      columnsList: [],
      // 倒冲仓列表
      reverseStockList: [],
      // 高级查询参数
      advParams: {},
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        code: null,
        name: null,
        status: null,
        address: null,
        stockModel: null,
        stockCategory: null,
        adminUser: null,
        factoryCode: null,
        factoryName: null,
        docunentStatus: null,
        createTime: [],
        erpMark: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        // code: [{ required: true, message: '仓库编号不能为空', trigger: 'blur' }],
        name: [
          { required: true, message: "仓库名称不能为空", trigger: "blur" },
        ],
        stockCategory: [
          { required: true, message: "仓库类别不能为空", trigger: "change" },
        ],
        stockModel: [
          { required: true, message: "仓库模式不能为空", trigger: "change" },
        ],
        factoryCode: [
          { required: true, message: "所属工厂不能为空", trigger: "change" },
        ],
        locationQty: [
          { required: true, message: "货位数量不能为空", trigger: "blur" },
        ],
      },
      filterList: [],
    };
  },
  // 获取当前登录用户id
  computed: {
    ...mapGetters(["userId"]),
  },
  created() {
    // 获取显隐列列表
    this.getColumnsList();
    this.getList();
    // this.handleSearchReverseStockList()
  },
  methods: {
    // 获取倒冲仓下拉列表数据
    handleSearchReverseStockList(keyword) {
      this.loading = true;
      getReverseStockListPage({ pageNo: 1, pageSize: 30, keyword })
        .then(({ code, data, msg }) => {
          if (code === 0) {
            this.reverseStockList = [];
            data?.forEach((item) => {
              this.reverseStockList.push({
                ...item,
                id: item.id,
                label: item.name,
                value: item.id,
              });
            });
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 执行查询
      const allParams = { ...this.queryParams, ...this.advParams };
      getStockPage(allParams)
        .then((response) => {
          const { list = [] } = response.data || {};
          this.list = list.map((item) => {
            item.erpMark = item.erpMark + "";
            return item;
          });
          this.filterList = [...this.list];
          this.total = response.data.total;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        erpId: undefined,
        code: undefined,
        name: undefined,
        status: undefined,
        address: undefined,
        stockModel: undefined,
        stockCategory: undefined,
        adminUser: undefined,
        factoryCode: undefined,
        docunentStatus: undefined,
        erpMark: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.advParams = {};
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加仓库";
    },
    valueToString(value) {
      return value === undefined || value === null ? "" : value + "";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      this.editDisabled = true;
      getStock(id).then((response) => {
        response.data.erpMark = this.valueToString(response.data.erpMark);
        this.form = response.data;
        this.open = true;
        this.title = "修改仓库";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (!valid) {
          return;
        }
        delete this.form.factoryName;
        // 修改的提交
        if (this.form.id != null) {
          updateStock(this.form)
            .then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.editDisabled = false;
              this.getList();
            })
            .finally(() => {
              this.editDisabled = false;
            });
          return;
        }
        // 添加的提交
        createStock(this.form).then((response) => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const { name, id } = row;
      this.$modal
        .confirm('是否确认删除仓库编号为"' + name + '"的数据项?')
        .then(function () {
          return deleteStock(id);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      const params = { ...this.queryParams };
      params.pageNo = undefined;
      params.pageSize = undefined;
      this.$modal
        .confirm("是否确认导出所有仓库数据项?")
        .then(() => {
          this.exportLoading = true;
          return exportStockExcel(params);
        })
        .then((response) => {
          this.$download.excel(response, "仓库.xls");
          this.exportLoading = false;
        })
        .catch(() => {});
    },
    dialogClose() {
      this.editDisabled = false;
    },
    /** 维护区域 */
    handleMaintain(row) {
      const { id, code, name } = row;
      this.ids = id;
      this.code = code;
      this.stockName = name;
      this.$refs.stockArea.stockCode = code;
      this.$refs.stockArea.openView = true;
    },
    // 数据过滤
    handleFilterData(data, prop) {
      if (data.length === 0) {
        this.list = this.filterList;
        return;
      }
      this.list = this.list.filter((item) =>
        data.some((subItem) => item[prop] === subItem.column)
      );
      // this.list = this.list.filter(item => data.some(subItem => subItem.column === item.code))
    },
    // 高级查询
    advQuery(advQueryParams) {
      this.advParams = advQueryParams;
      this.handleQuery();
    },
    // 获取显示隐藏列
    getColumnsList() {
      const { componentName } = this.$route.meta || null;
      const params = {
        userId: this.userId,
        vueForm: componentName,
      };
      getFormColumnsList(params)
        .then((res) => {
          if (isArray(res.data)) {
            this.columnsList = res.data.length === 0 ? this.columns : res.data;
            // 对比默认数据和接口数据，将缺失的列添加到接口数据中
            this.columnsList = this.columns.reduce((acc, defaultColumn) => {
              const found = res.data.find(
                (apiColumn) => apiColumn.key === defaultColumn.key
              );
              if (!found) {
                acc.push({
                  ...defaultColumn,
                  vueForm: componentName,
                  userId: this.userId,
                  id: null,
                });
              }
              return acc;
            }, res.data);
          } else {
            this.columnsList = this.columns;
          }
        })
        .catch((err) => {
          if (err) {
            this.columnsList = this.columns;
          }
        })
        .finally(() => {
          this.$emit("columns", this.columnsList);
        });
    },
  },
};
</script>
