<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-button type="primary"
                   size="small"
                   icon="el-icon-download"
                   plain
                   v-if="permission.goodsuse_download"
                   @click="handleDownload">下載
        </el-button>
      </template>

      <template slot="process" slot-scope="{row, index}">
        <el-tag size="small " type="warning" plain v-if="row.process == 2">待確認</el-tag>
        <el-tag size="small " type="success" plain v-if="row.process == 3">已確認</el-tag>
      </template>
    </avue-crud>

  </basic-container>
</template>

<script>
  import {getBalanceList, getDetail} from "@/api/bank/goodsuse";
  import {mapGetters} from "vuex";
  import {dateFormat} from "../../util/date";
  import { getCurrentDept } from "@/api/system/dept";
  import {getDeptTree, getTree} from "@/api/system/dept";

  export default {
    name: 'goodsuse-balance',
    data() {
      return {
        type: '',
        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          height:'auto',
          calcHeight: 30,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          viewBtn: true,
          addBtn: false,
          editBtn: false,
          delBtn: false,
          selection: true,
          menu: false,
          // header: false,

          dialogClickModal: false,
          column: [
            {
              label: "銀行號",
              prop: "bankNo",
              span: 24,
              hide: true,
              disabled: true,
              search: false,
              display: false,
              searchSpan: 4,
              rules: [{
                required: true,
                message: "請輸入銀行號",
                trigger: "blur"
              }]
            },
            {
              label: "機構號",
              prop: "orgNo",
              hide: true,
              disabled: true,
              display: false,
              rules: [{
                required: true,
                message: "請輸入機構號",
                trigger: "blur"
              }]
            },
            {
              label: "機構名稱",
              prop: "orgName",
              span: 24,
              disabled: true,
              rules: [{
                required: true,
                message: "請輸入機構號",
                trigger: "blur"
              }]
            },
            {
              label: "日期",
              prop: "date",
              type: "datetime",
              format: "yyyy-MM-dd",
              valueFormat: "yyyy-MM-dd",
              rules: [{
                required: true,
                message: "請輸入日期",
                trigger: "blur"
              }]
            },
            {
              label: "日期",
              prop: "dateRange",
              type: "date",
              format: "yyyy-MM-dd",
              valueFormat: "yyyy-MM-dd",
              searchRange:true,
              hide: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false,
              // search: true,
              rules: [{
                required: true,
                message: "請輸入交接日期",
                trigger: "blur"
              }]
            },
            {
              label: "區域/支行",
              prop: "orgNos",
              hide: true,
              display: false,
              searchMultiple: true,
              // search: true,
              type: "tree",
              dicData: [],
              props: {
                label: "title",
                value: "key"
              },
              checkStrictly: true,

            },
            {
              label: "憑證/實物種類",
              prop: "type",
              type: "select",
              // search: true,
              searchSpan: 4,
              searchMultiple: true,
              dicUrl: "/api/blade-system/dict/dictionary?code=voucher_type",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              dicFormatter: (res) => {
                res.data.forEach(item => {item.disabled = item.isSealed == 1;})
                return res.data;
              },
            },
            {
              label: "餘額",
              prop: "balance",
              type: "number",
              disabled: true,
            },

            {
              label: "填報時間",
              prop: "fillingDate",
              addDisplay: false,
              editDisplay: false,
            },
            {
              label: "填報人",
              prop: "fillingName",
              addDisplay: false,
              editDisplay: false,
            },
            {
              label: "進度",
              prop: "process",
              display: false,
              rules: [{
                required: true,
                message: "請輸入節點",
                trigger: "blur"
              }]
            },
            {
              label: "審批時間",
              prop: "approveTime",
              hide: true,
              addDisplay: false,
              editDisplay: false,

            },
          ]
        },
        data: []
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      ...mapGetters(["userInfo"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.goodsuse_add, false),
          viewBtn: this.vaildData(this.permission.goodsuse_view, false),
          delBtn: this.vaildData(this.permission.goodsuse_delete, false),
          editBtn: this.vaildData(this.permission.goodsuse_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    watch: {
      'form.useNumber': {
        handler: function(value) {
          this.calcBalance();
        }
      },
      'form.receiptNumber': {
        handler: function(value) {
          this.calcBalance();
        }
      },
      'form.writeOffNumber': {
        handler: function(value) {
          this.calcBalance();
        }
      },
      'form.type': {
        handler: function(value) {
          this.calcBalance();
        }
      },

    },
    mounted() {
      getDeptTree().then(res => {
        const column = this.findObject(this.option.column, "orgNos");
        let treeData = getTree(res.data.data, this.userInfo.dept_id);
        column.dicData = treeData;
      });
    },
    methods: {
      handleDownload(){
        if (this.selectionList.length === 0) {
          this.$message.warning("請選擇至少一條數據");
          return;
        }
        let columns = this.deepClone(this.option.column);
        for (let i = 0; i < columns.length; i++) {
          let item = columns[i];
          if (item.hide || item.prop == 'process'){
            columns.splice(i, 1);
            i--;
          }
          if (item.type == 'select' || item.type == 'tree'){
            item.prop = '$' + item.prop;
          }
        }
        this.$Export.excel({
          title: "使用及出入庫登記表" || new Date().getTime(),
          columns: columns,
          data: this.selectionList
        });
      },
      beforeOpen(done, type) {
        this.type = type;
        if (type === 'add'){
          this.form.writeOffNumber = 0;
          this.form.receiptNumber = 0;
          this.form.handoverDate = dateFormat(new Date(), "yyyy-MM-dd hh:mm");

          this.calcBalance();

          getCurrentDept().then(res => {
            const data =  res.data.data;
            this.form.bankNo = data.bankNo;
            this.form.orgNo = data.orgNo;
            this.form.orgName = data.deptName;
          });
        }
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        if (params.dateRange){
          params.date_begin = params.dateRange[0], params.date_end = params.dateRange[1];
          params.dateRange = null;
        }
        if (params.orgNos){
          params.orgNostr = params.orgNos.join();
          params.orgNos = '';
        }
        if (params.type){
          params.type = params.type.join();
        }

        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getBalanceList().then(res => {
          const data = res.data.data;
          this.data = data;
          this.loading = false;
          this.selectionClear();
        });
      }
    }
  };
</script>

<style>
</style>
