<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="检疫证号" prop="animalCertNo">
        <el-input
          v-model="queryParams.animalCertNo"
          placeholder="请输入检疫证号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="屠宰时间" prop="produceTime">
        <el-date-picker clearable
          v-model="queryParams.produceTime"
          type="date"
          value-format="yyyy-MM-dd HH:mm:ss"
          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>
        <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="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['app:porkSideProduce: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="['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="hookNo" />
      <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="吊钩类型" align="center" prop="hookName" />
      <el-table-column label="吊钩扣重" align="center" prop="hookWeight" />
      <el-table-column label="干损重量" align="center" prop="dryLossWeight" />
      <el-table-column label="宰后重量" align="center" prop="finalWeight" />
      <el-table-column label="操作" fixed="right" 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="['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="'当前血码存在'+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="item">
          <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" label-width="80px">
        <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"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择生产时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="吊钩号" prop="hookNo">
          <el-input v-model="form.hookNo" placeholder="请输入吊钩号" @blur="fillInput" />
        </el-form-item>
        <el-form-item label="血码" prop="slaughterCode">
          <el-select
                v-model="form.slaughterCode"
                filterable
                placeholder="请选择血码"
                @change="getDistribute()"
              >
                <el-option
                  v-for="item in slaughterRelationOptions"
                  :key="item.slaughterCode"
                  :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>
        <el-form-item label="吊钩类型" prop="hookName">
          <el-select
                v-model="form.hookName"
                filterable
                placeholder="请选择吊钩类型"
                @change="getHookType"
              >
                <el-option
                  v-for="item in hookOptions"
                  :key="item.hookName"
                  :label="item.hookName"
                  :value="item.hookName"
                ></el-option>
              </el-select>
        </el-form-item>
        <el-form-item label="吊钩扣重" prop="hookWeight">
          <el-input v-model="form.hookWeight" placeholder="请输入吊钩扣重" @change="caclutateWeight" style="width: 300px;" disabled />
        </el-form-item>
        <SerialInput :inputVal="form.scaleWeight" @confirm="confirmWeight"/>

        <!-- <el-form-item label="称显重量" prop="scaleWeight">
          <el-input v-model="form.scaleWeight" placeholder="请输入称显重量" @change="caclutateWeight" style="width: 300px;"/>
          <el-button class="ml20" type="primary" size="small" @click="confirmWeight">获取</el-button>
        </el-form-item> -->
        <el-form-item label="干损重量" prop="dryLossWeight">
          <el-input v-model="form.dryLossWeight" disabled style="width: 300px;" />
          <span style="color:#f00;margin-left:20px">【当前干损比为：{{ this.dryLossRatio }}%】</span>
        </el-form-item>
        <el-form-item label="宰后重量" prop="finalWeight">
          <el-input v-model="form.finalWeight" style="width: 300px;" disabled />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPorkSideProduce, getPorkSideProduce, delPorkSideProduce, addPorkSideProduce, updatePorkSideProduce } from "@/api/app/porkSideProduce";
import {getHookBindDetail} from "@/api/app/hookBind";
import {getValidDistributeBatch} from "@/api/app/distributeBatch";
import {getAllHook} from "@/api/app/hook";
import { getAllSlaughterRelation } from "@/api/app/slaughterRelation";
import { getNowRatio } from "@/api/app/dryLossRatio";
import SerialInput from '@/components/weightSerial/index.vue'
export default {
  name: "PorkSideProduce",
  components:{
    SerialInput
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 白条生产记录表格数据
      porkSideProduceList: [],
      hookOptions:[],
      slaughterRelationOptions:[],
      distributeList:[],
      dryLossRatio:0,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      selectBatch:false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        animalCertNo: null,
        produceTime: null,
        slaughterCode: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        productName: [
          { required: true, message: "产品名称不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getHookOptions();
    this.getSlaughterRelationOptions();

  },
  methods: {
    handleSerialRead(str) {
            console.log(str)
        },
        handleSerialLog(data) {
            console.log(data)
        },
        handleStatusMsg(data) {
            this.serialMsg = data
        },
    //确认重量，接入串口数据，确定该数据
    confirmWeight(val){
      this.form.scaleWeight = val;
      this.caclutateWeight();
    },
    //计算数量
    caclutateWeight(){
      this.form.dryLossWeight = this.form.scaleWeight * this.dryLossRatio / 100;
      this.form.dryLossWeight = this.form.dryLossWeight.toFixed(2);
      this.form.finalWeight = this.form.scaleWeight - this.form.hookWeight;//减去吊钩重量
      this.form.finalWeight = this.form.finalWeight - this.form.dryLossWeight>0?this.form.finalWeight - this.form.dryLossWeight:0;//减去干损重量
      this.form.finalWeight = this.form.finalWeight.toFixed(2)
    },
    //获取当前干损比
    getRatio(){
      getNowRatio().then(response => {
        if(response.data){
          this.dryLossRatio = response.data.dryLossRatio?response.data.dryLossRatio:0;
        }
      })
    },
    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;
    },
    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();
    },
    //使用失焦事件模拟识别的吊钩
    fillInput(){
      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)
      this.$set(this.form, "slaughterCode",null)
      if(!this.form.hookNo){
        return;
      }
      getHookBindDetail(this.form.hookNo).then(response => {
        if(response.data){
          let data = response.data;
          this.$set(this.form, "distributeBatchId",data.distributeBatchId)
          this.$set(this.form, "entranceBatchId",data.entranceBatchId)
          this.$set(this.form, "purchaserName",data.purchaserName)
          this.$set(this.form, "supplierName",data.supplierName)
          this.$set(this.form, "animalCertNo",data.animalCertNo)
          this.$set(this.form, "slaughterCode",data.slaughterCode)
        }
      })
    },
    //血码清单
    getSlaughterRelationOptions() {
      getAllSlaughterRelation({}).then((response) => {
        this.slaughterRelationOptions = response.data;
      });
    },
    /** 查询吊钩清单 */
    getHookOptions() {
      getAllHook().then(response => {
        this.hookOptions = response.data;
      });
    },
    /** 查询白条生产记录列表 */
    getList() {
      this.loading = true;
      listPorkSideProduce(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,
        hookNo: null,
        slaughterCode: null,
        supplierName:null,
        purchaserName:null,
        animalCertNo:null,
        distributeBatchId: null,
        entranceBatchId: null,
        hookName: null,
        hookWeight: null,
        scaleWeight: null,
        dryLossWeight: null,
        finalWeight: null,
      };
      this.resetForm("form");
      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.open = true;
      this.title = "添加白条生产记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getPorkSideProduce(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改白条生产记录";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updatePorkSideProduce(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPorkSideProduce(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 delPorkSideProduce(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('app/porkSideProduce/export', {
        ...this.queryParams
      }, `porkSideProduce_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
