<template>
  <div class="app-container">
    <el-card>
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="88px">
              <el-form-item label="货品名称" prop="goodsName">
                <el-input
                  v-model="queryParams.goodsName"
                  placeholder="请输入货品名称"
                  clearable
                />
              </el-form-item>
<!--        <el-form-item label="排查日期" prop="timeRange">-->
<!--          <el-date-picker-->
<!--            v-model="queryParams.timeRange"-->
<!--            type="daterange"-->
<!--            value-format="yyyy-MM-dd"-->
<!--            range-separator="至"-->
<!--            start-placeholder="开始日期"-->
<!--            end-placeholder="结束日期"-->
<!--            :picker-options="pickerOptions"-->
<!--          >-->
<!--          </el-date-picker>-->
<!--        </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="['baseInfo:material:add']"
              >新增</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="danger"
                plain
                icon="el-icon-delete"
                size="mini"
                :disabled="multiple"
                @click="handleDeleteAll"
                v-hasPermi="['baseInfo:material:remove']"
              >删除</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
          </el-row>
    </el-card>
    <br />
    <el-card>
      <el-table border stripe  v-loading="loading" ref="multipleTable" :data="disposalList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" fixed />
        <el-table-column label="货物编号" align="center" width="150" fixed prop="goodsNum" />
        <el-table-column label="货物名称" align="center" width="150" fixed prop="goodsName" />
        <el-table-column label="仓库名称" align="center" width="150" prop="warehouseName" />
        <el-table-column label="货品类别" align="center" width="100" prop="goodsTypeName" ></el-table-column>
        <el-table-column label="货品规格" align="center" width="100" prop="goodsSpec" />
        <el-table-column label="货品条码" align="center" width="100" prop="goodsBarcode" />
        <el-table-column label="计量单位" align="center" width="100" prop="unit" />
        <el-table-column label="辅助计量单位" align="center" width="100" prop="assistantUnit" />
        <el-table-column label="换算值" align="center" width="100" prop="conversionValue" />
        <el-table-column label="品种" align="center" width="100" prop="varietyName" ></el-table-column>
        <el-table-column label="级别" align="center" width="100" prop="goodsLevelName" />
        <el-table-column label="状态" align="center" width="100" prop="goodsStatus" >
          <template slot-scope="scope">
            <el-tag v-if="scope.row.goodsStatus === '1'" type="primary">启用</el-tag>
            <el-tag v-else-if="scope.row.goodsStatus === '0'" type="danger">停用</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="货品颜色" align="center" width="100" prop="goodsColor" />
        <el-table-column label="货品尺寸" align="center" width="100" prop="goodsSize" />
        <el-table-column label="产品类型" align="center" width="150" prop="productTypeName" ></el-table-column>
        <el-table-column label="备注" align="center" width="200" prop="remark" />
        <el-table-column label="备注一" align="center" width="200" prop="remark1" />
        <el-table-column label="备注二" align="center" width="200" prop="remark2" />
        <el-table-column label="备注三" align="center" width="200" prop="remark3" />
        <el-table-column label="备注四" align="center" width="200" prop="remark4" />
        <el-table-column label="备注五" align="center" width="200" prop="remark5" />
        <el-table-column label="操作" fixed="right" width="180" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleView(scope.row)"
            >查看</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['baseInfo:material:edit']"
              style="margin-right: 8px"
            >修改</el-button>
            <el-popconfirm
              v-hasPermi="['baseInfo:material:remove']"
              :title="'确定要删除这条数据吗？'"
              @confirm="handleDelete(scope.row)"
            >
              <el-button
                size="mini"
                type="text"
                slot="reference"
                icon="el-icon-delete"
              >删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
    <!-- 添加或修改死淘处理方式对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="650px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" :disabled="isView" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="货品编号" prop="goodsNum">
              <el-input
                ref="goodsNum"
                v-model="form.goodsNum"
                @keydown.enter.native="goNext($event, 'goodsName')"
                placeholder="请输入货品编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="货品名称" prop="goodsName">
              <el-input
                ref="goodsName"
                v-model="form.goodsName"
                @keydown.enter.native="goNext($event, 'warehouseNum')"
                placeholder="请输入货品名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="仓库" prop="warehouseNo">
              <el-select
                filterable
                style="width: 100%"
                ref="warehouseNo"
                v-model="form.warehouseNo"
                @keydown.enter.native="goNext($event, 'goodsName')"
                placeholder="请选择仓库"
                @change="changeWarehouse"
              >
                <el-option
                  v-for="item in warehouseList"
                  :key="item.warehouseNo"
                  :value="item.warehouseNo"
                  :label="item.warehouseName"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="货品类别" prop="goodsType">
              <el-select
                filterable
                ref="goodsType"
                style="width: 100%"
                @keydown.enter.native="goNext($event, 'goodsSpec')"
                v-model="form.goodsType"
                @change="changeGoodsType"
                placeholder="请选择货品类别" >
                  <el-option
                    v-for="item in goodsList"
                    :key="item.num"
                    :value="item.num"
                    :label="item.categoryName+ '(' + item.num +')'"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="货品规格" prop="goodsSpec">
              <el-input
                ref="goodsSpec"
                v-model="form.goodsSpec"
                @keydown.enter.native="goNext($event, 'goodsBarcode')"
                placeholder="请输入货品规格"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="货品条码" prop="goodsBarcode">
              <el-input
                ref="goodsBarcode"
                @keydown.enter.native="goNext($event, 'unit')"
                v-model="form.goodsBarcode"
                placeholder="请选择货品条码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="计量单位" prop="unit">
              <el-select
                filterable
                ref="unit"
                style="width: 100%"
                v-model="form.unit"
                placeholder="请选择计量单位"
                @keydown.enter.native="goNext($event, 'assistantUnit')"
              >
                <el-option
                  v-for="(item, i) in unitList"
                  :key="i"
                  :value="item.unitName"
                  :label="item.unitName"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="辅助计量单位" prop="assistantUnit">
              <el-select
                filterable
                ref="assistantUnit"
                style="width: 100%"
                v-model="form.assistantUnit"
                placeholder="请选择辅助计量单位"
                @keydown.enter.native="goNext($event, 'conversionValue')"
              >
                <el-option
                  v-for="(item, i) in unitList"
                  :key="i"
                  :value="item.unitName"
                  :label="item.unitName"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="换算值" prop="conversionValue">
              <decimal-input
                v-model="form.conversionValue"
                :min="0"
                :max="99999"
                :precision="2"
                placeholder="请输入换算值"
                @change="onConversionValueChange"
                @keydown.enter.native="goNext($event, 'variety')"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="品种" prop="variety">
              <el-select
                filterable
                ref="variety"
                style="width: 100%"
                v-model="form.variety"
                placeholder="请选择品种"
                @change="changeVariety"
                @keydown.enter.native="goNext($event, 'goodsStatus')"
              >
                <el-option
                  v-for="item in varietyList"
                  :key="item.varietyNo"
                  :value="item.varietyNo"
                  :label="item.varietyName"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="状态" prop="goodsStatus">
              <el-select
                filterable
                ref="goodsStatus"
                style="width: 100%"
                v-model="form.goodsStatus"
                placeholder="请选择状态"
                @keydown.enter.native="goNext($event, 'goodsColor')"
              >
                <el-option :value="'1'" label="启用"></el-option>
                <el-option :value="'0'" label="停用"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="货品颜色" prop="goodsColor">
              <el-input
                ref="goodsColor"
                v-model="form.goodsColor"
                placeholder="请输入货品颜色"
                @keydown.enter.native="goNext($event, 'goodsSize')"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="货品尺寸" prop="goodsSize">
              <el-input
                ref="goodsSize"
                v-model="form.goodsSize"
                placeholder="请输入货品尺寸"
                @keydown.enter.native="goNext($event, 'productType')"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品类型" prop="productType">
              <el-select
                filterable
                ref="productType"
                style="width: 100%"
                v-model="form.productType"
                placeholder="请选择产品类型"
                @change="changeProduceType"
                @keydown.enter.native="goNext($event, 'goodsLevel')"
              >
                <el-option v-for="item in produceTypeList" :key="item.typeNum" :label="item.typeName" :value="item.typeNum"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="级别" prop="goodsLevel">
              <el-select
                filterable
                ref="goodsLevel"
                style="width: 100%"
                v-model="form.goodsLevel"
                placeholder="请选择级别"
                @change="changeGoodsLevel"
                @keydown.enter.native="goNext($event, 'remark')"
              >
                <el-option v-for="item in levelList" :key="item.levelNo" :label="item.levelName" :value="item.levelNo"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input ref="remark" type="textarea" v-model="form.remark"  placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注一" prop="remark">
              <el-input type="textarea" v-model="form.remark1"  placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注二" prop="remark">
              <el-input type="textarea" v-model="form.remark2"  placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注三" prop="remark">
              <el-input type="textarea" v-model="form.remark3"  placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注四" prop="remark">
              <el-input type="textarea" v-model="form.remark4"  placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注五" prop="remark">
              <el-input type="textarea" v-model="form.remark5"  placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="!isView">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getMaterialPage, getMaterialById, addMaterial, editMaterial, delMaterial } from "@/api/baseInfo/material";
