<template>
  <div class="app-container">
    <el-form :model="queryForm" ref="queryForm" size="small" :inline="true">
      <el-form-item label="年度" prop="budgetYear">
        <el-date-picker v-model="queryForm.budgetYear" clearable type="year" value-format="yyyy" style="width: 100%"
          placeholder="选择年度">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="项目名称" prop="budgetName">
        <el-input clearable v-model="queryForm.budgetName" placeholder="请输入项目名称"
          @keyup.enter.native="handleQuery"></el-input>
      </el-form-item>
      <el-form-item label="科室" prop="deptName">
        <treeselect v-model="queryForm.deptId" :options="deptOptions" :show-count="true" :defaultExpandLevel="2"
          style="width: 200px" placeholder="请选择科室" />
      </el-form-item>
      <el-form-item label="是否政府采购" prop="isGov">
        <el-select v-model="queryForm.isGov" placeholder="请选择" style="width: 100%">
          <el-option label="是" value="0"></el-option>
          <el-option label="否" value="1"></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-form-item>
      <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="['system:assets:add']">新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" plain icon="el-icon-upload2" size="mini" @click="handleImport"
            v-hasPermi="['system:assets:import']">导入
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
            v-hasPermi="['system:assets:export']">导出
          </el-button>
        </el-col>
      </el-row>
    </el-form>
    <el-table v-loading="loading" border :row-style="{ height: '35px' }" :cell-style="{ padding: '0' }" :data="budgetList"
      style="font-size: 14px" stripe>
      <el-table-column label="年度" prop="budgetYear" min-width="95" align="center" />
      <el-table-column label="科室" prop="deptName" align="center" />
      <el-table-column label="项目名称" prop="budgetName" align="center" />
      <el-table-column label="项目明细" min-width="110" prop="budgetDetailed" align="center" class-name="inline-table">
        <template slot-scope="scope">
          <el-table :data="scope.row.schoolBudgetDetailsList" :show-header="false">
            <el-table-column prop="budgetDetailed" align="center"></el-table-column>
            <template slot="empty">{{ '' }}</template>
          </el-table>
        </template>
      </el-table-column>
      <el-table-column label="批复金额（万元）" prop="moneyDetailed" align="center" class-name="inline-table">
        <template slot-scope="scope">
          <el-table :data="scope.row.schoolBudgetDetailsList" :show-header="false">
            <el-table-column prop="moneyDetailed" align="center"></el-table-column>
            <template slot="empty">{{ '' }}</template>
          </el-table>
        </template>
      </el-table-column>
      <el-table-column label="批复总额（万元）" prop="giveMoney" align="center" class-name="inline-table">
      </el-table-column>
      <el-table-column label="已使用金额（万元）" prop="amountSpent" align="center" class-name="inline-table">
        <template slot-scope="scope">
          <div>
            <a @click="handleAmountClick(scope.row)">{{ scope.row.amountSpent }}</a>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="是否政府采购" prop="isGov" align="center">
        <template slot-scope="scope">
          {{ scope.row.isGov === '0' ? '是' : '否' }}
        </template>
      </el-table-column>
      <el-table-column label="备注" prop="remark" align="center" />
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">编辑
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryForm.pageNum" :limit.sync="queryForm.pageSize"
      @pagination="getList" />


    <el-dialog width="850px" :visible.sync="open" :title="title" append-to-body @close="cancel">
      <el-form ref="postForm" :model="postForm" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="预算年度" prop="budgetYear">
              <el-date-picker v-model="postForm.budgetYear" clearable type="year" value-format="yyyy" style="width: 100%"
                placeholder="选择年度">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="项目名称" prop="budgetName">
              <el-input v-model="postForm.budgetName" placeholder="请输入项目名称"></el-input>
            </el-form-item>
            <el-form-item label="政府采购" prop="isGov">
              <el-select v-model="postForm.isGov" placeholder="请选择" style="width: 100%">
                <el-option label="是" value="0"></el-option>
                <el-option label="否" value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="科室" prop="deptName">
              <treeselect v-model="postForm.deptId" :options="deptOptions" :show-count="true" :defaultExpandLevel="2"
                @select="selectDept" placeholder="请选择科室" />
            </el-form-item>
            <!-- <el-form-item label="批复金额" prop="giveMoney"> -->
            <!-- <el-input v-model="postForm.giveMoney"></el-input> -->
            <!-- <el-input :value="sum" readonly>
                <template slot="suffix">万元</template>
              </el-input>
            </el-form-item> -->
            <el-form-item label="批复金额" prop="giveMoney">
              <el-input :value="handlePrecision(sum, 4)">
                <template slot="suffix">万元</template>
              </el-input>
            </el-form-item>

          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="postForm.remark" type="textarea" placeholder="请输入备注" :maxlength="500"
            :autosize="{ minRows: 3 }"></el-input>
        </el-form-item>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="addDetail">新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="!multiple"
              @click="deleteDetail">删除
            </el-button>
          </el-col>
        </el-row>

        <el-table :data="postForm.schoolBudgetDetailsList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="序号" type="index" align="center"></el-table-column>
          <!-- budgetDetailed -->
          <el-table-column label="项目支出明细" align="center">
            <template slot-scope="scope">
              <el-autocomplete v-model="scope.row.budgetDetailed" placeholder="请选择或手动输入"
                :fetch-suggestions="handleFetchSuggestions" @select="handleProjectExpenditureSelect">
                <template slot-scope="{ item }">
                  <span>{{ item.value }}</span>
                </template>
                <el-input v-model="scope.row.budgetDetailed" clearable></el-input>
              </el-autocomplete>
            </template>
          </el-table-column>
          <!-- <el-table-column label="批复金额（万元）" align="center">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.moneyDetailed" :controls="false" :min="0"
                :precision="2"></el-input-number>
            </template>
          </el-table-column> -->
          <el-table-column label="批复金额（万元）" align="center">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.moneyDetailed" :controls="false" :min="0" :precision="4"
                readonly></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="remark" align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.remark" type="textarea" :maxlength="500" :autosize="{ minRows: 1 }"></el-input>
            </template>
          </el-table-column>
        </el-table>
      </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>

    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url"
        :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
        :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
            @click="importTemplate">下载模板
          </el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import {
  getBudgetList,
  addBudget,
  editBudget,
  deleteBudget,
  queryBudget
} from '@/api/smartSchool/logisticsManage/budgetApproval'
import { deptTreeSelect } from "@/api/system/user";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { getToken } from "@/utils/auth";

