<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="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"
          :disabled="disabled"
          v-hasPermi="['app:distributeBatch:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple || disabled"
          @click="handleDelete"
          v-hasPermi="['app:distributeBatch:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['app:distributeBatch:import']"
          >导入</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="distributeBatchList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="ID" align="center" prop="id" /> -->
      <el-table-column label="血码" align="center" prop="slaughterCode" />
      <el-table-column
        label="供应商"
        align="center"
        prop="supplier.supplierName"
      />
      <el-table-column
        label="肉商"
        align="center"
        prop="purchaser.purchaserName"
      />
      <el-table-column label="数量" align="center" prop="amount" />
      <el-table-column label="重量(kg)" align="center" prop="weight" />
      <el-table-column label="待宰圈号" align="center" prop="pigpenName" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            :disabled="disabled"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['app:distributeBatch:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            :disabled="disabled"
            @click="handleDelete(scope.row)"
            v-hasPermi="['app:distributeBatch: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="添加分销"
      :visible.sync="openBatch"
      width="940px"
      append-to-body
    >
      <el-form ref="batchForm" :model="batchForm" label-width="0px">
        <el-row class="mb20" :gutter="10">
          <el-col :span="5">
            <div><span style="color: #f00">* </span>血码</div>
          </el-col>
          <el-col :span="4">
            <div><span style="color: #f00">* </span>肉商</div>
          </el-col>
          <el-col :span="3">
            <div><span style="color: #f00">* </span>数量</div>
          </el-col>
          <el-col :span="5">
            <div>重量(kg)</div>
          </el-col>
          <el-col :span="3">
            <div>待宰圈</div>
          </el-col>
        </el-row>
        <el-row
          :gutter="10"
          v-for="(itemForm, i) in batchForm.distributeArr"
          :key="i"
        >
          <el-col :span="5">
            <el-form-item
              label=""
              :prop="'distributeArr.' + i + '.slaughterCode'"
              :rules="rules1"
            >
              <el-select
                v-model="itemForm.slaughterCode"
                filterable
                placeholder="请选择血码"
                @change="selectItem(i)"
              >
                <el-option
                  v-for="item in slaughterRelationOptions"
                  :key="item.slaughterCode"
                  :label="item.slaughterCode"
                  :value="item.slaughterCode"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item
              label=""
              :prop="'distributeArr.' + i + '.purchaserId'"
              :rules="rules2"
            >
              <el-select
                v-model="itemForm.purchaserId"
                disabled
                placeholder="请选择肉商"
              >
                <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-col :span="3">
            <el-form-item
              label=""
              :prop="'distributeArr.' + i + '.amount'"
              :rules="rules3"
            >
              <el-input
                v-model.number="itemForm.amount"
                placeholder="请输入"
                class="item-input"
              />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item
              label=""
              :prop="'distributeArr.' + i + '.weight'"
              :rules="rules4"
            >
              <el-input
                v-model="itemForm.weight"
                placeholder="请输入"
                class="item-input"
              />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="" :prop="'distributeArr.' + i + '.pigpenName'">
              <el-select
                v-model="itemForm.pigpenName"
                placeholder="请选择待宰圈"
              >
                <el-option
                  v-for="item in pigpenOptions"
                  :key="item.pigpenName"
                  :label="item.pigpenName"
                  :value="item.pigpenName"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-button
              class="item-add"
              type="primary"
              v-if="i == batchForm.distributeArr.length - 1"
              @click="addItem"
              ><i class="el-icon-plus"></i
            ></el-button>
            <el-button
              class="item-del"
              type="danger"
              v-if="i > 0 || batchForm.distributeArr.length > 1"
              @click="removeItem(i)"
              ><i class="el-icon-minus"></i
            ></el-button>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAddForm">确 定</el-button>
        <el-button @click="cancelBatch">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 修改分销批次对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="血码" prop="slaughterCode" disabled>
          <el-select
            v-model="form.slaughterCode"
            filterable
            placeholder="请选择血码"
            @change="selectForm"
          >
            <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="purchaserId">
          <el-select
            v-model="form.purchaserId"
            placeholder="请选择肉商"
            disabled
          >
            <el-option
              v-for="item in purchaserOptions"
              :key="item.id"
              :label="item.purchaserName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数量" prop="amount">
          <el-input v-model="form.amount" placeholder="请输入数量" />
        </el-form-item>
        <el-form-item label="重量(kg)" prop="weight">
          <el-input v-model="form.weight" placeholder="请输入重量" />
        </el-form-item>
        <el-form-item label="待宰圈号" prop="pigpenName">
          <el-select v-model="form.pigpenName" placeholder="请选择待宰圈">
            <el-option
              v-for="item in pigpenOptions"
              :key="item.pigpenName"
              :label="item.pigpenName"
              :value="item.pigpenName"
            ></el-option>
          </el-select>
        </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>

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>

        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listDistributeBatch,
  getDistributeBatch,
  delDistributeBatch,
  addDistributeBatchByBatch,
  updateDistributeBatch,
} from "@/api/app/distributeBatch";
import { getAllPurchaser } from "@/api/app/purchaser";
import { getAllSlaughterRelation } from "@/api/app/slaughterRelation";
import { getAllPigpen } from "@/api/app/pigpen";
import { getToken } from "@/utils/auth";
export default {
  name: "DistributeBatch",
  props: {
    entranceBatchId: {
      type: Number,
      default: 0,
    },
    supplierId: {
      type: Number,
      default: null,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  watch: {
    entranceBatchId: {
      handler(newVal, oldVal) {
        this.resetQueryParams();
        this.getList();
      },
      immediate: true,
    },
    supplierId: {
      handler(newVal, oldVal) {
        this.getSlaughterRelationOptions();
      },
      immediate: true,
    },
  },
  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();
      }
    };
    var valiAmount = (rule, value, callback) => {
      const regex = /^([1-9]\d{0,2})$/;
      if (
        !(regex.test(value) && parseInt(value) >= 1 && parseInt(value) <= 999)
      ) {
        callback(new Error("数量范围（1~999）"));
      } else {
        callback();
      }
    };
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 分销批次表格数据
      distributeBatchList: [],
      slaughterRelationOptions: [],
      purchaserOptions: [],
      pigpenOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openBatch: false,
      amount: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        entranceBatchId: this.entranceBatchId,
        slaughterCode: null,
      },
      // 导入参数
      upload: {
        // 是否显示弹出层（导入）
        open: false,
        // 弹出层标题（导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/app/distributeBatch/importData"
      },
      // 表单参数
      form: {},
      batchForm: {},
      // 表单校验
      rules: {
        slaughterCode: [
          {
            required: true,
            message: "血码不能为空",
            trigger: "change",
          },
        ],
        supplierId: [
          {
            required: true,
            message: "供应商不能为空",
            trigger: "change",
          },
        ],
        purchaserId: [
          {
            required: true,
            message: "肉商不能为空",
            trigger: "change",
          },
        ],
        amount: [
          {
            required: true,
            message: "数量不能为空",
            trigger: "blur",
          },
          { validator: valiAmount, trigger: "blur" },
        ],
        weight: [{ validator: valiWeight, trigger: "blur" }],
      },
      rules1: [
        {
          required: true,
          message: "血码不能为空",
          trigger: "change",
        },
      ],
      rules2: [
        {
          required: true,
          message: "肉商不能为空",
          trigger: "change",
        },
      ],
      rules3: [
        {
          required: true,
          message: "数量不能为空",
          trigger: "blur",
        },
        {
          type: "number",
          min: 1,
          max: 999,
          message: "范围（1~999）",
          trigger: "blur",
        },
      ],
      rules4: [{ validator: valiWeight, trigger: "blur" }],
    };
  },
  created() {
    this.getPurchaserOptions();
    this.getSlaughterRelationOptions();
    this.getPigpenOptions();
  },
  methods: {
    selectForm(value) {
      let select = this.slaughterRelationOptions.find(
        (item) => item.slaughterCode === value
      );
      //console.log(select)
      this.form.purchaserId = select.purchaserId;
      this.form.supplierId = select.supplierId;
      //console.log(this.batchForm)
    },
    selectItem(index) {
      var that = this;
      let select = this.slaughterRelationOptions.find(
        (item) =>
          item.slaughterCode ===
          that.batchForm.distributeArr[index].slaughterCode
      );
      //console.log(select)
      this.batchForm.distributeArr[index].purchaserId = select.purchaserId;
      this.batchForm.distributeArr[index].supplierId = select.supplierId;
      //console.log(this.batchForm)
    },
    addItem() {
      if (this.batchForm.distributeArr.length >= 10) {
        this.$modal.msgWarning("一次最多批量新增10条");
        return;
      }
      this.batchForm.distributeArr.push({
        slaughterCode: null,
        supplierId: null,
        purchaserId: null,
        amount: null,
        weight: null,
        pigpenName: null,
      });
    },
    removeItem(i) {
      this.batchForm.distributeArr.splice(i, 1);
    },
    /** 查询分销批次列表 */
    getList() {
      this.loading = true;
      listDistributeBatch(this.queryParams).then((response) => {
        this.distributeBatchList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getPigpenOptions() {
      getAllPigpen().then((response) => {
        this.pigpenOptions = response.data;
      });
    },
    getPurchaserOptions() {
      getAllPurchaser().then((response) => {
        this.purchaserOptions = response.data;
      });
    },
    getSlaughterRelationOptions() {
      let param = {
        supplierId: this.supplierId,
      };
      getAllSlaughterRelation(param).then((response) => {
        this.slaughterRelationOptions = response.data;
      });
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "导入"
      this.upload.open = true
    },
     // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true })
      this.getList()
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit()
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    cancelBatch() {
      this.openBatch = false;
      this.resetBatchForm();
    },
    resetQueryParams() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        entranceBatchId: this.entranceBatchId,
        slaughterCode: null,
      };
      this.resetForm("queryForm");
    },
    // 表单重置
    resetBatchForm() {
      this.batchForm = {
        entranceBatchId: this.entranceBatchId,
        distributeArr: [
          {
            slaughterCode: null,
            supplierId: null,
            purchaserId: null,
            amount: null,
            weight: null,
            pigpenName: null,
          },
        ],
      };
      this.resetForm("batchForm");
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        entranceBatchId: this.entranceBatchId,
        slaughterCode: null,
        supplierId: null,
        purchaserId: null,
        amount: null,
        weight: null,
        pigpenName: 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.resetBatchForm();
      //this.batchForm.entranceBatchId = this.queryParams.entranceBatchId;
      this.openBatch = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getDistributeBatch(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改分销批次";
      });
    },
    submitAddForm() {
      this.batchForm.distributeArr = this.batchForm.distributeArr.map(
        (item) => {
          item.entranceBatchId = this.batchForm.entranceBatchId;
          return item;
        }
      );
      this.$refs["batchForm"].validate((valid) => {
        if (valid) {
          console.log(this.batchForm);
          addDistributeBatchByBatch(this.batchForm).then((response) => {
            this.$modal.msgSuccess("批量新增成功");
            this.openBatch = false;
            this.getList();
          });
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateDistributeBatch(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDistributeBatch(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 delDistributeBatch(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "app/distributeBatch/export",
        {
          ...this.queryParams,
        },
        `distributeBatch_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
