<template>
  <basic-container>
    <!-- 科目费用维护 -->
    <avue-crud :option="option" :table-loading="loading" :data="data" v-model="form" v-model:page="page" ref="crud"
      @row-update="rowUpdate" @row-save="rowSave" @search-change="searchChange" @search-reset="searchReset"
      @selection-change="selectionChange" @current-change="currentChange" @size-change="sizeChange"
      @refresh-change="refreshChange" @on-load="onLoad">
      <template #menu-left>
        <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
        <el-button type="danger" icon="el-icon-delete" @click="handleDelete">删除</el-button>
        <el-button type="success" icon="el-icon-upload" @click="handleImport">导入</el-button>
        <el-button type="warning" icon="el-icon-s-finance" @click="handleCostCalculation">成本计算</el-button>
      </template>

      <template #menu="scope">
        <el-button type="text" @click="viewRow(scope.row)">详情</el-button>
        <el-button type="text" @click="maintainRow(scope.row)">维护</el-button>
      </template>
    </avue-crud>
    <el-dialog append-to-body title="新增" :model-value="showAdd" @update:model-value="val => showAdd = val">
      <el-form ref="addForm" :model="addForm" :rules="addRules">
        <el-form-item label="费用科目" prop="expenseAccount">
          <el-input v-model="addForm.expenseAccount" placeholder="请输入费用科目"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAdd = false">取 消</el-button>
          <el-button type="primary" @click="submitAdd">保 存</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 维护弹窗 -->
    <el-dialog append-to-body :title="title" :model-value="showMaintain" @update:model-value="val => showMaintain = val">
      <el-form :inline="true" :model="maintainForm" ref="maintainForm" :rules="maintainRules">
        <el-form-item label="月份" prop="month">
          <el-date-picker v-model="maintainForm.month" type="month" placeholder="选择月份" format="YYYY年MM月"
            value-format="YYYY-MM" :disabled="title == '详情'"></el-date-picker>
        </el-form-item>
        <el-form-item label="费用分配方式" prop="distributeType">
          <el-radio-group v-model="maintainForm.distributeType" :disabled="title == '详情'">
            <el-radio label="1">按金额</el-radio>
            <el-radio label="2">按比例</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="总费用金额" prop="totalCost">
          <el-input-number v-model="maintainForm.totalCost" controls-position="right" :min="1"
            :disabled="title == '详情'"></el-input-number>
        </el-form-item>
      </el-form>
      <el-table :data="tableData">
        <el-table-column type="index"></el-table-column>
        <el-table-column label="作业中心" prop="workCenter"></el-table-column>
        <el-table-column label="比例" prop="ratio">
          <template #default="scope">
            <el-input-number v-model="scope.row.ratio" controls-position="right" :min="1" :max="100"
              :disabled="title == '详情'"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="费用金额(元)" prop="money">
          <template #default="scope">
            <el-input-number v-model="scope.row.money" controls-position="right" :min="1"
              :disabled="title == '详情'"></el-input-number>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showMaintain = false">取 消</el-button>
          <el-button v-if="title == '维护'" type="primary" @click="submitMaintain">保 存</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 导入 -->
    <basic-import v-if="isShowImport" title="导入" :isShow="isShowImport"
      templateUrl="/blade-desk/QA/CycleTestItem/download-excel-template" templateName="试验项目模板.xls"
      importUrl="/blade-desk/QA/CycleTestItem/import-excel" @closeDialog="closeDialog"></basic-import>
      
    <!-- 成本计算月份选择弹窗 -->
    <el-dialog append-to-body title="成本计算" :model-value="showCostCalculation" @update:model-value="val => showCostCalculation = val" width="400px">
      <el-form ref="costForm" :model="costForm" :rules="costRules">
        <el-form-item label="选择月份" prop="month">
          <el-date-picker
            v-model="costForm.month"
            type="month"
            placeholder="选择月份"
            format="YYYY年MM月"
            value-format="YYYY-MM"
            style="width: 100%"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showCostCalculation = false">取 消</el-button>
          <el-button type="primary" @click="submitCostCalculation">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </basic-container>
