<template>
  <div class="app-container">
    <el-form
      :model="mainQueryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
    >
      <el-form-item label="供应商名称" prop="supplierName">
        <el-input
          v-model="mainQueryParams.supplierName"
          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="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['app:slaughterRelation:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      ref="supplierTable"
      :data="supplierList"
      @selection-change="handleSelectionSupplierChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="供应商编号" align="center" prop="supplierNo" width="120" />
      <el-table-column label="供应商名称" align="center" prop="supplierName" />
      <el-table-column
        label="血码数量"
        align="center"
        prop="slaughterCodeSum"
      />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-order"
            @click="showCodeList(scope.row)"
            >血码配置清单</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="mainTotal > 0"
      :total="mainTotal"
      :page.sync="mainQueryParams.pageNum"
      :limit.sync="mainQueryParams.pageSize"
      @pagination="getSupplierCodeSumList"
    />
    <!--血码配置清单-->
    <el-dialog
      :title="`${listDialogTitle}-血码配置清单`"
      :visible.sync="openList"
      width="800px"
      append-to-body
    >
      <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:slaughterRelation: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:slaughterRelation:remove']"
            >删除</el-button
          >
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['app:slaughterRelation:export']"
            >导出</el-button
          >
        </el-col>
      </el-row>
      <el-table
        v-loading="loading"
        ref="codeTable"
        :data="slaughterRelationList"
        @selection-change="handleSelectionCodeChange"
      >
        <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="purchaser.purchaserName"
        />
        <el-table-column label="血码" align="center" prop="slaughterCode" />
        <el-table-column
          label="操作"
          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:region:edit']"
              >修改</el-button
            >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['app:region: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>
    <!-- 添加血码关系对话框 -->
    <el-dialog
      title="批量添加血码"
      :visible.sync="openBatch"
      width="800px"
      append-to-body
    >
    <!-- <el-alert
          class="mb20"
          title="血码编号格式：1位字母+3位数字"
          type="info"
          :closable="false"
          show-icon>
        </el-alert> -->
      <el-form
        ref="batchForm"
        :model="batchForm"
        :rules="batchRules"
        label-width="120px"
      >
        <el-form-item label="关联供应商" prop="supplierId">
          <el-select
            v-model="batchForm.supplierId"
            filterable
            placeholder="请选择关联供应商"
          >
            <el-option
              v-for="item in supplierOptions"
              :key="item.id"
              :label="item.supplierName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="血码关系">
          <el-row
            class="mb20"
            v-for="(itemForm, i) in batchForm.relationArr"
            :key="i"
          >
            <el-col :span="8">
              <el-form-item
                label=""
                :prop="'relationArr.' + i + '.purchaserId'"
                :rules="{
                  required: true,
                  message: '关联肉商不能为空',
                  trigger: 'blur',
                }"
              >
                <el-select
                  v-model="itemForm.purchaserId"
                  filterable
                  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="16">
              <el-form-item
                label=""
                :prop="'relationArr.' + i + '.slaughterCode'"
                :rules="[
                  {
                    required: true,
                    message: '血码编号不能为空',
                    trigger: 'blur',
                  },
                  /*{
                    pattern: /^[a-zA-Z0-9]{2,4}$/,
                    message: '血码编号格式输入错误',
                    trigger: 'blur',
                  },*/
                ]"
              >
                <el-input
                  v-model="itemForm.slaughterCode"
                  placeholder="请输入血码编号"
                  class="item-input"
                />
                <el-button
                  class="item-add"
                  type="primary"
                  v-if="i == batchForm.relationArr.length - 1"
                  @click="addItem"
                  ><i class="el-icon-plus"></i
                ></el-button>
                <el-button
                  class="item-del"
                  type="danger"
                  v-if="i > 0 || batchForm.relationArr.length > 1"
                  @click="removeItem(i)"
                  ><i class="el-icon-minus"></i
                ></el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form-item>
      </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" :disabled="isView" label-width="120px">
        <el-alert
          class="mb20"
          title="血码编号格式：1位字母+3位数字"
          type="info"
          :closable="false"
          show-icon>
        </el-alert>
        <el-form-item label="关联供应商" prop="supplierId">
          <el-select
            v-model="form.supplierId"
            filterable
            placeholder="请选择关联供应商"
          >
            <el-option
              v-for="item in supplierOptions"
              :key="item.id"
              :label="item.supplierName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="关联肉商" prop="purchaserId">
          <el-select
            v-model="form.purchaserId"
            filterable
            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-form-item label="血码" prop="slaughterCode">
          <el-input v-model="form.slaughterCode" placeholder="请输入血码编号" />
        </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 {
  listSlaughterRelation,
  supplierCodeSumList,
  getSlaughterRelation,
  delSlaughterRelation,
  addSlaughterRelation,
  addSlaughterRelationBatch,
  updateSlaughterRelation,
} from "@/api/app/slaughterRelation";
import { getAllSupplier } from "@/api/app/supplier";

import { getAllPurchaser } from "@/api/app/purchaser";

