<template>
  <div class="app-container">
    <el-form ref="queryForm" :model="queryParams" :inline="true" size="small" label-width="90px">
      <el-form-item label="费用日期">
        <el-date-picker
          v-model="queryParams.feeDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择"
          style="width: 220px"
        />
      </el-form-item>
      <el-form-item label="单据编号">
        <el-input v-model="queryParams.sheetNo" placeholder="请输入单据编号" clearable 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:operPerf:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleEdit"
          v-hasPermi="['erp:stock:operPerf:edit']"
        >修改</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:operPerf: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="feeDate" min-width="120" align="center" />
      <el-table-column label="单据编号" prop="sheetNo" min-width="180" align="center" />
      <el-table-column label="单头头副返利" prop="rebHead" min-width="160" align="right" />
      <el-table-column label="其他业务收入" prop="othInc" min-width="160" align="right" />
      <el-table-column label="其他业务成本" prop="othExp" min-width="160" align="right" />
      <el-table-column label="税金及附加" prop="taxSurch" min-width="160" align="right" />
      <el-table-column label="资产减值损失" prop="impairLoss" min-width="160" align="right" />
      <el-table-column label="营业外收入" prop="nonopInc" min-width="160" align="right" />
      <el-table-column label="营业外支出" prop="nonopExp" min-width="160" align="right" />
      <el-table-column label="所得税费用" prop="incTaxExp" min-width="150" align="right" />
      <el-table-column label="销售费用-运费白条" prop="freightBills" min-width="190" align="right" />
      <el-table-column label="操作" align="center" width="150">
        <template slot-scope="scope">
          <el-button type="text" size="mini" @click="handleView(scope.row)" v-hasPermi="['erp:stock:operPerf:query']">查看</el-button>
          <el-button
            type="text"
            size="mini"
            @click="handleEditRow(scope.row)"
            v-hasPermi="['erp:stock:operPerf: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="980px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="12">
          <el-col :span="6">
            <el-form-item label="费用日期" prop="feeDate">
              <el-date-picker
                v-model="form.feeDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择"
                style="width: 100%"
                :disabled="feeDateDisabled"
              />
              <div
                v-if="!readonly && !feeDateDisabled"
                style="margin-top: 8px; display: flex; gap: 8px; justify-content: flex-start;"
              >
                <el-button size="mini" @click="shiftFeeDate(-1)">前一天</el-button>
                <el-button size="mini" type="primary" @click="shiftFeeDate(1)">下一天</el-button>
              </div>
            </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>

        <el-row :gutter="12">
          <el-col :span="6">
            <el-form-item label="单头头副返利">
              <el-input-number v-model="form.rebHead" :precision="4" :min="0" :step="1" :disabled="readonly" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="其他业务收入">
              <el-input-number v-model="form.othInc" :precision="4" :min="0" :step="1" :disabled="readonly" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="12">
          <el-col :span="6">
            <el-form-item label="其他业务成本">
              <el-input-number v-model="form.othExp" :precision="4" :min="0" :step="1" :disabled="readonly" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="税金及附加">
              <el-input-number v-model="form.taxSurch" :precision="4" :min="0" :step="1" :disabled="readonly" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="12">
          <el-col :span="6">
            <el-form-item label="资产减值损失">
              <el-input-number v-model="form.impairLoss" :precision="4" :min="0" :step="1" :disabled="readonly" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="营业外收入">
              <el-input-number v-model="form.nonopInc" :precision="4" :min="0" :step="1" :disabled="readonly" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="12">
          <el-col :span="6">
            <el-form-item label="营业外支出">
              <el-input-number v-model="form.nonopExp" :precision="4" :min="0" :step="1" :disabled="readonly" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="所得税费用">
              <el-input-number v-model="form.incTaxExp" :precision="4" :min="0" :step="1" :disabled="readonly" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="12">
          <el-col :span="6">
            <el-form-item label="销售费用-运费白条">
              <el-input-number v-model="form.freightBills" :precision="4" :min="0" :step="1" :disabled="readonly" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

      </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 { addOperPerf, editOperPerf, delOperPerf, getOperPerf, listOperPerf } from "@/api/erp/stock";

