<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px">
      <el-form-item label="" prop="drugsName">
        <el-input
          v-model="queryParams.drugsName"
          placeholder="请输入药品名称"
          clearable
          size="small"
          style="width:140px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="" prop="drugsType">
        <el-select
          v-model="queryParams.drugsType"
          placeholder="请选择药品分类"
          clearable
          size="small"
          style="width:140px"
        >
          <el-option
            v-for="item in drugsTypeArr"
            :key="item.dictValue"
            :value="item.dictValue"
            :label="item.dictLabel"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="" prop="drugsSpecsType">
        <el-select
          v-model="queryParams.drugsSpecsType"
          placeholder="请选择中药类型"
          clearable
          size="small"
          style="width:140px"
        >
          <el-option
            v-for="item in chinesMedicineTypeArr"
            :key="item.dictValue"
            :value="item.dictValue"
            :label="item.dictLabel"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="" prop="costType">
        <el-select
          v-model="queryParams.costType"
          placeholder="请选择毒理分类"
          clearable
          size="small"
          style="width:140px"
        >
          <el-option
            v-for="item in poisonTypeArr"
            :key="item.dictValue"
            :value="item.dictValue"
            :label="item.dictLabel"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="" prop="poisonType">
        <el-select
          v-model="queryParams.poisonType"
          placeholder="请选择入价值分类"
          clearable
          size="small"
          style="width:150px"
        >
          <el-option
            v-for="item in costTypeArr"
            :key="item.dictValue"
            :value="item.dictValue"
            :label="item.dictLabel"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="" prop="stock">
        <el-select
          v-model="queryParams.skuState"
          placeholder="请选择库存"
          clearable
          size="small"
          style="width:140px"
        >
          <el-option
            v-for="item in stockArr"
            :key="item.dictValue"
            :value="item.dictValue"
            :label="item.dictLabel"
          ></el-option>
        </el-select>
      </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-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['inventory:inventory:export']"
          >导出</el-button
        >
      </el-form-item>
    </el-form>

    <el-table
      v-loading="loading"
      :data="inventoryList"
      @selection-change="handleSelectionChange"
      border
      size="mini"
      :row-class-name="setBGClass"
    >
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column type="index" width="55" align="center" label="序号" />
      <!-- <el-table-column label="id" align="center" prop="id" /> -->
      <!-- <el-table-column label="药房id" align="center" prop="pharmacyId" /> -->
      <el-table-column
        label="药品名称规格"
        align="center"
        prop="drugsName"
      >
        <template slot-scope="scope">{{scope.row.drugsName}}{{scope.row.specsName}}</template>
      </el-table-column>
      <el-table-column
        label="药品产地"
        align="center"
        prop="priceName"
      />
      <el-table-column label="库存数量" align="center" prop="stock">
        <template slot-scope="scope">{{scope.row.stock.toFixed(4)}}</template>
      </el-table-column>
      <el-table-column
        label="进货单价"
        align="center"
        prop="purchasePrice"
      />
      <el-table-column
        label="进货总价"
        align="center"
        prop="purchasePrice"
      >
        <template slot-scope="scope">
          {{ (scope.row.purchasePrice * scope.row.stock).toFixed(4) }}
        </template>
      </el-table-column>
      <el-table-column
        label="零售单价"
        align="center"
        prop="retailPrice"
      ><template slot-scope="scope">{{scope.row.retailPrice}}</template></el-table-column>
      <el-table-column
        label="零售总价"
        align="center"
        prop="retailPrice"
      >
        <template slot-scope="scope">
          {{ (scope.row.retailPrice * scope.row.stock).toFixed(4) }}
        </template>
      </el-table-column>
      <el-table-column
        label="批准文号"
        align="center"
        prop="approvalCode"
      />
      <el-table-column
        label="库存上限"
        align="center"
        prop="stockMax"
      ><template slot-scope="scope">{{parseInt(scope.row.stockMax)||'-'}}</template></el-table-column>
      <el-table-column
        label="库存下限"
        align="center"
        prop="stockMin"
      ><template slot-scope="scope">{{parseInt(scope.row.stockMin)||'-'}}</template></el-table-column>
      <el-table-column
        label="摆放位置"
        align="center"
        prop="site"
      />

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            style="width: 40px"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['inventory:inventory:edit']"
            >详情</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="title" :visible.sync="open" width="720px" append-to-body>
      <el-form
        :model="queryParamsDetails"
        ref="queryFormDetails"
        :inline="true"
        v-show="showSearch"
        label-width="68px">
        <div class="query-box">
          <div class="query-box__left">
            <el-form-item label="" prop="type">
              <el-select
                v-model="queryParamsDetails.validState"
                placeholder="请选择批次"
                clearable
                size="small"
                @change="handleQueryDetails"
              >
                <el-option
                  v-for="item in pcArr"
                  :key="item.dictValue"
                  :value="item.dictValue"
                  :label="item.dictLabel"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                icon="el-icon-search"
                size="mini"
                @click="handleQueryDetails"
                >搜索</el-button
              >
              <!-- <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
                >重置</el-button
              > -->
            </el-form-item>
          </div>
        </div>
      </el-form>

      <el-table :data="detailsList" size="mini">
        <el-table-column type="index" width="55" align="center" />
        <el-table-column label="批次号" align="center" prop="productionCode" />
        <el-table-column label="入库时间" align="center" prop="createTime" />
        <el-table-column label="进货单价" align="center" prop="purchasePrice" />
        <el-table-column label="入库数量" align="center" prop="stock" />
      </el-table>

      <!-- <pagination
        v-show="totalDetails > 0"
        :total="totalDetails"
        :page.sync="queryParamsDetails.pageNum"
        :limit.sync="queryParamsDetails.pageSize"
        @pagination="handleUpdate"
      /> -->
      <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 {
  listInventory,
  getInventory,
  detailList,
  delInventory,
  addInventory,
  updateInventory,
  getInventoryDetail,
  exportInventory,
} from "@/api/inventory/inventory";