</template>

<script>
import basicImport from '@/components/basic-import/main.vue'
export default {
  components: {
    basicImport,
  },
  data() {
    return {
      isShowImport: false,
      data: [],
      form: {},
      distributeType: "",
      loading: false,
      showAdd: false,
      title: "详情",
      tableData: [],
      addForm: {},
      selectionList: [],
      showMaintain: false,
      showCostCalculation: false,
      costForm: {
        month: ''
      },
      costRules: {
        month: [{ required: true, message: "请选择月份", trigger: "change" }]
      },
      calculatedMonths: ['2023-10', '2023-11'], // 模拟已计算成本的月份列表
      addRules: {
        expenseAccount: [{ required: true, message: "请输入费用科目", trigger: "blur" }],
      },
      maintainForm: {},
      maintainRules: {
        month: [{ required: true, message: "请选择月份", trigger: "change" }],
        totalCost: [{ required: true, message: "请输入总费用金额", trigger: "blur" }],
      },
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      option: {
        height: "auto",
        calcHeight: 32,
        tip: false,
        simplePage: true,
        searchShow: true,
        searchMenuSpan: 6,
        searchIcon: true,
        searchIndex: 3,
        tree: false,
        border: true,
        index: true,
        selection: true,
        viewBtn: false,
        delBtn: false,
        addBtn: false,
        editBtn: false,
        editBtnText: "修改",
        viewBtnIcon: " ",
        delBtnIcon: " ",
        editBtnIcon: " ",
        viewBtnText: "详情",
        labelWidth: 120,
        searchLabelWidth: 120,
        menuWidth: 220,
        dialogWidth: 1200,
        dialogClickModal: false,
        searchEnter: true,
        excelBtn: false,
        filterBtn: true,
        searchShowBtn: false,
        columnSort: true,
        excelBtn: true,
        columnSort: true,
        index: false,
        showOverflowTooltip: true,
        searchLabelPosition: "left",
        searchLabelPosition: "left",
        searchGutter: 24,
        searchSpan: 6,
        menuAlign: "left",
        gridBtn: false,
        searchMenuPosition: "right",
        addBtnIcon: " ",
        viewBtnIcon: " ",
        delBtnIcon: " ",
        editBtnIcon: " ",
        align: "center",

        column: [
          {
            label: "费用科目",
            prop: "expenseAccount",
            search: true,
            sortable: true,
            overHidden: true,
            rules: [
              {
                required: true,
                message: "请输入费用科目",
                trigger: "blur",
              },
            ],
          },
          {
            label: "分配方式",
            prop: "distributeType",
            type: "select",
            search: false,
            sortable: true,
            overHidden: true,
            rules: [
              {
                required: true,
                message: "请输入分配方式",
                trigger: "blur",
              },
            ],
            dicData: [
              { label: "按金额", value: "1" },
              { label: "按比例", value: "2" },
            ],
          },
          {
            label: "费用总金额(元)",
            prop: "totalCost",
            search: false,
            sortable: true,
            overHidden: true,
            rules: [
              {
                required: true,
                message: "请输入费用总金额(元)",
                trigger: "blur",
              },
            ],
          },
          {
            label: "操作人",
            prop: "createUser",
            search: false,
            sortable: true,
            overHidden: true,
            rules: [
              {
                required: true,
                message: "请输入操作人",
                trigger: "blur",
              },
            ],
          },
          {
            label: "更新时间",
            prop: "updateTime",
            search: false,
            sortable: true,
            overHidden: true,
            rules: [
              {
                required: true,
                message: "请输入更新时间",
                trigger: "blur",
              },
            ],
          },
        ],
      },
    };
  },
  mounted() { },
  methods: {
    // 点击导入按钮
    handleImport() {
      this.isShowImport = true
    },
    // 多选
    selectionChange(val) {
      this.selectionList = val;
    },
    // 点击删除按钮
    handleDelete() {
      if (this.selectionList.length == 0) {
        this.$message.error("请先选择数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then((res) => { });
    },
    // 点击新增按钮
    handleAdd() {
      this.showAdd = true;
    },
    // 新增提交
    submitAdd() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.showAdd = false;
        }
      });
    },
    // 维护提交
    submitMaintain() {
      this.$refs.maintainForm.validate((valid) => {
        if (valid) {
          this.showMaintain = false;
        }
      });
    },
    // 详情
    viewRow(row) {
      this.title = "详情";
      this.maintainForm = { ...row, month: row.month || this.getCurrentMonth() };
      this.tableData = row.tableData;
      this.showMaintain = true;
    },
    // 维护
    maintainRow(row) {
      this.title = "维护";
      this.maintainForm = { ...row, month: row.month || this.getCurrentMonth() };
      this.tableData = row.tableData;
      this.showMaintain = true;
    },
    // 获取当前月份
    getCurrentMonth() {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      return `${year}-${month}`;
    },
    // 成本计算按钮点击事件
    handleCostCalculation() {
      this.costForm.month = this.getCurrentMonth();
      this.showCostCalculation = true;
    },
    // 提交成本计算
    submitCostCalculation() {
      this.$refs.costForm.validate((valid) => {
        if (valid) {
          const selectedMonth = this.costForm.month;
          const year = selectedMonth.split('-')[0];
          const month = selectedMonth.split('-')[1];
          
          // 检查是否已计算过成本
          if (this.calculatedMonths.includes(selectedMonth)) {
            this.$confirm(`${year}年${month}月已计算成本，是否重新计算？`, {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.performCostCalculation(selectedMonth);
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消成本计算'
              });          
            });
          } else {
            this.performCostCalculation(selectedMonth);
          }
        }
      });
    },
    // 执行成本计算
    performCostCalculation(month) {
      // 模拟API调用
      this.$message({
        type: 'success',
        message: `${month}成本计算中，请稍候...`
      });
      
      setTimeout(() => {
        // 添加到已计算月份列表
        if (!this.calculatedMonths.includes(month)) {
          this.calculatedMonths.push(month);
        }
        
        this.showCostCalculation = false;
        this.$message({
          type: 'success',
          message: `${month}成本计算完成`
        });
      }, 2000);
    },
    onLoad() {
      this.data = [
        {
          id: 1,
          expenseAccount: "房租补贴",
          distributeType: "1",
          totalCost: 1000,
          createUser: "张三",
          updateTime: "2016-09-21  08:50:08",
          tableData: [
            { workCenter: "作业中心一", ratio: 40, money: 400 },
            { workCenter: "作业中心二", ratio: 30, money: 300 },
            { workCenter: "作业中心三", ratio: 30, money: 300 },
          ],
        },
        {
          id: 2,
          expenseAccount: "电话费",
          distributeType: "2",
          totalCost: 1000,
          createUser: "张三",
          updateTime: "2016-09-21  08:50:08",
          tableData: [
            { workCenter: "作业中心一", ratio: 20, money: 200 },
            { workCenter: "作业中心二", ratio: 50, money: 500 },
            { workCenter: "作业中心三", ratio: 30, money: 300 },
          ],
        },
        {
          id: 3,
          expenseAccount: "差旅费",
          distributeType: "1",
          totalCost: 1000,
          createUser: "张三",
          updateTime: "2016-09-21  08:50:08",
          tableData: [
            { workCenter: "作业中心一", ratio: 15, money: 150 },
            { workCenter: "作业中心二", ratio: 35, money: 350 },
            { workCenter: "作业中心三", ratio: 50, money: 500 },
          ],
        },
      ];
    },
  },
};
</script>

<style></style>
