<template>
  <div>
    <el-form
      :model="tempInfo"
      ref="planForm"
      label-width="237px"
      class="grid-form-class"
    >
      <div class="common-card">
        <h3>基本信息</h3>

        <div class="form-body">
          <div class="flex-css">
            <el-form-item label="申领单位" prop="orgId" :rules="rules.required">
              <el-input v-model="tempInfo.orgId" placeholder="请输入申领单位" />
            </el-form-item>
            <el-form-item label="申领人" prop="docmker" :rules="rules.required">
              <el-input v-model="tempInfo.docmker" placeholder="请输入申领人" />
            </el-form-item>
          </div>
        </div>
      </div>

      <!--列表-->
      <div class="common-card">
        <h3>药品明细</h3>
        <div class="right-type">
          <el-button
            class="lake-Blue"
            type="primary"
            icon="el-icon-plus"
            @click="handleAdd()"
            >添加药品
          </el-button>
        </div>
        <el-table
          id="listId"
          v-loading="listLoading"
          element-loading-text="加载中"
          :data="tempInfo.detlList"
          fit
          border
          :span-method="objectSpanMethod"
        >
          <template slot="empty">
            <img src="@/assets/nopage.png" alt />
            <p>暂无数据</p>
          </template>
          <el-table-column
            fixed
            type="index"
            label="序号"
            width="60"
          ></el-table-column>
          <el-table-column label="药品编码" prop="drugListId" width="150" />
          <el-table-column label="药品信息" min-width="300">
            <template slot-scope="scope">
              <div class="drug-name">
                <el-tag v-if="scope.row.drugName">
                  {{ scope.row.drugName }}
                </el-tag>
                {{ "【" + scope.row.dosformName + "】" }}
                <el-tag v-if="scope.row.essdrugType">
                  {{
                    scope.row.essdrugType === "0"
                      ? "非基药"
                      : scope.row.essdrugType === "1"
                      ? "基药"
                      : scope.row.essdrugType
                  }}
                </el-tag>
                <br />
                {{ "生产厂家 【" + scope.row.prodentpName + "】" }}
                <br />
                {{
                  "药品规格 【" +
                  scope.row.specName +
                  "*" +
                  scope.row.convrat +
                  scope.row.prepunt +
                  "/" +
                  scope.row.pacUnt +
                  "】"
                }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="包装单位" prop="pacUnt" width="150" />
          <el-table-column label="出库数量" width="150">
            <template #header>
              <span style="color: red; margin-right: 4px">*</span>
              <span>出库数量</span>
            </template>
            <template slot-scope="scope">
              <el-form-item
                label-width="0"
                :prop="'detlList.' + scope.$index + '.stoWaitCnt'"
                :rules="rules.InterNum"
              >
                <el-input
                  v-model="scope.row.stoWaitCnt"
                  placeholder="请输入"
                ></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="批号" prop="lotNum" width="150" />
          <el-table-column label="效期" prop="prodExpy" width="150" />
          <el-table-column label="生产厂商" prop="prodentpName" width="150" />
          <el-table-column label="当前库存" prop="invCnt" width="150" />
          <el-table-column fixed="right" label="操作" width="100">
            <template slot-scope="scope">
              <el-button
                class="red"
                type="text"
                @click="handleDelete(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="foot-button">
        <el-button type="info" @click="goback">返回</el-button>
        <el-button type="primary" @click="save()" :loading="saveLoading"
          >提交
        </el-button>
      </div>
    </el-form>

    <!--添加药品-->
    <el-dialog
      title="选择药品"
      :visible.sync="dialogDrugFormVisible"
      width="1200px"
    >
      <!--条件-->
      <el-form :model="drugListQuery" ref="queryForm" :inline="true">
        <el-form-item label="药品信息">
          <el-input
            v-model="drugListQuery.drugInfo"
            placeholder="请输入药品名称/编码/生产企业"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getDrugData('search')"
            >查询
          </el-button>
          <el-button @click="drugReset()">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table
        ref="drugTable"
        v-loading="drugListLoading"
        row-key="drugListId"
        element-loading-text="加载中"
        :data="drugList"
        fit
        stripe
        border
        @selection-change="handleSelectionChange"
      >
        <template slot="empty">
          <img src="@/assets/nopage.png" alt />
          <p>暂无数据</p>
        </template>
        <el-table-column
          type="selection"
          :selectable="selected"
          :reserve-selection="true"
          width="55"
        >
        </el-table-column>
        <el-table-column
          fixed
          type="index"
          label="序号"
          width="60"
        ></el-table-column>
        <el-table-column label="药品编码" prop="drugListId" width="150" />
        <el-table-column label="药品名称" min-width="300">
          <template slot-scope="scope">
            <div class="drug-name">
              <el-tag v-if="scope.row.drugName">
                {{ scope.row.drugName }}
              </el-tag>
              {{ "【" + scope.row.dosformName + "】" }}
              <el-tag v-if="scope.row.essdrugType">
                {{
                  scope.row.essdrugType === "0"
                    ? "非基药"
                    : scope.row.essdrugType === "1"
                    ? "基药"
                    : scope.row.essdrugType
                }}
              </el-tag>
              <br />
              {{ "生产厂家 【" + scope.row.prodentpName + "】" }}
              <br />
              {{
                "药品规格 【" +
                scope.row.specName +
                "*" +
                scope.row.convrat +
                scope.row.prepunt +
                "/" +
                scope.row.pacUnt +
                "】"
              }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="剂型" width="100" prop="dosformName" />
        <el-table-column label="规格信息" width="100" prop="specName" />
        <el-table-column label="包装单位" width="80" prop="pacUnt" />
        <el-table-column label="当前库存" width="80" prop="invCnt" />
        <el-table-column label="生产企业" width="150" prop="prodentpName" />
      </el-table>

      <!--分页-->
      <yl-pagination
        v-show="drugTotal > 0"
        :total="drugTotal"
        :page.sync="drugListQuery.current"
        :limit.sync="drugListQuery.size"
        @pagination="getDrugData"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogDrugFormVisible = false">取消</el-button>
        <el-button type="primary" @click="commitData()"> 确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import ylPagination from "@/components/yl-pagination";
import rules from "@/utils/rules";
import {
  handStoout,
  getDrugList,
  getDrugInvRtList
} from "@/api/storeroom/shipped-out";
export default {
  components: { ylPagination },
  data() {
    return {
      saveLoading: false,
      amount: {
        num: 0,
        price: 0
      },
      // 药品多选
      selectData: [],
      rules,
      listLoading: false,
      // 添加药品
      drugListLoading: false,
      drugListQuery: {
        //条件查询
        current: 1,
        size: 10,
        drugInfo: ""
      },
      drugTotal: 0, //分页
      drugList: [],
      dialogDrugFormVisible: false,
      tempInfo: {
        orgId: "",
        docmker: "",
        detlList: []
      }
    };
  },

  created() {},

  methods: {
    goback() {
      this.$router.go(-1);
    },

    // 筛选合并项
    computeCell(tableData) {
      this.cellList = [];
      this.count = null;
      for (let i = 0; i < tableData.length; i++) {
        if (i == 0) {
          // 先设置第一项
          this.cellList.push(1); // 初为1，若下一项和此项相同，就往cellList数组中追加0
          this.count = 0;
        } else {
          // 判断当前项与上项的设备类别是否相同，因为是合并这一列的单元格
          if (tableData[i].drugListId == tableData[i - 1].drugListId) {
            this.cellList[this.count] += 1; // 增加计数
            this.cellList.push(0); // 相等就往cellList数组中追加0
          } else {
            this.cellList.push(1); // 不等就往cellList数组中追加1
            this.count = i; // 将索引赋值为计数
          }
        }
      }
    },

    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (
        columnIndex === 1 ||
        columnIndex === 2 ||
        columnIndex === 3 ||
        columnIndex === 8 ||
        columnIndex === 9 ||
        columnIndex === 10
      ) {
        // console.log("单元格数组，若下一项为0，则代表合并上一项", this.cellList);
        const rowCell = this.cellList[rowIndex];
        if (rowCell > 0) {
          const colCell = 1;
          // console.log(`动态竖向合并单元格, 第${colCell}列，竖向合并${rowCell}个单元格 `);
          return {
            rowspan: rowCell,
            colspan: colCell
          };
        } else {
          // 清除原有的单元格，必须要加，否则就会出现单元格会被横着挤到后面了！！！
          // 本例中数据是写死的不会出现，数据若是动态后端获取的，就会出现了！！！
          return {
            rowspan: 0,
            colspan: 0
          };
        }
      }
    },

    // 复选框禁用
    selected(row) {
      if (
        this.tempInfo.detlList.some((item) => {
          return item.drugListId === row.drugListId;
        })
      ) {
        return false;
      } else {
        return true;
      }
    },

    // 新增目录 多选
    handleSelectionChange(val) {
      this.selectData = val;
    },
    // 计划类型发生改变时
    handleChange(val) {
      this.tempInfo.planPrd = "";
    },

    // 删除
    handleDelete(row) {
      const index = this.tempInfo.detlList.indexOf(row);
      this.tempInfo.detlList.splice(index, 1);
      this.$refs.planForm.clearValidate("detlList." + index + ".stoWaitCnt");
    },

    // 添加药品
    handleAdd() {
      this.dialogDrugFormVisible = true;
      this.$nextTick(() => {
        if (this.$refs.drugTable) {
          this.$refs.drugTable.clearSelection();
          this.selectData = [];
        }
      });
      this.getDrugData();
    },

    //新增药品列表
    getDrugData(type) {
      if (type == "search") {
        this.drugListQuery.current = 1;
      }
      this.drugListLoading = true;
      getDrugList(this.drugListQuery)
        .then((response) => {
          this.drugList = response.data.records;
          this.drugTotal = response.data.total;
          this.drugListLoading = false;
        })
        .catch((err) => {
          this.drugListLoading = false;
        });
    },

    // 重置药品列表
    drugReset() {
      this.drugListQuery.drugInfo = "";
      this.getDrugData();
    },

    // 添加药品确认
    commitData() {
      let ids = [];
      this.selectData.forEach((item) => {
        ids.push(item.drugListId);
      });
      this.dialogDrugFormVisible = false;
      getDrugInvRtList({ drugListIdList: ids })
        .then((response) => {
          this.tempInfo.detlList.push(...response.data);
          this.computeCell(this.tempInfo.detlList);
          this.listLoading = false;
        })
        .catch((err) => {
          this.listLoading = false;
        });
    },

    // 保存
    save() {
      this.$refs["planForm"].validate((valid) => {
        if (valid) {
          this.$confirm("确认保存", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
            .then(() => {
              this.saveLoading = true;
              handStoout(this.tempInfo)
                .then((response) => {
                  this.$message({
                    message: "保存成功",
                    type: "success"
                  });
                  this.saveLoading = false;
                  this.$router.push({
                    path: "/purchasing-management/plan-template-maintenance"
                  });
                })
                .catch((err) => {
                  this.saveLoading = false;
                });
            })
            .catch(() => {
              this.saveLoading = false;
            });
        }
      });
    }
  }
};
</script>

<style scoped lang="scss">
::v-deep #listId {
  th.el-table__cell.is-leaf,
  td.el-table__cell {
    border-bottom: 1px solid #dfe6ec;
  }
}
</style>