export default {
  name: "SlaughterRelation",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      exportParam: {
        ids: [],
        supplierIds: [],
      },
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0, //血码
      mainTotal: 0, //供应商
      supplierOptions: [],
      purchaserOptions: [],
      // 血码关系表格数据
      slaughterRelationList: [],
      //供应商血码数量数据
      supplierList: [],
      // 弹出层标题
      title: "",
      listDialogTitle: "",
      isView:false,
      // 是否显示弹出层
      open: false,
      openList: false,
      openBatch: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        supplierId: null,
      },
      //
      mainQueryParams: {
        pageNum: 1,
        pageSize: 10,
        slaughterName: null,
      },
      selectSupplierId: null,
      // 表单参数
      form: {},

      batchForm: {
        supplierId: null,
        relationArr: [
          {
            purchaserId: null,
            slaughterCode: null,
          },
        ],
      },
      // 表单校验
      rules: {
        slaughterCode: [
          { required: true, message: "血码编号不能为空", trigger: "blur" },
          /*{
            pattern: /^[a-zA-Z0-9]{2,4}$/,
            message: "血码编号格式输入错误",
            trigger: "blur",
          },*/
        ],
        supplierId: [
          { required: true, message: "关联供应商不能为空", trigger: "blur" },
        ],
        purchaserId: [
          { required: true, message: "关联肉商不能为空", trigger: "blur" },
        ],
      },
      batchRules: {
        supplierId: [
          { required: true, message: "关联供应商不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getSupplierCodeSumList();
    this.getSupplierOptions();
    this.getPurchaserOptions();
    console.log(this.batchForm);
  },
  methods: {
    addItem() {
      if (this.batchForm.relationArr.length >= 10) {
        this.$modal.msgWarning("一次最多批量新增10条");
        return;
      }
      this.batchForm.relationArr.push({
        name: "",
      });
    },
    removeItem(i) {
      this.batchForm.relationArr.splice(i, 1);
    },
    //打开血码配置清单
    showCodeList(row) {
      this.listDialogTitle = row.supplierName;
      this.queryParams.supplierId = row.id;
      this.$refs.supplierTable.clearSelection();
      this.$refs.supplierTable.toggleRowSelection(row);

      this.getList();
      this.openList = true;
    },
    /** 查询血码关系列表 */
    getList() {
      this.loading = true;
      listSlaughterRelation(this.queryParams).then((response) => {
        this.slaughterRelationList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getSupplierOptions() {
      getAllSupplier().then((response) => {
        this.supplierOptions = response.data;
      });
    },
    getPurchaserOptions() {
      getAllPurchaser().then((response) => {
        this.purchaserOptions = response.data;
      });
    },
    getSupplierCodeSumList() {
      this.loading = true;
      supplierCodeSumList(this.mainQueryParams).then((response) => {
        this.supplierList = response.rows;
        this.mainTotal = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    cancelBatch() {
      this.openBatch = false;
      this.resetBatchForm();
    },
    // 表单重置
    resetBatchForm() {
      this.batchForm = {
        supplierId: null,
        relationArr: [
          {
            purchaserId: null,
            slaughterCode: null,
          },
        ],
      };
      this.resetForm("batchForm");
    },
    reset() {
      this.form = {
        id: null,
        supplierId: null,
        purchaserId: null,
        slaughterCode: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getSupplierCodeSumList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    //选中供应商
    handleSelectionSupplierChange(selection) {
      this.exportParam.supplierIds = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    //选中血码
    handleSelectionCodeChange(selection) {
      this.exportParam.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.getSupplierOptions();
      this.getPurchaserOptions();
      this.resetBatchForm();
      this.batchForm.supplierId = this.queryParams.supplierId;
      this.openBatch = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getSupplierOptions();
      this.getPurchaserOptions();
      const id = row.id || this.exportParam.ids;
      getSlaughterRelation(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.isView = false;
        this.title = "修改血码关系";
      });
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.reset();
      this.getSupplierOptions();
      this.getPurchaserOptions();
      const id = row.id || this.exportParam.ids;
      getSlaughterRelation(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.isView = true;
        this.title = "查看血码关系";
      });
    },
    /** 提交按钮 */
    submitAddForm() {
      this.$refs["batchForm"].validate((valid) => {
        if (valid) {
          console.log(this.batchForm);
          addSlaughterRelationBatch(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) {
            updateSlaughterRelation(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            // addSlaughterRelation(this.form).then((response) => {
            //   this.$modal.msgSuccess("新增成功");
            //   this.open = false;
            //   this.getList();
            // });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.exportParam.ids;
      this.$modal
        .confirm('是否确认删除血码关系编号为"' + ids + '"的数据项？')
        .then(function () {
          return delSlaughterRelation(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "app/slaughterRelation/export",
        {
          ...this.exportParam,
        },
        `slaughterRelation_${new Date().getTime()}.xlsx`
      );
      this.exportParam = {
        ids: [],
        supplierIds: [],
      };
      //清除选中状态
      this.$refs.supplierTable.clearSelection();
      this.$refs.codeTable.clearSelection();
    },
  },
};
</script>
<style scoped>
.item-input {
  width: 180px;
  margin-left: 10px;
}
.item-add {
  margin-left: 10px;
}
.item-del {
  margin-left: 10px;
}
</style>