export default {
  name: "Inventory",
  data() {
    return {
      id: "",
      drugsTypeArr: [],
      chinesMedicineTypeArr: [],
      poisonTypeArr: [],
      costTypeArr: [],
      stockArr: [
        { dictValue: 0, dictLabel: "全部库存" },
        { dictValue: 1, dictLabel: "上下限之内" },
        { dictValue: 2, dictLabel: "超上限" },
        { dictValue: 3, dictLabel: "超下限" },
        { dictValue: 4, dictLabel: "零库存" },
      ],
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      totalDetails: 0,
      // 药品库存表格数据
      inventoryList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        pharmacyId: window.localStorage.getItem("pharmacyId"),
        drugsType: null,
        drugsName: null,
        drugsType: null,
        drugsSpecsType: null,
        costType: null,
        poisonType: null,
        stock: null,
      },
      queryParamsDetails: {
        pageNum: 1,
        pageSize: 10,
        validState: null,
        id: null,
      },
      pcArr: [
        { dictValue: '', dictLabel: "全部批次" },
        { dictValue: 3, dictLabel: "过期批次" },
      ],
      detailsList: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        pharmacyId: [
          { required: true, message: "药房id不能为空", trigger: "blur" },
        ],
        validTime: [
          { required: true, message: "有效时间不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getDicts("drugs_type").then((response) => {
      this.drugsTypeArr = response.data;
    });

    this.getDicts("chinese_medicine_type").then((response) => {
      this.chinesMedicineTypeArr = response.data;
    });

    this.getDicts("poison_type").then((response) => {
      this.poisonTypeArr = response.data;
    });

    this.getDicts("cost_type").then((response) => {
      this.costTypeArr = response.data;
    });
  },
  methods: {
    setBGClass (r) {
      if (r.row.stockMin && (r.row.stock < r.row.stockMin)) {
        return 'redColumn'
      }
      if (r.row.stockMax && (r.row.stock > r.row.stockMax)) {
        return 'greenColumn'
      }
    },
    /** 查询药品库存列表 */
    getList() {
      this.loading = true;
      listInventory(this.queryParams).then((response) => {
        this.inventoryList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        pharmacyId: window.localStorage.getItem("pharmacyId"),
        specsId: null,
        priceId: null,
        stock: null,
        purchasePrice: null,
        retailPrice: null,
        approvalCode: null,
        stockMax: null,
        stockMin: null,
        site: null,
        productionCode: null,
        validTime: null,
        del: null,
        state: null,
        createBy: null,
        updateBy: null,
        createTime: null,
        updateTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    handleQueryDetails() {
      this.queryParamsDetails.pageNum = 1;
      this.getDetails();
    },
    /** 重置按钮操作 */
    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();
      this.open = true;
      this.queryParamsDetails.id = row.id;
      this.queryParamsDetails.validState = ''
      this.title = "查看药品库存";
      this.getDetails();
    },
    getDetails() {
      getInventoryDetail(this.queryParamsDetails.id, this.queryParamsDetails.validState).then((response) => {
        this.detailsList = response.rows;
        this.totalDetails = response.total;
        //console.log(response.rows, "999");
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateInventory(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addInventory(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm("确定需要删除选中数据吗？", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delInventory(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有药品库存数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.exportLoading = true;
          return exportInventory(queryParams);
        })
        .then((response) => {
          //console.log(response)
          this.download(response.msg);
          this.exportLoading = false;
        })
        .catch(() => {});
    },
  },
};
</script>

<style>
.redColumn, .redColumn:hover, .el-table__body tr.redColumn.hover-row > td {
  background: #F56C6C!important;
  color: #fff!important;
}
.greenColumn, .greenColumn:hover, .el-table__body tr.greenColumn.hover-row > td {
  background: #67C23A!important;
  color: #fff!important;
}
</style>
