<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="44px"
    >
      <div class="query-box">
        <div class="query-box__left">
          <el-form-item label="日期" prop="time">
            <el-select v-model="time" style="width:330px">
              <el-option v-for="(v,i) in times" :key="i" :value="i" :label="v.startTime+' ~ '+v.endTime"></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="primary" plain size="mini" @click="bindCheckForward" v-hasPermi="['inventory:forward:add']">核对账本</el-button>
            <el-button type="primary" plain size="mini" @click="bindForwards" v-hasPermi="['inventory:forward:add']">结转</el-button>
          </el-form-item>
        </div>
      </div>
    </el-form>
    <el-table v-loading="loading" :data="forwardList" @selection-change="handleSelectionChange" border size="mini">
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column type="index" width="55" align="center" label="序号"></el-table-column>
      <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>
      <el-table-column label="单位" align="center" prop="packingUnit">
        <template slot-scope="scope">
          <dict-tag v-if="scope.row.packingUnit" :options="unitArr" :value="scope.row.packingUnit" />
        </template>
      </el-table-column>
      <el-table-column label="结存数量" align="center" prop="carryNum"></el-table-column>
      <el-table-column label="结存金额" align="center" prop="carryAmount"></el-table-column>
      <el-table-column label="账面数量" align="center" prop="paperNum"></el-table-column>
      <el-table-column label="账面金额" align="center" prop="paperAmount"></el-table-column>
      <el-table-column label="生成日期" align="center" prop="createTime"></el-table-column>
      <el-table-column label="操作" align="center" fixed="right" width="160" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" style="width: 40px" @click="handleUpdate(scope.row)" v-hasPermi="['inventory:forward:edit']">平尾差</el-button>
          <el-button size="mini" type="primary" style="width: 40px" @click="handleDelete(scope.row)" v-hasPermi="['inventory:forward: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="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" class="eform">
        <!-- <el-form-item label="药房id" prop="pharmacyId">
          <el-input v-model="form.pharmacyId" placeholder="请输入药房id" />
        </el-form-item>
        <el-form-item label="库存id" prop="inventoryId">
          <el-input v-model="form.inventoryId" placeholder="请输入库存id" />
        </el-form-item> -->
        <el-form-item label="结存数量:" prop="carryNum">
          <el-input v-model="form.carryNum" placeholder="请输入结存数量" />
        </el-form-item>
        <el-form-item label="结存金额:" prop="carryAmount">
          <el-input v-model="form.carryAmount" placeholder="请输入结存金额" />
        </el-form-item>
        <el-form-item label="账面数量:" prop="paperNum">
          <span>{{form.paperNum}}</span>
          <!-- <el-input v-model="form.paperNum" placeholder="请输入账面数量" /> -->
        </el-form-item>
        <el-form-item label="账面金额:" prop="paperAmount">
          <span>{{form.paperAmount}}</span>
          <!-- <el-input v-model="form.paperAmount" placeholder="请输入账面金额" /> -->
        </el-form-item>
        <!-- <el-form-item label="是否结转" prop="state">
          <el-switch v-model="form.state" active-value="1" inactive-value="0"></el-switch>
        </el-form-item>
        <el-form-item label="是否结转" prop="del">
          <el-switch v-model="form.del" active-value="1" inactive-value="0"></el-switch>
        </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>
  </div>
</template>

<script>
import {
  listForward,
  getForward,
  delForward,
  addForward,
  updateForward,
  exportForward,
  getTime,
  checkForward,
  bindForward,
  getTimeList
} from "@/api/inventory/forward";

export default {
  name: "Forward",
  data() {
    return {
      times: [],
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 库存结转表格数据
      forwardList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        pharmacyId: null,
        inventoryId: null,
        carryNum: null,
        carryAmount: null,
        paperNum: null,
        paperAmount: null,
        state: null,
        del: null,
      },
      time: '',
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      unitArr: []
    };
  },
  created() {
    this.getDicts("unit").then((response) => {
      this.unitArr = response.data;
    });
    this.getTimeApi();
    this.getList();
    // //console.log(this.dayjs().startOf("month").format("YYYY-MM-DD")+' 00:00:00')
    // this.dayjs().startOf("month").format("YYYY-MM-DD")
  },
  methods: {
    bindCheckForward () {
      if (this.time === '') {
        return this.msgError('请选择日期')
      }
      var t = this.times[this.time]
      checkForward({
        startTime: t.startTime,
        endTime: t.endTime,
        pharmacyId: localStorage.getItem('pharmacyId')
      }).then(res => {
        if (res.code == 200) {
          this.msgSuccess('核对成功')
        }
      })
    },
    bindForwards () {
      if (this.time === '') {
        return this.msgError('请选择日期')
      }
      var t = this.times[this.time]
      bindForward({
        startTime: t.startTime,
        endTime: t.endTime,
        pharmacyId: localStorage.getItem('pharmacyId')
      }).then(res => {
        if (res.code == 200) {
          this.msgSuccess('结转成功')
        }
      })
    },
    getTime (val) {
      var t = new Date(val)
      var y = t.getFullYear(t)
      var m = t.getMonth() + 1
      var d = t.getDate()
      var h = t.getHours()
      var i = t.getMinutes()
      var s = t.getSeconds()
      m = m < 10 ? '0' + m : m
      d = d < 10 ? '0' + d : d
      h = h < 10 ? '0' + h : h
      i = i < 10 ? '0' + i : i
      s = s < 10 ? '0' + s : s
      return y + '/' + m + '/' + d + ' ' + h + ':' + i + ':' + s
    },
    //获取最新结转时间
    getTimeApi() {
      /*getTime().then((res) => {
        res.msg
          ? this.time.push(new Date(res.msg))
          : this.time.push(
              new Date(
                this.dayjs().startOf("month").format("YYYY-MM-DD") + " 00:00:00"
              )
            ); // 回显开始时间
        this.time.push(
          new Date(
            this.dayjs().endOf("month").format("YYYY-MM-DD") + " 00:00:00"
          )
        ); // 回显结束时间
      });*/
      getTimeList({
        pharmacyId: localStorage.getItem('pharmacyId')
      }).then(res => {
        if (res.code == 200) {
          this.times = res.data
        }
      })
    },
    /** 查询库存结转列表 */
    getList() {
      this.loading = true;
      listForward(this.queryParams).then((response) => {
        this.forwardList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        pharmacyId: null,
        inventoryId: null,
        carryNum: null,
        carryAmount: null,
        paperNum: null,
        paperAmount: null,
        createTime: null,
        state: null,
        createBy: null,
        updateBy: null,
        updateTime: null,
        del: 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.reset();
      this.open = true;
      this.title = "添加库存结转";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.form = row
      this.open = true;
      this.title = "修改库存结转";
      /*const id = row.id || this.ids;
      getForward(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改库存结转";
      });*/
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateForward(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addForward(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm(
        '是否确认删除库存结转编号为"' + ids + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return delForward(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有库存结转数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.exportLoading = true;
          return exportForward(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
          this.exportLoading = false;
        })
        .catch(() => {});
    },
  },
};
</script>

<style>
.eform .el-form-item--medium .el-form-item__label { color: #999; }
</style>