export default {
  name: "StockOperPerf",
  data() {
    return {
      loading: false,
      showSearch: true,
      total: 0,
      list: [],
      ids: [],
      single: true,
      multiple: true,
      open: false,
      title: "",
      readonly: false,
      feeDateDisabled: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        feeDate: undefined,
        sheetNo: undefined
      },
      form: {},
      rules: {
        feeDate: [{ required: true, message: "费用日期不能为空", trigger: "change" }]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getList() {
      this.loading = true;
      listOperPerf(this.queryParams).then((res) => {
        this.list = res.rows || [];
        this.total = res.total || 0;
        this.loading = false;
      });
    },
    reset() {
      this.form = {
        id: undefined,
        feeDate: this.parseTime(new Date(), "{y}-{m}-{d}"),
        sheetNo: "",
        rebHead: 0,
        othInc: 0,
        othExp: 0,
        taxSurch: 0,
        impairLoss: 0,
        nonopInc: 0,
        nonopExp: 0,
        incTaxExp: 0,
        freightBills: 0,
      };
      this.resetForm("form");
    },
    parseYMD(dateStr) {
      if (!dateStr || typeof dateStr !== "string") return null;
      const parts = dateStr.split("-");
      if (parts.length !== 3) return null;
      const y = Number(parts[0]);
      const m = Number(parts[1]);
      const d = Number(parts[2]);
      if (!y || !m || !d) return null;
      const dt = new Date(y, m - 1, d);
      return Number.isNaN(dt.getTime()) ? null : dt;
    },
    formatYMD(dateObj) {
      const y = dateObj.getFullYear();
      const m = String(dateObj.getMonth() + 1).padStart(2, "0");
      const d = String(dateObj.getDate()).padStart(2, "0");
      return `${y}-${m}-${d}`;
    },
    buildEmptyForm(feeDateStr) {
      return {
        id: undefined,
        feeDate: feeDateStr,
        sheetNo: "",
        rebHead: 0,
        othInc: 0,
        othExp: 0,
        taxSurch: 0,
        impairLoss: 0,
        nonopInc: 0,
        nonopExp: 0,
        incTaxExp: 0,
        freightBills: 0,
      };
    },
    loadByFeeDate(feeDateStr) {
      const query = {
        pageNum: 1,
        pageSize: 1,
        feeDate: feeDateStr,
        sheetNo: undefined
      };
      listOperPerf(query).then((res) => {
        const rows = res.rows || [];
        if (rows.length > 0) {
          this.form = Object.assign({}, rows[0]);
          this.readonly = false;
          this.feeDateDisabled = false;
          this.title = "修改相经营业绩";
        } else {
          this.form = this.buildEmptyForm(feeDateStr);
          this.readonly = false;
          this.feeDateDisabled = false;
          this.title = "新增相经营业绩";
        }
        this.$nextTick(() => {
          if (this.$refs.form && this.$refs.form.clearValidate) {
            this.$refs.form.clearValidate();
          }
        });
      });
    },
    shiftFeeDate(deltaDays) {
      if (this.readonly || this.feeDateDisabled) return;
      const cur = this.parseYMD(this.form.feeDate);
      if (!cur) return;
      const next = new Date(cur.getTime());
      next.setDate(next.getDate() + deltaDays);
      const nextStr = this.formatYMD(next);
      this.form.feeDate = nextStr;
      this.loadByFeeDate(nextStr);
    },
    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.feeDateDisabled = false;
      this.reset();
      this.open = true;
      this.title = "新增相经营业绩";
    },
    handleEdit() {
      const id = this.ids[0];
      this.readonly = false;
      // 修改时不允许改日期，避免重新生成 sheetNo 导致不一致
      this.feeDateDisabled = true;
      getOperPerf(id).then((res) => {
        this.form = Object.assign({}, res.data || {});
        this.open = true;
        this.title = "修改相经营业绩";
      });
    },
    handleEditRow(row) {
      if (!row || !row.id) return;
      const id = row.id;
      this.readonly = false;
      // 修改时不允许改日期，避免重新生成 sheetNo 导致不一致
      this.feeDateDisabled = true;
      getOperPerf(id).then((res) => {
        this.form = Object.assign({}, res.data || {});
        this.open = true;
        this.title = "修改相经营业绩";
      });
    },
    handleView(row) {
      this.readonly = true;
      this.feeDateDisabled = true;
      getOperPerf(row.id).then((res) => {
        this.form = Object.assign({}, res.data || {});
        this.open = true;
        this.title = "查看相经营业绩";
      });
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (!valid) return;
        const payload = {
          id: this.form.id,
          feeDate: this.form.feeDate,
          sheetNo: this.form.sheetNo,
          rebHead: Number(this.form.rebHead || 0),
          othInc: Number(this.form.othInc || 0),
          othExp: Number(this.form.othExp || 0),
          taxSurch: Number(this.form.taxSurch || 0),
          impairLoss: Number(this.form.impairLoss || 0),
          nonopInc: Number(this.form.nonopInc || 0),
          nonopExp: Number(this.form.nonopExp || 0),
          incTaxExp: Number(this.form.incTaxExp || 0),
          freightBills: Number(this.form.freightBills || 0),
        };
        const isEdit = !!payload.id;
        this.$modal.confirm("确认提交该相经营业绩吗？").then(() => {
          const req = isEdit ? editOperPerf(payload) : addOperPerf(payload);
          return req.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(() => delOperPerf(ids)).then(() => {
        this.$modal.msgSuccess("删除成功");
        this.getList();
      }).catch(() => {});
    }
  }
};
</script>

