<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="88px"
    >
      <el-form-item label="屠宰时间" prop="produceTime">
        <el-date-picker
          clearable
          v-model="queryParams.produceTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择屠宰时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="血码" prop="slaughterCode">
        <el-input
          v-model="queryParams.slaughterCode"
          placeholder="请输入血码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="检疫证号" prop="animalCertNo">
        <el-input
          v-model="queryParams.animalCertNo"
          placeholder="请输入检疫证号"
          clearable
          @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="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="['app:porkOtherProduce:add']"
          >新增</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="['app:porkOtherProduce:remove']"
          >删除</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="porkOtherProduceList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="ID" align="center" prop="id" width="80" /> -->
      <el-table-column label="产品名称" align="center" prop="productName" />
      <el-table-column
        label="屠宰时间"
        align="center"
        prop="produceTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.produceTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="血码" align="center" prop="slaughterCode" />
      <el-table-column label="检疫证号" align="center" prop="animalCertNo" />
      <el-table-column label="供应商" align="center" prop="supplierName" />
      <el-table-column label="肉商" align="center" prop="purchaserName" />
      <el-table-column label="重量(kg)" align="center" prop="finalWeight" />
      <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="['app:porkOtherProduce:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['app:porkOtherProduce: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="'当前血码存在' + distributeList.length + '个可选择的批次'"
      :visible.sync="selectBatch"
      width="800px"
    >
      <el-row :gutter="20" style="height: 600px; overflow-y: scroll">
        <el-col :span="12" v-for="(item, i) in distributeList" :key="i">
          <el-descriptions
            :title="'信息-' + (i + 1)"
            direction="vertical"
            :column="4"
            border
          >
            <template slot="extra">
              <el-button type="primary" size="small" @click="selectThisBatch(i)"
                >选择</el-button
              >
            </template>
            <el-descriptions-item label="供应商">{{
              item.supplierName
            }}</el-descriptions-item>
            <el-descriptions-item label="肉商">{{
              item.purchaserName
            }}</el-descriptions-item>
            <el-descriptions-item label="血码" :span="2">{{
              item.slaughterCode
            }}</el-descriptions-item>
            <el-descriptions-item label="入场批次ID">
              {{ item.entranceBatchId }}
            </el-descriptions-item>
            <el-descriptions-item label="检疫证号">{{
              item.animalCertNo
            }}</el-descriptions-item>
          </el-descriptions>
        </el-col>
      </el-row>
    </el-dialog>
    <!-- 添加或修改红脏生产记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" :disabled="isView" label-width="120px">
        <el-form-item label="产品名称" prop="productName">
          <el-input
            v-model="form.productName"
            placeholder="请输入产品名称"
            disabled
          />
        </el-form-item>
        <el-form-item label="屠宰时间" prop="produceTime">
          <el-date-picker
            clearable
            v-model="form.produceTime"
            type="datetime"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择屠宰时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="血码" prop="slaughterCode">
          <el-select
            v-model="form.slaughterCode"
            filterable
            placeholder="请选择血码"
            @change="getDistribute()"
          >
            <el-option
              v-for="(item,i) in slaughterRelationOptions"
              :key="i"
              :label="item.slaughterCode"
              :value="item.slaughterCode"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="检疫证号" prop="animalCertNo">
          <el-input v-model="form.animalCertNo" placeholder="" disabled />
        </el-form-item>
        <el-form-item label="肉商" prop="purchaserName">
          <el-input v-model="form.purchaserName" placeholder="" disabled />
        </el-form-item>
        <el-form-item label="供应商" prop="supplierName">
          <el-input v-model="form.supplierName" placeholder="" disabled />
        </el-form-item>
        <SerialInput
          ref="SerialInputRef"
          :inputVal="form.scaleWeight"
          :disabled="isView"
          @confirm="confirmWeight"
        />
      </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 {
  listPorkOtherProduce,
  getPorkOtherProduce,
  delPorkOtherProduce,
  addPorkOtherProduce,
  updatePorkOtherProduce,
} from "@/api/app/porkOtherProduce";
import { getAllSlaughterRelation } from "@/api/app/slaughterRelation";
import { getValidDistributeBatch } from "@/api/app/distributeBatch";
import SerialInput from "@/components/weightSerial/index.vue";
export default {
  name: "PorkOtherProduce",
  components: {
    SerialInput,
  },
  data() {
    var validateNumber = (str) => {
      const regex =
        /^(?!0+\.00$)(?!.*\.\d{3,})(?:0?\.[1-9]\d?|0?\.0[1-9]|[1-9]\d{0,4}(?:\.\d{1,2})?)$/;
      const num = parseFloat(str);
      return regex.test(str) && num >= 0.01 && num <= 99999.99;
    };
    var valiWeight = (rule, value, callback) => {
      //包含小数的数字
      var msg = "范围(0.01~99999.99),两位小数";
      if (value && !validateNumber(value)) {
        callback(new Error(msg));
      } else {
        callback();
      }
    };
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 红脏生产记录表格数据
      porkOtherProduceList: [],
      slaughterRelationOptions: [],
      distributeList: [],
      // 弹出层标题
      title: "",
      isView:false,
      // 是否显示弹出层
      open: false,
      selectBatch: false,
      // 查询参数
      queryParams: {
        id: null,
        pageNum: 1,
        pageSize: 10,
        animalCertNo: null,
        produceTime: null,
        slaughterCode: null,
        productName: "红脏",
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        productName: [
          { required: true, message: "产品名称不能为空", trigger: "blur" },
        ],
        produceTime: [
          { required: true, message: "屠宰时间不能为空", trigger: "change" },
        ],
        hookNo: [
          { required: true, message: "吊钩号不能为空", trigger: "blur" },
        ],
        slaughterCode: [
          { required: true, message: "血码不能为空", trigger: "change" },
        ],
        supplierName: [
          { required: true, message: "供应商不能为空", trigger: "change" },
        ],
        purchaserName: [
          { required: true, message: "肉商不能为空", trigger: "change" },
        ],
        animalCertNo: [
          { required: true, message: "检疫证号不能为空", trigger: "change" },
        ],
        scaleWeight: [
          {
            required: true,
            message: "称显重量不能为空",
            trigger: "blur",
          },
          { validator: valiWeight, trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getSlaughterRelationOptions();
  },
  methods: {
    //确认重量，接入串口数据，确定该数据
    confirmWeight(val) {
      this.form.scaleWeight = val;
    },
    getDistribute() {
      this.$set(this.form, "distributeBatchId", null);
      this.$set(this.form, "entranceBatchId", null);
      this.$set(this.form, "purchaserName", null);
      this.$set(this.form, "supplierName", null);
      this.$set(this.form, "animalCertNo", null);

      if (!this.form.slaughterCode) {
        return;
      }
      let param = {
        slaughterCode: this.form.slaughterCode,
      };
      getValidDistributeBatch(param).then((response) => {
        this.distributeList = response.data ? response.data : [];
        if (this.distributeList.length == 1) {
          this.selectThisBatch(0);
        } else if (this.distributeList.length > 1) {
          this.selectBatch = true;
        }
      });
    },
    selectThisBatch(i) {
      let res = this.distributeList[i];
      if (res) {
        this.$set(this.form, "distributeBatchId", res.id);
        this.$set(this.form, "purchaserName", res.purchaserName);
        this.$set(this.form, "supplierName", res.supplierName);
        this.$set(this.form, "animalCertNo", res.animalCertNo);
        this.$set(this.form, "entranceBatchId", res.entranceBatchId);
      }
      this.selectBatch = false;
    },
    //血码清单
    getSlaughterRelationOptions() {
      getAllSlaughterRelation({}).then((response) => {
        this.slaughterRelationOptions = response.data;
      });
    },
    /** 查询生产记录列表 */
    getList() {
      this.loading = true;
      listPorkOtherProduce(this.queryParams).then((response) => {
        this.porkOtherProduceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        productName: "红脏",
        produceTime: this.parseTime(new Date()),
        slaughterCode: null,
        supplierName: null,
        purchaserName: null,
        animalCertNo: null,
        distributeBatchId: null,
        entranceBatchId: null,
        scaleWeight: null,
        finalWeight: 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;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.isView = false;
      this.title = "添加红脏生产记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getPorkOtherProduce(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.isView = false;
        this.title = "修改红脏生产记录";
      });
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.reset();
      const id = row.id || this.ids;
      getPorkOtherProduce(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.isView = true;
        this.title = "查看红脏生产记录";
      });
    },
    /** 提交按钮 */
   submitForm() {
      this.form.finalWeight = this.form.scaleWeight;
       this.$refs["form"].validate(async(valid) =>  {
        //检查重量是否输入
        const sonValid = await this.$refs.SerialInputRef.validateForm();
        if (valid && sonValid) {

              if (this.form.id != null) {
                updatePorkOtherProduce(this.form).then((response) => {
                  this.$modal.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                });
              } else {
                addPorkOtherProduce(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 delPorkOtherProduce(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "app/porkOtherProduce/export",
        {
          ...this.queryParams,
        },
        `porkOtherProduce_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