import { getWareHouseList } from "../../../api/inventory/wareHouse";
import { getFindByKey } from "../../../utils";
import { getGoodsList } from "../../../api/baseInfo/goods";
import { getVarietyList } from "../../../api/baseInfo/variety";
import { getUnitList } from "../../../api/baseInfo/unit";
import { getProduceTypeList } from "../../../api/baseInfo/produceType";
import { getLevelList } from "../../../api/baseInfo/level";

export default {
  name: "Material",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      disposalList: [],
      // 弹出层标题
      title: "",
      isView:false,
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        goodsName: null,
        timeRange: null,
        startTime: null,
        endTime: null,
      },
      pickerOptions: {
        disabledDate(time) {
          // 获取当前日期
          const today = new Date();
          today.setHours(0, 0, 0, 0); // 将时间设置为当天的 00:00:00

          // 禁用今天之后的日期
          return time.getTime() > today.getTime();
        }
      },
      // 表单参数
      form: {},
      rules: {
        goodsNum: [{ required: true, message: "请输入货品编号", trigger: "blur" }],
        goodsName: [{ required: true, message: "请输入货品名称", trigger: "blur" }],
        warehouseNo: [{ required: true, message: "请选择仓库", trigger: "change" }],
        goodsType: [{ required: true, message: "请选择货品类别", trigger: "change" }],
        goodsSpec: [{ required: true, message: "请输入货品规格", trigger: "blur" }],
        unit: [{ required: true, message: "请选择计量单位", trigger: "change" }],
        assistantUnit: [{ required: true, message: "请选择辅助计量单位", trigger: "change" }],
        conversionValue: [
          {
            validator: (rule, value, callback) => {
              if (value === null || value === undefined || String(value).trim() === "") {
                callback(new Error("请输入换算值"));
                return;
              }
              const n = Number(value);
              if (Number.isNaN(n)) {
                callback(new Error("换算值格式不正确"));
                return;
              }
              callback();
            },
            trigger: ["change", "blur"],
          },
        ],
        variety: [{ required: true, message: "请选择品种", trigger: "change" }],
        productType: [{ required: true, message: "请选择产品类型", trigger: "change" }],
      },
      warehouseList: [],
      goodsList: [],
      varietyList: [],
      unitList: [],
      produceTypeList: [],
      levelList: []
    }
  },
  watch: {
    "queryParams.timeRange": {
      handler(newVal) {
        if (newVal) {
          this.queryParams.startTime = newVal[0]
          this.queryParams.endTime = newVal[1]
        } else {
          this.queryParams.startTime = null
          this.queryParams.endTime = null
        }
      },
      deep: true
    },
  },
  created() {
    this.getUnit()
    this.getWarehouse()
    this.getGoods()
    this.getProduceType()
    this.getVariety()
    this.getLevel()
    this.getList();
  },
  methods: {
    /**
     * 换算值变更后触发表单项校验（与 decimal-input 的 change 对齐）
     */
    onConversionValueChange() {
      this.$nextTick(() => {
        if (this.$refs.form) this.$refs.form.validateField("conversionValue");
      });
    },
    goNext(event, nextRef) {
      event.preventDefault();
      this.$refs[nextRef].focus();
    },
    /** 级别 **/
    getLevel() {
      getLevelList({}).then(res => {
        this.levelList = res.data
      })
    },
    changeGoodsLevel(val) {
      let item = getFindByKey(this.levelList, val, 'levelNo')
      if(item) {
        this.form.goodsLevelName = item.levelName
      }
    },
    /** 产品类型列表 **/
    getProduceType() {
      getProduceTypeList({}).then(res => {
        this.produceTypeList = res.data
      })
    },
    changeProduceType(val) {
      let item = getFindByKey(this.produceTypeList, val, 'typeNum')
      if(item) {
        this.form.productTypeName = item.typeName
      }
    },
    /** 单位列表**/
    getUnit() {
      getUnitList({}).then(res => {
        this.unitList = res.data
      })
    },
    /** 品种列表 **/
    getVariety() {
      getVarietyList({}).then(res => {
        this.varietyList = res.data
      })
    },
    changeVariety(val) {
      console.log(111, val)
      let item = getFindByKey(this.varietyList, val, 'varietyNo')
      if(item) {
        this.form.varietyName = item.varietyName
      }
      console.log(item)
    },
    /** 货品类别列表 **/
    getGoods() {
      getGoodsList({}).then(res => {
        this.goodsList = res.data
      })
    },
    changeGoodsType(val) {
      let item = getFindByKey(this.goodsList, val, 'num')
      if(item) {
        this.form.goodsTypeName = item.categoryName
      }
    },
    /** 仓库列表 **/
    getWarehouse() {
      getWareHouseList({}).then(res => {
        this.warehouseList = res.data
      })
    },
    changeWarehouse(val) {
      let item = getFindByKey(this.warehouseList, val, 'warehouseNo')
      if(item) {
        this.form.warehouseName = item.warehouseName
      }
    },
    /** 查询检验项目列表 */
    getList() {
      getMaterialPage(this.queryParams).then(res => {
        this.disposalList = res.data.records;
        this.total = res.data.total;
        this.loading = false;
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      // this.resetForm("queryForm");
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        goodsName: null,
        timeRange: null,
        startTime: null,
        endTime: 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.isView = false;
      this.title = "添加";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      let params = {
        id: id
      }
      getMaterialById(params).then(res => {
        this.form = res.data;
        this.open = true;
        this.isView = false;
        this.title = "编辑"
      })
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.reset();
      const id = row.id;
      let params = {
        id: id
      }
      getMaterialById(params).then(res => {
        this.form = res.data;
        this.open = true;
        this.isView = true;
        this.title = "查看"
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        goodsNum: null,
        goodsName: null,
        warehouseNo: null,
        warehouseName: null,
        goodsType: null,
        goodsTypeName: null,
        goodsSpec: null,
        goodsBarcode: null,
        unit: null,
        assistantUnit: null,
        conversionValue: null,
        variety: null,
        varietyName: null,
        goodsLevel: null,
        goodsLevelName: null,
        goodsStatus: '1',
        goodsColor: null,
        goodsSize: null,
        productType: null,
        productTypeName: null,
        remark: null,
        remark1: null,
        remark2: null,
        remark3: null,
        remark4: null,
        remark5: null,
        // dealReason: null,
        // dealWay: null,
      };
      this.resetForm("form");
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            // 编辑
            editMaterial(this.form).then(res => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            })
          } else {
            // 新增
            addMaterial(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id;
      let params = {
        ids: ids
      }
      delMaterial(params).then(res => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      })
    },
    /** 删除按钮操作 */
    handleDeleteAll() {
      const ids = this.ids;
      this.$modal.confirm('确定要删除这条数据吗？').then(() => {
        let params = {
          ids: ids.join(',')
        }
        delMaterial(params).then(res => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
          this.$refs.multipleTable.clearSelection();
        })
      })
    }
  }
}
</script>

<style scoped lang="scss">

</style>
