<template>
  <div class="app-container">
    <el-form :model="queryForm" ref="queryForm" size="small" :inline="true" label-width="70px">
      <el-form-item label="年度" prop="budgetYear">
        <!-- <el-input
          v-model="queryForm.budgetYear"
          placeholder="请输入年度"
          @keyup.enter.native="handleQuery"
        ></el-input> -->
        <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
          v-model="queryForm.budgetName"
          placeholder="请输入项目名称"
          @keyup.enter.native="handleQuery"
        ></el-input>
      </el-form-item>
      <!--      <el-form-item label="科室" prop="deptName">-->
      <!--        &lt;!&ndash; <el-input-->
      <!--          v-model="queryForm.deptName"-->
      <!--          placeholder="请输入科室"-->
      <!--          @keyup.enter.native="handleQuery"-->
      <!--        ></el-input> &ndash;&gt;-->
      <!--        <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-input-->
      <!--            v-model="queryForm.isGov"-->
      <!--            placeholder="请选择是否政府采购"-->
      <!--          ></el-input>-->
      <!--      </el-form-item>-->
      <el-form-item label="政府采购" prop="isGov">
        <el-select v-model="queryForm.isGov" placeholder="请选择是否为政府采购" style="width: 100%">
          <el-option label="是" value="1"></el-option>
          <el-option label="否" value="0"></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="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:assets:export']"
        >导出
        </el-button>
      </el-form-item>
    </el-form>
    <!-- :span-method="arraySpanMethod" -->
    <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>
      <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">
      </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)"-->
          <!--            v-hasPermi="['system:assets:edit']"-->
          <!--          >编辑-->
          <!--          </el-button>-->
          <!--          <el-button-->
          <!--            size="mini"-->
          <!--            type="text"-->
          <!--            icon="el-icon-delete"-->
          <!--            @click="handleDelete(scope.row)"-->
          <!--            v-hasPermi="['system:assets:delete']"-->
          <!--          >删除-->
          <!--          </el-button>-->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:assets:edit']"
          >查看
          </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="800px"
      :visible.sync="open"
      :title="title"
      append-to-body
      @close="cancel"
    >
      <el-form ref="postForm" :model="postForm" :rules="rules" label-width="80px">
        <el-row :gutter="25">
          <el-col :span="12">
            <el-form-item label="预算年度" prop="budgetYear">
              <el-input v-model="postForm.budgetYear" readonly></el-input>
            </el-form-item>
            <el-form-item label="项目名称" prop="budgetName">
              <el-input v-model="postForm.budgetName" readonly></el-input>
            </el-form-item>
            <el-form-item label="政府采购" prop="isGov">
              <el-input v-model="isGovConvert" readonly>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="科室" prop="deptName">
              <el-input v-model="postForm.deptName" readonly></el-input>
            </el-form-item>
            <el-form-item label="批复总额" prop="giveMoney">
              <el-input v-model="postForm.giveMoney" readonly>
                <template slot="append">万元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="postForm.remark" type="textarea" readonly></el-input>
        </el-form-item>
        <el-table
          :data="postForm.schoolBudgetDetailsList"
        >
          <!-- @selection-change="handleSelectionChange" el-table中出来的-->
          <!--          <el-table-column type="selection" width="55"/>-->
          <el-table-column label="序号" type="index" align="center"></el-table-column>
          <el-table-column label="项目支出明细" align="center">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.budgetDetailed" readonly
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="批复金额（万元）" align="center" min-width="50px">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.moneyDetailed" readonly
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="remark" align="center" min-width="100px">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.remark" readonly
              ></el-input>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="cancel">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getBudgetList,
  addBudget,
  editBudget,
  deleteBudget,
  queryBudget,
  exportBudget
} from '@/api/smartSchool/officialWork/budgetView'

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: "BudgetView",
  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
      },
      // 遮罩层
      loading: false,
      total: 0,
      // 信息列表
      budgetList: [],
      // 新增/编辑表单
      postForm: {
        schoolBudgetDetailsList: []
      },
      // 是否显示弹出层
      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: 'blur'}],
        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 + "/budget/importData"
      },
    }
  },

  created() {
    this.getList();
    // 获取科室信息
    this.getDeptTree();
  },
  methods: {
    // 获取列表
    getList() {
      this.loading = true;
      getBudgetList(this.queryForm).then(response => {
        this.loading = false;
        this.budgetList = response.rows;
        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();
    },

    // 导出按钮
    handleExport() {
      this.throttle(() => {
        this.download('budget/exportDept', {},
          `预算查看${Date.now()}.xlsx`)
      }, 300)
    },


    // 编辑按钮
    handleUpdate(row) {
      this.title = '预算批复信息查看';
      this.$modal.loading('正在加载数据。请稍等...');
      queryBudget(row.id).then(response => {
        this.postForm = response.data;
        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) {
    //           // 编辑
    //           editBudget(this.postForm).then(response => {
    //             this.$modal.closeLoading();
    //             this.$modal.msgSuccess("修改成功");
    //             this.open = false;
    //             this.getList();
    //           }).catch(err => {
    //             this.$modal.closeLoading();
    //           });
    //         } else {
    //           // 新增
    //           addBudget(this.postForm).then(response => {
    //             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>
