<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="bindTime">
          <el-date-picker
            v-model="queryParams.bindTime"
            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="success"
          plain
          icon="el-icon-add"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['app:hookBind: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:hookBind:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="hookBindList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="绑定时间" align="center" prop="bindTime" width="180">
        <template slot-scope="scope">
          <span v-if="scope.row.bindTime">{{ parseTime(scope.row.bindTime) }}</span>
          <el-tag v-else type="info">待绑定</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="吊钩号" align="center" prop="hookNoList" min-width="240"/>
      <el-table-column label="数量" align="center" prop="total" width="120"/>
      <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" width="180" 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:hookBind:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['app:hookBind: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="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" :disabled="isView" label-width="80px">
        <el-form-item label="绑定时间" prop="bindTime"  v-if="isEdit">
          <el-date-picker
            v-model="form.bindTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="吊钩号" prop="hookNoListArr" >
          <!--改为手动选择识别的吊钩-->
          <!-- <el-input v-model="form.hookNoList" type="textarea" :disabled="isEdit" :rows="4" placeholder="请输入吊钩号" /> -->
          <el-select
            v-model="form.hookNoListArr"
            multiple
            filterable
            style="width:100%"
            placeholder="请选择吊钩"
            @change="changeHook"
            >
            <el-option
              v-for="(item,index) in validNFIDRecordOptions"
              :key="index"
              :label="item.hookNo"
              :value="item.hookNo">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数量" prop="hookTotal" disabled>
          <el-input :value="this.form.hookNoListArr?this.form.hookNoListArr.length:0" disabled />
        </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" disabled />
        </el-form-item>
        <el-form-item label="供应商" prop="supplierName">
          <el-input v-model="form.supplierName" disabled />
        </el-form-item>
        <el-form-item label="肉商" prop="purchaserName">
          <el-input v-model="form.purchaserName" 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 { listHookBindByBatch, getHookBind, delHookBind, addHookBindBatch, updateHookBind,updateHookBindBatch } from "@/api/app/hookBind";
import {getValidDistributeBatch} from "@/api/app/distributeBatch";
import { getAllSlaughterRelation } from "@/api/app/slaughterRelation";
import { listValidNFIDRecord } from "@/api/app/nfidReadRecord";
import { isEmpty } from "@/utils/validate"
export default {
  name: "HookBind",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 吊钩绑定表格数据
      hookBindList: [],
      //可绑定的批次
      distributeList:[],
      //
      slaughterRelationOptions:[],
      //可用的识别记录
      validNFIDRecordOptions:[],
      // 弹出层标题
      title: "",
      isView:false,
      // 是否显示弹出层
      open: false,
      selectBatch:false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        bindTime:null,
        slaughterCode: null,
        animalCertNo:null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        hookNoListArr: [
          { required: true, message: "吊钩号不能为空", trigger: "change" }
        ],
        slaughterCode: [
          { required: true, message: "血码不能为空", trigger: "change" }
        ],
        animalCertNo: [
          { required: true, message: "检疫证号不能为空", trigger: "change" }
        ],
      }
    };
  },
  computed: {
    //判断当前是修改还是新增
    isEdit:function() {
      return !isEmpty(this.form.batchNo);
    },
		// 计算两个周期值
		hookTotal: function () {
      console.log(this.form.hookNoListArr)
			return this.form.hookNoListArr?this.form.hookNoListArr.length:0;
		},
  },
  created() {
    this.getList();
    this.getSlaughterRelationOptions();
  },
  methods: {
    changeHook(v){
      this.$forceUpdate();
    },
    getSlaughterRelationOptions() {
      getAllSlaughterRelation({}).then((response) => {
        this.slaughterRelationOptions = response.data;
      });
    },
    getValidNFIDRecordOptions(hookNos){
      var param = {}
      if(hookNos && hookNos.length>0){
        param.hookNos = hookNos;
      }
      listValidNFIDRecord(param).then((response) => {
        this.validNFIDRecordOptions = response.data;
      });
    },
    /** 查询吊钩绑定列表 */
    getList() {
      this.loading = true;
      listHookBindByBatch(this.queryParams).then(response => {
        this.hookBindList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getDistribute(){
      this.$set(this.form, "distributeBatchId",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.selectBatch = false;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        batchNo:null,
        bindTime: null,
        hookNoList: null,
        hookNoListArr: null,
        slaughterCode:null,
        distributeBatchId:null,
        purchaserName:null,
        supplierName:null,
        animalCertNo:null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      // let ids = [];
      // selection.forEach(item => {
      //   let groupIdArr = isEmpty(item.groupId)?[]:item.groupId.split(",");
      //   ids.push(...groupIdArr)
      // });
      // this.ids = ids;
      this.ids = selection.map((item) => item.batchNo);
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.isView = false;
      this.title = "添加吊钩绑定";
      this.getValidNFIDRecordOptions([]);
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const batchNo = row.batchNo;

      getHookBind({batchNo:batchNo}).then(response => {
        this.form = response.data;
        this.form.hookNoListArr = this.form.hookNoList?this.form.hookNoList.split(","):[];
        this.getValidNFIDRecordOptions(this.form.hookNoListArr);
        if(isEmpty(this.form.bindTime)){
          this.form.bindTime = this.parseTime(new Date());
        }

        this.open = true;
        this.isView = false;
        this.title = "修改吊钩绑定";
      });
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.reset();
      const batchNo = row.batchNo;
      getHookBind({batchNo:batchNo}).then(response => {
        this.form = response.data;
        this.form.hookNoListArr = this.form.hookNoList?this.form.hookNoList.split(","):[];
        this.open = true;
        this.isView = true;
        this.title = "查看吊钩绑定";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.isEdit) {
            //this.form.groupIds = this.form.groupId.split(",")
            updateHookBindBatch(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addHookBindBatch(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = isEmpty(row.batchNo)?this.ids:row.batchNo;
      console.log(ids)
      this.$modal.confirm('是否确认删除该吊钩绑定数据项？').then(function() {
        return delHookBind(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('app/hookBind/export', {
        ...this.queryParams
      }, `hookBind_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
