<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="部门" prop="deptId">
        <div style="width: 200px">
          <treeselect
            v-model="queryParams.deptId"
            :options="deptOptions"
            :show-count="true"
            placeholder="请选择归属部门"
            :disabled="disabled"
          />
        </div>
      </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="['system:account:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:account: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="['system:account:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
		  :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['system:account:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>-->

    <el-table v-loading="loading" :data="accountList">
      <el-table-column
        label="部门"
        align="center"
        prop="deptName"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="账户总额" align="center" prop="totalAmount" />
      <el-table-column label="可用金额" align="center" prop="ableAmount" />
      <el-table-column
        label="应收总额"
        align="center"
        prop="incomeAbleTotalAmount"
      >
        <template v-slot="scope">
          <el-button
            size="mini"
            type="text"
            @click="moneyDialog(scope.row, 'income')"
          >
            {{ scope.row.incomeAbleTotalAmount }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column
        label="应付总额"
        align="center"
        prop="payableTotalAmount"
      >
        <template v-slot="scope">
          <el-button
            size="mini"
            type="text"
            @click="moneyDialog(scope.row, 'pay')"
          >
            {{ scope.row.payableTotalAmount }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <!--<el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:account:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:account:remove']"
          >删除</el-button>-->
          <el-button size="mini" type="text" @click="accountDetail(scope.row)"
            >账户详情</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="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="部门" prop="deptId">
          <el-input v-model="form.deptId" placeholder="请输入部门" />
        </el-form-item>
        <el-form-item label="可用金额" prop="ableAmount">
          <el-input v-model="form.ableAmount" placeholder="请输入可用金额" />
        </el-form-item>
      </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="tableOr === 'pay' ? '应付金额' : '应收金额'"
      :visible.sync="moneyOpen"
      append-to-body
      destroy-on-close
    >
      <MoneyTable
        :tableData="ableTotalAmountData"
        :or="tableOr"
        :deptId="deptId"
        :total="ableTotalAmounTotal"
        :moneyLoading="moneyLoading"
      />
    </el-dialog>
    <!-- 账户详情 -->
    <el-dialog
      title="账户详情"
      :visible.sync="operateOpen"
      width="800px"
      append-to-body
    >
      <el-form :model="queryAccountDetailParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="98px">
        <el-form-item label="操作类型" prop="transactionProjectName">

          <el-select v-model="queryAccountDetailParams.operateType" placeholder="请选择操作类型" clearable>
            <el-option label="收入" value="1"/>
            <el-option label="支出" value="2" />
            <el-option label="尾款扣除" value="3" />
          </el-select>
        </el-form-item>

<!--        <el-form-item label="部门" prop="deptId">-->
<!--          <div style="width: 200px">-->
<!--            <treeselect v-model="queryParams.deptId" :options="deptOptions" :show-count="true" placeholder="请选择归属部门" :disabled="disabled"/>-->
<!--          </div>-->
<!--        </el-form-item>-->

        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="getOperateList">搜索</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="cashOperateList">
        <el-table-column label="序号" width="50px" align="center">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column
          label="操作部门"
          align="center"
          prop="operateDeptName"
        />
        <el-table-column label="操作类型" align="center" prop="operateType">
          <template slot-scope="scope">
            <span v-if="scope.row.operateType == '1'">收入</span>
            <span v-if="scope.row.operateType == '2'">支出</span>
            <span v-if="scope.row.operateType == '3'">尾款扣除</span>
          </template>
        </el-table-column>
        <el-table-column label="金额" align="center" prop="operateAmount" />
        <el-table-column label="操作时间" align="center" prop="operateTime" width="150"/>
        <el-table-column label="单据类型" align="center" prop="documentType" >
          <template slot-scope="scope">
            <span v-if="scope.row.documentType == '1'">项目交易单</span>
            <span v-if="scope.row.documentType == '2'">借支申请</span>
            <span v-if="scope.row.documentType == '3'">外部采购单</span>
            <span v-if="scope.row.documentType == '4'">借贷申请</span>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="operateListTotal > 0"
        :total="operateListTotal"
        :page.sync="queryAccountDetailParams.pageNum"
        :limit.sync="queryAccountDetailParams.pageSize"
        @pagination="getOperateList"
      />
    </el-dialog>
  </div>
</template>

<script>
import {
  listAccount,
  getIncomeOrPayableList,
  getAccount,
  delAccount,
  addAccount,
  updateAccount,
  exportAccount,
} from "@/api/account/account";
import { treeselect } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { listOperate } from "@/api/account/operate";

import MoneyTable from "./component/MoneyTable";
export default {
  name: "Account",
  components: {
    Treeselect,
    MoneyTable,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 账户表格数据
      accountList: [],
      // 弹出层标题
      title: "",

      // 是否显示弹出层
      open: false,
      // 总额弹框
      moneyOpen: false,
      moneyLoading:true,
      // 应收还是应付 income / pay
      tableOr: "income",
      ableTotalAmountData: [],
      ableTotalAmounTotal: 0,
      deptId: null,

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deptId: null,
        ableAmount: null,
      },
      queryAccountDetailParams: {
        pageNum: 1,
        pageSize: 10,
        operateDeptId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      // 部门树选项
      deptOptions: [],
      disabled: false,
      operateOpen: false,
      cashOperateList: [],
      operateListTotal: 0,
    };
  },
  created() {
    console.log("userId===", this.$store.state.user.userId);
    console.log("deptId===", this.$store.state.user.deptId);
    if (this.$store.state.user.userId != 1) {
      this.queryParams.deptId = this.$store.state.user.deptId;
      this.disabled = true;
    }
    this.getList();
    this.getTreeselect();
  },
  methods: {
    /** 查询账户列表 */
    getList() {
      this.loading = true;
      listAccount(this.queryParams).then((response) => {
        console.log(response);
        this.accountList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getIncomeOrPayableList(queryParams, or) {
      if (or === "pay") {
        return getIncomeOrPayableList({
          ...queryParams,
          tradeDeptId: queryParams.deptId,
        });
      } else {
        return getIncomeOrPayableList({
          ...queryParams,
          applyDeptId: queryParams.deptId,
        });
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        accountId: null,
        deptId: null,
        ableAmount: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.accountId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加账户";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const accountId = row.accountId || this.ids;
      getAccount(accountId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改账户";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.accountId != null) {
            updateAccount(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAccount(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const accountIds = row.accountId || this.ids;
      this.$confirm(
        '是否确认删除账户编号为"' + accountIds + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return delAccount(accountIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有账户数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.exportLoading = true;
          return exportAccount(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
          this.exportLoading = false;
        })
        .catch(() => {});
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then((response) => {
        this.deptOptions = response.data;
      });
    },
    // 应收音符金额点击弹框 data是table传进来的数据，or是印绶还是应付
    moneyDialog(data, or, pageNum, pageSize) {
       this.tableOr = or;
      this.moneyOpen = true;
      this.ableTotalAmountData=[];
      this.moneyLoading=true;
      // 储存一下，好传参,点击进来的要
      this.deptId = data.deptId;
      const queryParams = {
        pageNum: pageNum ? pageNum : 1,
        pageSize: pageSize ? pageSize : 10,
        deptId: this.deptId,
      };

      this.getIncomeOrPayableList(queryParams, or).then((res) => {
        // console.log(res)
        this.ableTotalAmountData = res.rows;
        this.ableTotalAmounTotal=res.total;
        this.moneyLoading=false;
      });
      // // 应收还是应付
      // this.tableOr = or;
      // this.moneyOpen = true;
      // this.ableTotalAmountData = [];
    },
    //账户详情
    accountDetail(row) {
      this.operateOpen = true;
      this.queryAccountDetailParams.operateDeptId = row.deptId;
      this.getOperateList();
    },
    //账户操作记录查询
    getOperateList() {
      listOperate(this.queryAccountDetailParams).then((res) => {
        if (res.code == 200) {
          this.cashOperateList = res.rows;
          this.operateListTotal = res.total;
        }
      });
    },
  },
};
</script>