export default {
  name: "BudgetApproval",
  components: {
    Treeselect
  },
  computed: {
    isGovConvert: {
      get() {
        return this.postForm.isGov === '0' ? '是' : '否'
      },
      set(val) {
        this.postForm.isGov = val
      }
    }
  },
  data() {
    return {
      // 查询表单
      queryForm: {
        budgetYear: '',// 预算年度
        deptId: null,// 部门ID科室
        budgetName: '',// 项目名称
        isGov: '',// 是否政府采购
        remark: '',// 备注
        giveMoney: '',// 批复金额
        budgetDetailed: '',//项目支出明细
        pageNum: 1,
        pageSize: 10
      },
      // 是否政府采购
      isGovConvert: "",
      isGov: "",
      // 遮罩层
      loading: false,
      total: 0,
      // 信息列表
      budgetList: [],
      // 新增/编辑表单
      postForm: {
        schoolBudgetDetailsList: [],
        isGov: '0',
      },
      options: [],
      // 是否显示弹出层
      open: false,
      // 校验规则
      rules: {
        budgetYear: [{ required: true, message: '年度不能为空', trigger: 'blur' }],
        deptName: [{ required: true, message: '科室不能为空', trigger: 'blur' }],
        budgetName: [{ required: true, message: '项目名称不能为空', trigger: 'blur' }],
        isGov: [{ required: true, message: '是否政府采购不能为空', trigger: 'change' }],
        giveMoney: [{ required: true, message: '批复金额不能为空', trigger: 'blur' }]
      },
      // 弹出层标题
      title: '',
      // 是否禁用删除按钮--项目明细
      multiple: false,
      // 选中数据的值数组
      selectItems: [],
      // 科室列表
      deptOptions: [],
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/budgetDetails/importExcel"
      },
    }
  },


  computed: {
    sum() {
      const list = this.postForm.schoolBudgetDetailsList || [];
      const result = list.reduce((front, back) => {
        const money = this.handlePrecision(back.moneyDetailed, 4); // 将精度改为 4
        return this.handlePrecision(front + money, 4); // 将精度改为 4
      }, 0);
      this.postForm.giveMoney = result;
      return result;
    }
  },

  created() {
    this.getList();
    // 获取科室信息
    this.getDeptTree();
  },
  methods: {
    handleFetchSuggestions(queryString, callback) {
      // 根据用户输入的查询字符串查询选项列表
      // 在这里可以根据需要进行异步请求获取选项列表数据
      const suggestions = [
        { value: 'option1', label: '选项1' },
        { value: 'option2', label: '选项2' },
        { value: 'option3', label: '选项3' }
      ];

      callback(suggestions);
    },
    handleProjectExpenditureSelect(value) {
      // 处理用户选择下拉框选项的逻辑
      console.log(value);
    },
    // 处理精度
    handlePrecision(value, precision = 2) {
      if (precision < 1) {
        return Number(value);
      }
      return Number(Number(value).toFixed(precision)) || 0;
    },
    //点击出现弹窗
    handleLandClick(rowData) {
      // 构建目标页面 URL，假设为 /detail，同时传递 rowData 中的必要参数
      const detailUrl = '/detail?id=' + rowData.id; // 假设传递 id 参数
      // 使用页面跳转方法，例如 Vue Router
      this.$router.push(detailUrl);
    },
    // 已使用金额操作
    handleAmountClick(row) {
      console.log('row', row);
      this.$router.push({
        path: "/logisticsManage/detailsofFundusage",
        query: {
          budgetName: row.budgetName,
          purchaseName: row.purchaseName
        }
      });
    },
    // 获取列表
    getList() {
      this.loading = true;
      getBudgetList(this.queryForm).then(response => {
        this.loading = false;
        this.budgetList = response.rows;
        console.log(111, this.budgetList);
        this.total = response.total;
      }).catch(err => {
        this.loading = false;
      })
    },

    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },


    // 搜索按钮
    handleQuery() {
      this.getList();
    },

    // 重置按钮
    resetQuery() {
      this.queryForm = {
        budgetYear: '',// 预算年度
        deptId: null,// 部门ID科室
        budgetName: '',// 项目名称
        isGov: '',// 是否政府采购
        remark: '',// 备注
        giveMoney: '',// 批复金额
        budgetDetailed: '',//项目支出明细
        pageNum: 1,
        pageSize: 10
      };
      this.resetForm("queryForm");
      this.handleQuery();
    },

    // 导入按钮
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },

    // 导出按钮
    handleExport() {
      this.throttle(() => {
        this.download('budget/importTemplate', {
          ...this.queryForm
        }, `预算批复${new Date().getTime()}.xlsx`)
      })
    },

    // 编辑按钮
    handleUpdate(row) {
      this.title = '修改预算批复信息';
      this.$modal.loading('正在加载数据。请稍等...');
      queryBudget(row.id).then(response => {
        this.postForm = response.data;
        console.log('this.postForm', this.postForm);
        this.open = true;
        this.$modal.closeLoading();
      }).catch(err => {
        this.$modal.closeLoading();
      })
    },

    // 新增按钮
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = '新增预算批复信息'
    },

    // 删除按钮操作
    handleDelete(row) {
      this.throttle(() => {
        this.$modal.confirm(`是否确认删除此条数据？`).then(() => {
          this.$modal.loading('正在处理数据，请稍等...');
          return deleteBudget(row.id);
        }).then(() => {
          this.$modal.closeLoading();
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {
          this.$modal.closeLoading();
        });
      }
      )
    },

    // 提交表单
    submitForm() {
      this.throttle(() => {
        this.$refs["postForm"].validate(valid => {
          if (valid) {
            this.$modal.loading('正在上传数据，请稍等...');
            if (this.postForm.id != null) {
              // 编辑
              this.postForm.isGov = this.postForm.isGov; // 设置 isGov 字段的值
              editBudget(this.postForm).then(response => {
                this.$modal.closeLoading();
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }).catch(err => {
                this.$modal.closeLoading();
              });
            } else {
              // 新增

              this.postForm.isGov = this.postForm.isGov; // 设置 isGov 字段的值
              addBudget(this.postForm).then(response => {
                console.log('this.postForm', this.postForm);
                this.$modal.closeLoading();
                console.log(this);
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }).catch(err => {
                this.$modal.closeLoading();
              });
            }
          }
        });
      })
    },
    // 重置
    reset() {
      this.postForm = {
        budgetYear: '',// 预算年度
        deptId: null,// 部门ID科室
        deptName: '',
        budgetName: '',// 项目名称
        isGov: '',// 是否政府采购
        remark: '',// 备注
        giveMoney: '',// 批复金额
        schoolBudgetDetailsList: []
      }
      this.resetForm('postForm');
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.resetForm('postForm');
    },

    // 多选框选择数据
    handleSelectionChange(selection) {
      this.selectItems = selection.map(item => item.budgetDetailed);
      this.multiple = selection.length;

    },

    // 新增明细
    addDetail() {
      this.postForm.schoolBudgetDetailsList.push({
        budgetDetailed: '',
        moneyDetailed: '',
        remark: ''
      })
    },

    // 删除明细
    deleteDetail() {
      this.selectItems.forEach(selectItem => {
        const index = this.postForm.schoolBudgetDetailsList.findIndex(item => item.budgetDetailed === selectItem);
        this.postForm.schoolBudgetDetailsList.splice(index, 1);
      })
      this.selectIndexs = [];
    },

    //  合并单元格
    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
      const spanArr = this.getSpanArr(this.budgetList);
      if (columnIndex !== 3 && columnIndex !== 4) {
        const _row = spanArr[rowIndex];
        const _col = _row > 0 ? 1 : 0
        return {
          rowspan: _row,
          colspan: _col
        }
      }
    },
    // 合并相邻行之前存在相同项目的数据
    getSpanArr(data) {
      // data就是我们从后台拿到的数据
      let spanArr = [];
      let pos = 0;

      for (var i = 0; i < data.length; i++) {
        if (i === 0) {
          //设置table表格行号、设置合并参数，以便相同参数合并
          spanArr.push(1);
          pos = 0;
        } else {
          // 判断当前元素与上一个元素是否相同
          if (data[i].budgetName === data[i - 1].budgetName) {
            spanArr[pos] += 1;
            spanArr.push(0);
          } else {
            spanArr.push(1);
            pos = i;
          }
        }
      }
      return spanArr;
    },

    // 选择科室
    selectDept(node, instanceId) {
      this.postForm.deptId = node.id;
      this.postForm.deptName = node.label;
    },


    /** 下载模板操作 */
    importTemplate() {
      this.download('/budget/template', {}, `预算项目_${new Date().getTime()}.xlsx`)
    },

    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }

  }
}
</script>

<style lang="scss" scoped>
::v-deep .inline-table .cell {
  padding: 0;
}
</style>
