<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"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          placeholder="请选择屠宰时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="肉商" prop="keyword">
        <el-input
          v-model="queryParams.keyword"
          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:porkSideProduce: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:porkSideProduce:remove']"
          >删除</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="porkSideProduceList"
      @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="purchaserName" />
      <el-table-column label="吊钩类型" align="center" prop="hookName">
        <template slot-scope="scope">
          <span>{{ showValue(scope.row.hookName) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="吊钩扣重(kg)" align="center" prop="hookWeight">
        <template slot-scope="scope">
          <span>{{ showValue(scope.row.hookWeight) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="干损重量(kg)" align="center" prop="dryLossWeight">
        <template slot-scope="scope">
          <span>{{ showValue(scope.row.dryLossWeight) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="宰后重量(kg)" align="center" prop="finalWeight">
        <template slot-scope="scope">
          <span>{{ showValue(scope.row.finalWeight) }}</span>
        </template>
      </el-table-column>
      <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:porkSideProduce:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['app:porkSideProduce: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="800px" append-to-body>
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        :disabled="isView"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="产品名称" prop="productName">
              <el-input
                v-model="form.productName"
                placeholder="请输入产品名称"
                disabled
                style="width: 240px;"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <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="请选择生产时间"
                style="width: 240px;"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="肉商" prop="purchaserId">
             <el-select
                  v-model="form.purchaserId"
                  filterable
                  placeholder="请选择肉商"
                   style="width: 240px;"
                >
                  <el-option
                    v-for="item in purchaserOptions"
                    :key="item.id"
                    :label="item.purchaserName"
                    :value="item.id"
                  ></el-option>
                </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="吊钩类型" prop="hookName">
              <el-radio-group v-model="form.hookName" @input="getHookType">
                <el-radio
                  v-for="(item, i) in hookOptions"
                  :key="i"
                  :label="item.hookName"
                  border
                  >{{ item.hookName }}</el-radio
                >
              </el-radio-group>
              <!-- <el-select
                v-model="form.hookName"
                filterable
                placeholder="请选择吊钩类型"
                @change="getHookType"
                style="width: 240px;"
              >
                <el-option
                  v-for="item in hookOptions"
                  :key="item.hookName"
                  :label="item.hookName"
                  :value="item.hookName"
                ></el-option>
              </el-select> -->
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="吊钩扣重(kg)" prop="hookWeight">
              <el-input
                v-model="form.hookWeight"
                placeholder="请输入吊钩扣重"
                @change="caclutateWeight"
                style="width: 240px"
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>

        <SerialInput
          :inputVal="form.scaleWeight"
          :type="1"
          ref="SerialInputRef"
          :disabled="isView"
          @confirm="confirmWeight"
        />

        <el-form-item label="干损重量(kg)" prop="dryLossWeight">
          <el-input
            v-model="form.dryLossWeight"
            disabled
             style="width: 240px;"
          />
          <span style="color: #f00; margin-left: 20px"
            >【当前干损比为：{{ this.dryLossRatio }}%】</span
          >
        </el-form-item>
        <el-form-item label="宰后重量(kg)" prop="finalWeight">
          <el-input v-model="form.finalWeight" class="large-input" style="width: 240px;" disabled />
        </el-form-item>
      </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 {
  listPorkSideProduceRecord,
  getPorkSideProduceRecord,
  delPorkSideProduceRecord,
  addPorkSideProduceRecord,
  updatePorkSideProduceRecord,
} from "@/api/app/porkSideProduceRecord";
import { getAllHook } from "@/api/app/hook";
import { getNowRatio } from "@/api/app/dryLossRatio";
import { getAllPurchaser } from "@/api/app/purchaser";
import SerialInput from "@/components/weightSerial/index.vue";
export default {
  name: "PorkSideProduceRecord",
  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,
      // 白条生产记录表格数据
      porkSideProduceList: [],
      hookOptions: [],
      purchaserOptions: [],
      dryLossRatio: 0,
      regexRule:
        /^(?!0+\.00$)(?!.*\.\d{3,})(?:0?\.[1-9]\d?|0?\.0[1-9]|[1-9]\d{0,4}(?:\.\d{1,2})?)$/,
      // 弹出层标题
      title: "",
      isView: false,
      // 是否显示弹出层
      open: false,
      selectBatch: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        produceTime: null,
        keyword:null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        productName: [
          { required: true, message: "产品名称不能为空", trigger: "blur" },
        ],
        produceTime: [
          { required: true, message: "屠宰时间不能为空", trigger: "change" },
        ],
        purchaserId: [
          { required: true, message: "肉商不能为空", trigger: "change" },
        ],
        hookName: [
          { required: true, message: "吊钩类型不能为空", trigger: "change" },
        ],
        hookWeight: [
          { required: true, message: "吊钩类型不能为空", trigger: "change" },
        ],
        scaleWeight: [
          {
            required: true,
            message: "称显重量不能为空",
            trigger: "blur",
          },
          { validator: valiWeight, trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getHookOptions();
    this.getPurchaserOptions();
  },
  methods: {
    //空值显示 -
    showValue(value) {
      return value != null ? value : "-";
    },
    handleSerialRead(str) {
      console.log(str);
    },
    handleSerialLog(data) {
      console.log(data);
    },
    handleStatusMsg(data) {
      this.serialMsg = data;
    },
    //确认重量，接入串口数据，确定该数据
    confirmWeight(val) {
      this.form.scaleWeight = val;
      this.caclutateWeight();
    },
    //设置默认吊钩
    setDefaultHook(){
      this.hookOptions.forEach((item)=>{
          if(item.defaultFlag){
            console.log(item)
            this.$set(this.form, "hookName", item.hookName);
            this.$set(this.form, "hookWeight", item.hookWeight);
            this.caclutateWeight();
          }
        })
    },
    //计算数量
    caclutateWeight() {
      console.log("计算数量")
      let finalWeight =
        this.form.scaleWeight - this.form.hookWeight > 0
          ? this.form.scaleWeight - this.form.hookWeight
          : 0; //称的重量-挂钩重量
      let dryLossWeight = (finalWeight * this.dryLossRatio) / 100; //（称的重量-挂钩重量）*干损比例
      this.form.dryLossWeight = dryLossWeight.toFixed(2);
      //（称的重量-挂钩重量）-（称的重量-挂钩重量）*干损比例
      finalWeight =
        finalWeight - this.form.dryLossWeight > 0
          ? finalWeight - this.form.dryLossWeight
          : 0; //减去干损重量
      this.form.finalWeight = finalWeight.toFixed(2);
    },
    //获取当前干损比
    getRatio() {
      getNowRatio().then((response) => {
        if (response.data) {
          this.dryLossRatio = response.data.dryLossRatio
            ? response.data.dryLossRatio
            : 0;
        }
      });
    },
    getHookType(value) {
      let select = this.hookOptions.find((item) => item.hookName === value);
      //console.log(value);
      this.$set(this.form, "hookWeight", select ? select.hookWeight : null);
      this.caclutateWeight();
    },
    getPurchaserOptions() {
      getAllPurchaser().then((response) => {
        this.purchaserOptions = response.data;
      });
    },
    /** 查询吊钩清单 */
    getHookOptions() {
      getAllHook().then((response) => {
        this.hookOptions = response.data;

      });
    },
    /** 查询白条生产记录列表 */
    getList() {
      this.loading = true;
      listPorkSideProduceRecord(this.queryParams).then((response) => {
        this.porkSideProduceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        productName: "白条",
        produceTime: null,
        purchaserId: null,
        hookName: null,
        hookWeight: null,
        scaleWeight: null,
        dryLossWeight: null,
        finalWeight: null,
      };
      this.resetForm("form");
      this.setDefaultHook();
      this.getRatio();
    },
    /** 搜索按钮操作 */
    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.form.produceTime = this.parseTime(new Date());
      this.open = true;
      this.isView = false;
      this.title = "添加白条生产记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getPorkSideProduceRecord(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.isView = false;
        this.title = "修改白条生产记录";
        //是否需要设置默认吊钩
        if(this.form.hookName == null && this.form.hookWeight==null){
          this.setDefaultHook();
        }
      });
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.reset();
      const id = row.id || this.ids;
      getPorkSideProduceRecord(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.isView = true;
        this.title = "查看白条生产记录";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(async (valid) => {
        //检查重量是否输入
        const sonValid = this.$refs.SerialInputRef
          ? await this.$refs.SerialInputRef.validateForm()
          : true;
        if (valid && sonValid) {
          if (this.form.id != null) {
            updatePorkSideProduceRecord(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPorkSideProduceRecord(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 delPorkSideProduceRecord(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
  },
};
</script>
<style>
/* 样式保持不变 */
.large-input {
  font-size: 32px;
  width: 300px;
}
.large-input > .el-input__inner {
  height: 60px;
  line-height: 60px;
}
</style>
