<template>
  <div class="app-container">
    <el-form ref="queryForm" :model="queryParams" :inline="true" size="small" label-width="90px">
      <el-form-item label="单据编号">
        <el-input v-model="queryParams.sheetNo" placeholder="请输入单据编号" clearable style="width: 220px" />
      </el-form-item>
      <el-form-item label="业务日期">
        <el-date-picker v-model="queryParams.bizDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择" style="width: 220px" />
      </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" v-hasPermi="['erp:stock:relatedFee: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="['erp:stock:relatedFee:remove']">删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" prop="id" width="80" align="center" />
      <el-table-column label="业务日期" prop="bizDate" min-width="120" align="center" />
      <el-table-column label="单据编号" prop="sheetNo" min-width="180" align="center" />
      <el-table-column label="操作" align="center" width="160">
        <template slot-scope="scope">
          <el-button type="text" size="mini" @click="handleView(scope.row)" v-hasPermi="['erp:stock:relatedFee:query']">查看</el-button>
          <el-button type="text" size="mini" @click="handleDelete(scope.row)" v-hasPermi="['erp:stock:relatedFee: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="1300px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="12">
          <el-col :span="6">
            <el-form-item label="业务日期" prop="bizDate">
              <el-date-picker v-model="form.bizDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择" style="width: 100%" :disabled="readonly" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="单据编号">
              <el-input v-model="form.sheetNo" readonly />
            </el-form-item>
          </el-col>
        </el-row>

        <div class="mb8" v-if="!readonly">
          <el-button type="primary" plain size="mini" icon="el-icon-plus" @click="addItemRow">新增费用项</el-button>
        </div>

        <el-table :data="form.goodsList" border>
          <el-table-column label="序号" width="80" align="center">
            <template slot-scope="scope">{{ scope.$index + 1 }}</template>
          </el-table-column>
          <el-table-column label="一级科目名称" min-width="260">
            <template slot-scope="scope">
              <el-input v-model="scope.row.subjectLevel1" :disabled="readonly" placeholder="请输入一级科目名称" />
            </template>
          </el-table-column>
          <el-table-column label="二级科目名称" min-width="260">
            <template slot-scope="scope">
              <el-input v-model="scope.row.subjectLevel2" :disabled="readonly" placeholder="请输入二级科目名称" />
            </template>
          </el-table-column>
          <el-table-column label="费用金额" min-width="160" align="right">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.amount" :precision="4" :min="0" :disabled="readonly" :step="1" controls-position="right" style="width: 100%" />
            </template>
          </el-table-column>
          <el-table-column label="备注" min-width="220">
            <template slot-scope="scope">
              <el-input v-model="scope.row.remark" :disabled="readonly" placeholder="请输入备注" />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80" v-if="!readonly" align="center">
            <template slot-scope="scope">
              <el-button type="text" size="mini" @click="removeItemRow(scope.$index)">删</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" v-if="!readonly" @click="submitForm">提 交</el-button>
        <el-button @click="cancel">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addRelatedFee, delRelatedFee, getRelatedFee, listRelatedFee } from "@/api/erp/stock";

export default {
  name: "StockRelatedFee",
  data() {
    return {
      loading: false,
      showSearch: true,
      total: 0,
      list: [],
      ids: [],
      single: true,
      multiple: true,
      open: false,
      title: "",
      readonly: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sheetNo: undefined,
        bizDate: undefined
      },
      form: {},
      rules: {
        bizDate: [{ required: true, message: "业务日期不能为空", trigger: "change" }]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getList() {
      this.loading = true;
      listRelatedFee(this.queryParams).then((res) => {
        this.list = res.rows || [];
        this.total = res.total || 0;
        this.loading = false;
      });
    },
    reset() {
      this.form = {
        id: undefined,
        bizDate: this.parseTime(new Date(), "{y}-{m}-{d}"),
        sheetNo: "",
        goodsList: [this.buildEmptyItemRow()]
      };
      this.resetForm("form");
    },
    buildEmptyItemRow() {
      return { subjectLevel1: "", subjectLevel2: "", amount: 0, remark: "" };
    },
    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.readonly = false;
      this.reset();
      this.open = true;
      this.title = "新增相关费用";
    },
    handleView(row) {
      this.readonly = true;
      const id = row.id || this.ids[0];
      getRelatedFee(id).then((res) => {
        this.form = Object.assign({ goodsList: [] }, res.data || {});
        this.open = true;
        this.title = "查看相关费用";
      });
    },
    addItemRow() {
      this.form.goodsList.push(this.buildEmptyItemRow());
    },
    removeItemRow(index) {
      this.form.goodsList.splice(index, 1);
      if (this.form.goodsList.length === 0) {
        this.form.goodsList.push(this.buildEmptyItemRow());
      }
    },
    validateGoodsList() {
      const list = this.form.goodsList || [];
      if (!list.length) {
        this.$modal.msgError("至少需要一条费用项");
        return false;
      }
      for (let i = 0; i < list.length; i++) {
        const it = list[i];
        if (!it.subjectLevel1 || !it.subjectLevel2) {
          this.$modal.msgError(`第${i + 1}行科目不能为空`);
          return false;
        }
      }
      return true;
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (!valid) return;
        if (!this.validateGoodsList()) return;
        const payload = {
          bizDate: this.form.bizDate,
          goodsList: (this.form.goodsList || []).map((it) => ({
            subjectLevel1: it.subjectLevel1,
            subjectLevel2: it.subjectLevel2,
            amount: Number(it.amount || 0),
            remark: it.remark
          }))
        };
        this.$modal.confirm("确认提交该相关费用吗？").then(() => {
          return addRelatedFee(payload).then(() => {
            this.$modal.msgSuccess("提交成功");
            this.open = false;
            this.getList();
          });
        }).catch(() => {});
      });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    handleDelete(row) {
      const ids = row && row.id ? row.id : this.ids.join(",");
      if (!ids) return;
      this.$modal.confirm("确认删除选中的相关费用单吗？").then(() => delRelatedFee(ids)).then(() => {
        this.$modal.msgSuccess("删除成功");
        this.getList();
      }).catch(() => {});
    }
  }
};
</script>

