<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page.sync="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @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="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   :disabled="delBatchBtn"
                   v-if="permission.goodsuse_delete"
                   @click="handleDelete">刪 除
        </el-button>
        <!--<el-button type="success"
                   size="small"
                   icon="el-icon-setting"
                   plain
                   v-if="permission.goodsuse_setting"
                   @click="handleSetting">設置確認人
        </el-button>-->
        <el-button type="success"
                   size="small"
                   icon="el-icon-refresh"
                   plain
                   v-if="permission.goodsuse_transfer"
                   @click="handleTransfer">一鍵移交
        </el-button>
        <el-button type="primary"
                   size="small"
                   icon="el-icon-download"
                   plain
                   v-if="permission.goodsuse_download"
                   @click="handleDownload">下載
        </el-button>
        <el-button type="success"
                   size="small"
                   icon="el-icon-search"
                   plain
                   @click="balanceVisible = true">餘額查詢
        </el-button>
      </template>

      <template slot="personNameForm">
        <select-dialog-user :id="form.personId" :name="form.personName" :ehr="form.personNo" :disabled="false" :callback="selectCallback"></select-dialog-user>
      </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>
      <template slot="menu" slot-scope="{row, index}">
        <el-button size="small" class="el-button--text" v-if="permission.goodsuse_view" @click="$refs.crud.rowView(row, index)"><i class="el-icon-view"></i> 查 看</el-button>
        <el-button size="small" class="el-button--text" v-if="permission.goodsuse_edit && row.process == 2 && userInfo.user_id == row.createUser" @click="$refs.crud.rowEdit(row, index)"><i class="el-icon-edit"></i> 編 輯</el-button>
        <el-button size="small" class="el-button--text" v-if="permission.goodsuse_delete && row.process == 2 && userInfo.user_id == row.createUser" @click="$refs.crud.rowDel(row, index)"><i class="el-icon-delete"></i> 刪 除</el-button>
        <el-button size="small" class="el-button--text" v-if="permission.goodsuse_confirm && row.process == 2 && row.personNo == userInfo.user_ehr" @click="form = row, sureVisible = true"> 確 認</el-button>
      </template>
    </avue-crud>

    <el-dialog :append-to-body="true" :modal-append-to-body="false" :visible.sync="settingVisible" title="設置">
      <flow-settings :id="personId" :ehr="personNo" :name="personName" :callback="settingCallback" @close="settingVisible = false"></flow-settings>
    </el-dialog>

    <el-dialog :append-to-body="true" :modal-append-to-body="false" :visible.sync="sureVisible" title="確認">
      <goodsuse-sure :form="form" @close="sureVisible = false, onLoad(page)"></goodsuse-sure>
    </el-dialog>

    <el-dialog :append-to-body="true" :modal-append-to-body="false" :visible.sync="transferVisible" title="一鍵移交">
      <div v-if="transferVisible">
        <select-dialog-user :callback="transferCallback"></select-dialog-user>
      </div>
    </el-dialog>

    <el-dialog :append-to-body="true" :modal-append-to-body="false" :destroy-on-close="true" :fullscreen="true" :visible.sync="balanceVisible" title="餘額查詢">
      <goodsuse-balance></goodsuse-balance>
    </el-dialog>

  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove, getSetting, settingSave, transfer, getLastByType, getDownloadList} from "@/api/bank/goodsuse";
  import {mapGetters} from "vuex";
  import FlowSettings from "../../components/common/flow-settings";
  import {dateFormat} from "../../util/date";
  import { getCurrentDept } from "@/api/system/dept";
  import SelectDialogUser from "../../components/select-dialog/select-dialog-user";
  import GoodsuseSure from "../../components/common/goodsuse-sure";
  import {getDeptTree, getTree} from "@/api/system/dept";
  import {getStandardByCode} from "@/api/bank/handoverstandard";
  import {validatenumplus} from "../../util/validate";
  import GoodsuseBalance from "../../views/bank/goodsuse-balance";

  export default {
    name: "init-goodsuse",
    components: {GoodsuseBalance, GoodsuseSure, SelectDialogUser, FlowSettings},
    data() {
      return {
        isManageUser: false,

        balanceVisible: false,
        transferVisible: false,
        delBatchBtn: true,

        personId: null,
        personNo: null,
        personName: null,
        settingVisible: false,

        sureVisible: false,

        type: '',
        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          addTitle: '新增【使用及出入庫登記表】',
          editTitle: '編輯【使用及出入庫登記表】',
          viewTitle: '查看【使用及出入庫登記表】',
          height:'auto',
          calcHeight: 30,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          viewBtn: false,
          editBtn: false,
          delBtn: false,
          selection: true,
          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",
              disabled: true,
              span: 24,
              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,
              rules: [{
                required: true,
                message: "請輸入機構號",
                trigger: "blur"
              }]
            },
            {
              label: "憑證/實物種類",
              prop: "typeSearch",
              type: "select",
              search: true,
              hide: true,
              display: false,
              searchSpan: 4,
              searchMultiple: true,
              dicUrl: "/api/blade-system/dict/dictionary?code=voucher_type",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
            },
            {
              label: "憑證/實物種類",
              prop: "type",
              type: "select",
              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;
              },
              rules: [{
                required: true,
                message: "請輸入憑證/實物種類",
                trigger: "blur"
              }]
            },
            {
              label: "使用數量",
              prop: "useNumber",
              type: "number",
              rules: [{
                required: true,
                message: "請輸入使用數量",
                trigger: "blur"
              },{
                validator: validatenumplus,
                trigger: "blur"
              }]
            },
            {
              label: "領入數量",
              prop: "receiptNumber",
              type: "number",
              rules: [{
                required: false,
                message: "請輸入領入數量",
                trigger: "blur"
              },{
                validator: validatenumplus,
                trigger: "blur"
              }]
            },
            {
              label: "註銷數量",
              prop: "writeOffNumber",
              type: "number",
              rules: [{
                required: false,
                message: "請輸入註銷數量",
                trigger: "blur"
              },{
                validator: validatenumplus,
                trigger: "blur"
              }]
            },
            {
              label: "開始編號",
              prop: "beginNo",
              rules: [{
                required: false,
                message: "請輸入開始編號",
                trigger: "blur"
              }]
            },
            {
              label: "結束編號",
              prop: "endNo",
              rules: [{
                required: false,
                message: "請輸入結束編號",
                trigger: "blur"
              }]
            },
            {
              label: "上日餘額",
              prop: "lastBalance",
              type: "number",
              disabled: true,
              hide: true,
              viewDisplay: false,
              rules: [{
                required: true,
                message: "請輸入餘額",
                trigger: "blur"
              },{
                validator: validatenumplus,
                trigger: "blur"
              }]
            },
            {
              label: "餘額",
              prop: "balance",
              type: "number",
              disabled: true,
              rules: [{
                required: true,
                message: "請輸入餘額",
                trigger: "blur"
              },{
                validator: validatenumplus,
                trigger: "blur"
              }]
            },
            {
              label: "備註",
              prop: "remark",
              rules: [{
                required: false,
                message: "請輸入備註",
                trigger: "blur"
              }]
            },
            {
              label: "填報人員工號",
              prop: "fillingNo",
              addDisplay: false,
              editDisplay: false,
              rules: [{
                required: true,
                message: "請輸入填報人員工號",
                trigger: "blur"
              }]
            },
            {
              label: "填報人姓名",
              prop: "fillingName",
              addDisplay: false,
              editDisplay: false,
              rules: [{
                required: true,
                message: "請輸入填報人姓名",
                trigger: "blur"
              }]
            },
            /* {
               label: "確認人員工號",
               prop: "confirmNo",
               hide: true,
               addDisplay: false,
               rules: [{
                 required: true,
                 message: "請輸入確認人員工號",
                 trigger: "blur"
               }]
             },
             {
               label: "確認人姓名",
               prop: "confirmName",
               hide: true,
               addDisplay: false,
               rules: [{
                 required: true,
                 message: "請輸入確認人姓名",
                 trigger: "blur"
               }]
             },*/


            {
              label: "確認人",
              prop: "personName",
              hide: true,
              // addDisplay: false,
              rules: [{
                required: true,
                message: "請輸入審批人",
                trigger: "change"
              }]
            },
            {
              label: "確認人員工號",
              prop: "personNo",
              hide: true,
              // addDisplay: false,
              disabled: true,
              rules: [{
                required: true,
                message: "請輸入",
                trigger: "blur"
              }]
            },
            {
              label: "填報時間",
              prop: "fillingDate",
              addDisplay: false,
              editDisplay: false,
              rules: [{
                required: true,
                message: "請輸入填報日期及時間",
                trigger: "blur"
              }]
            },
            {
              label: "審批時間",
              prop: "approveTime",
              hide: true,
              addDisplay: false,
              editDisplay: false,
              rules: [{
                required: true,
                message: "請輸入審批時間",
                trigger: "blur"
              }]
            },
            {
              label: "進度",
              prop: "process",
              display: false,
              rules: [{
                required: true,
                message: "請輸入節點",
                trigger: "blur"
              }]
            },
            {
              label: "是否已完成",
              prop: "isCompleted",
              hide: true,
              display: false,
              rules: [{
                required: true,
                message: "請輸入是否已完成",
                trigger: "blur"
              }]
            },
          ]
        },
        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;
      });
      /*getStandardByCode("goodsuse").then(res => {
        const data = res.data.data;
        if (data){
          this.option.addTitle = data.content;
          this.option.editTitle = data.content;
          this.option.viewTitle = data.content;
        }
      });*/
    },
    methods: {
      handleDownload(){
        if (this.selectionList.length === 0) {
          let tip = "確定下載篩選的" + this.page.total + "條數據嗎？"
          this.$confirm(tip, {
            confirmButtonText: "確定",
            cancelButtonText: "取消",
            type: "warning"
          })
            .then(() => {
              getDownloadList(this.query).then(res => {
                this.downLoadData(res.data.data, true)
              });
            })
        }else{
          this.downLoadData(this.selectionList, false)
        }
      },
      downLoadData(data, isAll){
        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 (!isAll && (item.type == 'select' || item.type == 'tree')){
            item.prop = '$' + item.prop;
          }
        }
        this.$Export.excel({
          title: "使用及出入庫登記表" || new Date().getTime(),
          columns: columns,
          data: data
        });
      },
      calcBalance(){
        /*if (this.type != 'add'){
          return;
        }*/
        if (!this.form.type || this.form.useNumber == undefined){
          return;
        }
        if (!this.form.receiptNumber){
          this.form.receiptNumber = 0;
        }
        if (!this.form.writeOffNumber){
          this.form.writeOffNumber = 0;
        }
        getLastByType(this.form.type).then(res => {
          const data = res.data.data;
          let lastBalance = 0;
          this.form.lastBalance = 0;

          if (data && Object.keys(data).length > 0){
            lastBalance = data.balance;
            this.form.lastBalance = lastBalance;
          }
          this.form.balance = lastBalance + this.form.receiptNumber - this.form.writeOffNumber - this.form.useNumber;
        });
      },
      transferCallback(row){
        if (this.selectionList && this.selectionList.length > 0 && this.selectionList[0].personNo == row.ehr){
          this.$message.warning("移交人不能為原審批人，請重新選擇！")
          return;
        }
        transfer(this.ids, row.ehr).then(() => {
          this.onLoad(this.page);
          this.transferVisible = false;
          this.$message({
            type: "success",
            message: "移交成功!"
          });
        });
      },
      selectCallback(row){
        this.form.personId = row.id;
        this.form.personNo = row.ehr;
        this.form.personName = row.name;
      },
      settingCallback(row){
        this.form.personId = row.personId;
        this.form.personNo = row.personNo;
        this.form.personName = row.personName;
        settingSave(this.form).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log('error');
        });
      },
      handleSetting(){
        getSetting().then((res) => {
          let data = res.data.data;
          if (!!data){
            this.personId = data.personId;
            this.personNo = data.personNo;
            this.personName = data.personName;
          }
        });
        this.settingVisible = true;
      },
      handleTransfer(){
        if (this.selectionList.length === 0) {
          this.$message.warning("請選擇至少一條數據");
          return;
        }
        let personSet = new Set(), processSet = new Set();
        for (let i = 0; i < this.selectionList.length; i++) {
          let item = this.selectionList[i];
          personSet.add(item.personNo);
          processSet.add(item.process)
        }
        if (personSet.size > 1 || processSet.size > 1 || !processSet.has(2)){
          this.$message.warning("請選擇同一人員的待確認任務！");
          return;
        }
        this.transferVisible = true;
      },
      rowSave(row, done, loading) {
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("確定將選擇數據刪除?", {
          confirmButtonText: "確定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("請選擇至少一條數據");
          return;
        }
        this.$confirm("確定將選擇數據刪除?", {
          confirmButtonText: "確定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      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;
          });

          /*getSetting().then((res) => {
            let data = res.data.data;
            if (!!data) {
              this.form.personId = data.personId;
              this.form.personNo = data.personNo;
              this.form.personName = data.personName;
            }
          })*/

          /*let userInfoStr = localStorage.getItem("saber-userInfo");
          let userInfo = JSON.parse(userInfoStr);
          this.form.personId =userInfo.content.user_id;
          this.form.personNo =userInfo.content.user_ehr;
          this.form.personName =userInfo.content.user_name;*/
        }
        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.typeSearch){
          params.type = params.typeSearch.join();
        }

        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
        if (list && list.length > 0){
          let delFlag = true;
          // userInfo.user_id == row.createUser && row.process != 3
          for (let i = 0; i < list.length; i++) {
            let item = list[i];
            delFlag = delFlag && item.createUser == this.userInfo.user_id && item.process != 3;
          }
          this.delBatchBtn = !delFlag;
        }else{
          this.delBatchBtn = true;
        }
      },
      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;
        params.createUser = this.userInfo.user_id;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      }
    }
  };
</script>

<style>
</style>
