<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"
               :search.sync="search"
               @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.sealhandover_delete"
                   @click="handleDelete">刪 除
        </el-button>
        <el-button type="success"
                   size="small"
                   icon="el-icon-search"
                   plain
                   v-if="permission.sealhandover_keep_view"
                   @click="keepVisible = true">保管人查詢
        </el-button>
        <el-button type="primary"
                   size="small"
                   icon="el-icon-download"
                   plain
                   v-if="permission.sealhandover_download"
                   @click="handleDownload">下載
        </el-button>
      </template>

      <template slot="menu" slot-scope="{row, index}">
        <el-button size="small" class="el-button--text" v-if="permission.sealhandover_edit && 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.sealhandover_delete && userInfo.user_id == row.createUser" @click="$refs.crud.rowDel(row, index)"><i class="el-icon-delete"></i> 刪 除</el-button>
      </template>

      <template slot="receiverNameForm">
        <select-dialog-user :name="form.receiverName" :ehr="form.receiverNo" :disabled="receiverDisabled" :callback="selectCallback"></select-dialog-user>
      </template>
      <template slot="handoverPersonNameForm">
        <select-dialog-user :name="form.handoverPersonName" :ehr="form.handoverPersonNo" :disabled="true" :callback="handoverSelectCallback"></select-dialog-user>
      </template>

      <template slot-scope="{disabled,size}" slot="sealNoSearch">
        <!--        <avue-input placeholder="請選擇內容" v-model="search.sealNos"></avue-input>-->
        <el-input placeholder="請輸入印章編號" v-model="search.sealNo"></el-input>
      </template>

      <template slot="titleForm" slot-scope="{row, index}">
        <div v-html="title" style="white-space: pre-line;font-size: 8px;"></div>
      </template>

      <template slot="isTurnIn" slot-scope="{row, index}">
        <!--        <el-checkbox v-model="row.isTurnIn" @change="turnInChange"></el-checkbox>-->
        <el-tag size="small " type="success" plain v-if="row.isTurnIn == 1">上繳至上級單位</el-tag>
        <el-tag size="small " type="danger" plain v-if="row.isTurnIn == 0">非上繳</el-tag>
      </template>

      <template slot="isTurnInForm" slot-scope="{row, index}">
        <el-checkbox v-model="row.isTurnIn" @change="turnInChange"></el-checkbox>
        <el-tag size="small " type="success" plain v-if="row.isTurnIn == 1">上繳至上級單位</el-tag>
        <el-tag size="small " type="danger" plain v-if="row.isTurnIn == 0">非上繳</el-tag>
      </template>

    </avue-crud>

    <el-dialog :append-to-body="true" :modal-append-to-body="false" :destroy-on-close="true" :fullscreen="true" :visible.sync="keepVisible" title="保管人查詢">
      <sealhandover-keep></sealhandover-keep>
    </el-dialog>

  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove, getByNoAndType, getDownloadList} from "@/api/bank/sealhandover";
  import {mapGetters} from "vuex";
  import { getCurrentDept } from "@/api/system/dept";
  import {dateFormat} from "../../util/date";
  import SelectDialogUser from "../../components/select-dialog/select-dialog-user";
  import {getDeptTree, getTree} from "@/api/system/dept";
  import SealhandoverKeep from "./sealhandover-keep";
  import {getStandardByCode} from "@/api/bank/handoverstandard";

  export default {
    components: {SealhandoverKeep, SelectDialogUser},
    data() {
      return {
        title: "",
        search: {},
        receiverDisabled: false,
        keepVisible: false,
        delBatchBtn: true,

        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: true,
          editBtn: false,
          delBtn: false,
          selection: true,
          dialogClickModal: false,
          column: [
            {
              label: '交接標準',
              prop: 'title',
              hide: true,
              formslot: true,
              type: 'text',
              span: 24
            },
            {
              label: "銀行號",
              prop: "bankNo",
              disabled: true,
              search: true,
              searchSpan: 4,
              rules: [{
                required: true,
                message: "請輸入銀行號",
                trigger: "blur"
              }]
            },
            {
              label: "機構號",
              prop: "orgNo",
              disabled: true,
              rules: [{
                required: true,
                message: "請輸入機構號",
                trigger: "blur"
              }]
            },
            {
              label: "印章類型",
              prop: "sealTypeSearch",
              type: "select",
              dicUrl: "/api/blade-system/dict/dictionary?code=seal_type",
              props:{
                label: "dictValue",
                value: "dictKey",
              },dicFormatter: (res) => {
                res.data.forEach(item => {item.disabled = item.isSealed == 1;})
                return res.data;
              },
              search: true,
              hide: true,
              display: false,
              searchMultiple: true,
            },
            {
              label: "印章類型",
              prop: "sealType",
              type: "select",
              dicUrl: "/api/blade-system/dict/dictionary?code=seal_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: "sealNo",
              search: true,
              searchSpan: 4,
              searchslot: true,
              change: ({value, column}) => {
                if (!value) return;
                getByNoAndType(value, this.form.sealType, this.form.orgNo).then(res => {
                  const data = res.data.data;
                  let $handoverNo = this.findObject(this.option.column, 'handoverPersonNo');
                  if (Object.keys(data).length == 0){
                    // $handoverNo.disabled = false;
                    this.form.handoverPersonNo = '';
                    delete this.form.handoverPersonName;
                    this.receiverDisabled = false;
                  } else {
                    // $handoverNo.disabled = true;
                    // 編輯時，若記錄為自己，則跳過
                    if (this.form.id == data.id){
                      return;
                    }
                    if (data.isTurnIn == 1){
                      this.$message.warning("此印章已上繳，請重新選擇！");
                      this.receiverDisabled = true;
                    }else{
                      this.receiverDisabled = false;
                    }
                    this.form.handoverPersonNo = data.receiverNo;
                    this.form.handoverPersonName = data.receiverName;
                  }
                });
              },
              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: "handoverPersonName",
              formslot: true,
              rules: [{
                required: false,
                message: "請輸入交出人姓名",
                trigger: "change"
              }]
            },
            {
              label: "交出人員工號",
              prop: "handoverPersonNo",
              disabled: true,
              rules: [{
                required: false,
                message: "請輸入交出人員工號",
                trigger: "blur"
              }]
            },
            {
              label: "交接日期",
              prop: "handoverDate",
              type: "datetime",
              format: "yyyy-MM-dd HH:mm",
              valueFormat: "yyyy-MM-dd HH:mm",
              rules: [{
                required: true,
                message: "請輸入交接日期",
                trigger: "blur"
              }]
            },
            {
              label: "是否上繳",
              prop: "isTurnIn",
              formslot: true,
              rules: [{
                required: false,
                message: "請勾選是否上繳",
                trigger: "blur"
              }]
            },
            {
              label: "接收人",
              prop: "receiverName",
              search: true,
              searchPlaceholder: "保管人",
              searchTip: "保管人",
              searchSpan: 4,
              formslot: true,
              rules: [{
                required: true,
                message: "請輸入接收人姓名",
                trigger: "change"
              }]
            },
            {
              label: "交接日期",
              prop: "handoverDateRange",
              type: "datetime",
              format: "yyyy-MM-dd HH:mm",
              valueFormat: "yyyy-MM-dd HH:mm",
              searchRange:true,
              hide: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false,
              search: true,
              rules: [{
                required: true,
                message: "請輸入交接日期",
                trigger: "blur"
              }]
            },
            {
              label: "接收人員工號",
              prop: "receiverNo",
              disabled: true,
              rules: [{
                required: true,
                message: "請輸入接收人員工號",
                trigger: "blur"
              }]
            },
            {
              label: "備註",
              prop: "remark",
              rules: [{
                required: false,
                message: "請輸入備註",
                trigger: "blur"
              }]
            },
            {
              label: "填報時間",
              prop: "fillingDate",
              addDisplay: false,
              editDisplay: false,
              rules: [{
                required: true,
                message: "請輸入填報時間",
                trigger: "blur"
              }]
            },
            {
              label: "填報人",
              prop: "fillingPerson",
              addDisplay: false,
              editDisplay: false,
              rules: [{
                required: true,
                message: "請輸入填報人",
                trigger: "blur"
              }]
            },
          ]
        },
        data: []
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      ...mapGetters(["userInfo"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.sealhandover_add, false),
          viewBtn: this.vaildData(this.permission.sealhandover_view, false),
          delBtn: this.vaildData(this.permission.sealhandover_delete, false),
          editBtn: this.vaildData(this.permission.sealhandover_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    created() {
      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("sealhandover").then(res => {
        const data = res.data.data;
        if (Object.keys(data).length > 0){
          this.title = data.content;
        }else {
          this.option.column.splice(0,1)
        }
      });
    },
    methods: {
      turnInChange(value){
        this.findObject(this.option.column, "receiverNo").rules[0].required = !value;
        this.findObject(this.option.column, "receiverName").rules[0].required = !value;
        this.receiverDisabled = !!value;
      },
      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
        });
      },
      handoverSelectCallback(value){
        this.form.handoverPersonNo = value.ehr;
        this.form.handoverPersonName = value.name;
      },
      selectCallback(value){
        this.form.receiverNo = value.ehr;
        this.form.receiverName = value.name;
      },
      rowSave(row, done, loading) {
        row.isTurnIn = !row.isTurnIn ? 0 : 1;
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        row.isTurnIn = !row.isTurnIn ? 0 : 1;
        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) {
        if (type === 'add'){
          let userInfo = localStorage.getItem("saber-userInfo");
          this.form.number = 1;
          this.form.handoverDate = dateFormat(new Date(), "yyyy-MM-dd hh:mm");
          getCurrentDept().then(res => {
            const data =  res.data.data;
            this.form.bankNo = data.bankNo;
            this.form.orgNo = data.orgNo;
          });
        }

        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.sealTypeSearch){
          params.sealType = params.sealTypeSearch.join();
          params.sealTypeSearch = [];
        }
        if (params.orgNos){
          params.orgNostr = params.orgNos.join();
          params.orgNos = '';
        }
        if (params.handoverDateRange){
          params.handoverDate_begin = params.handoverDateRange[0], params.handoverDate_end = params.handoverDateRange[1];
          params.handoverDateRange = null;
        }

        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;
          // permission.keypwd_delete && userInfo.user_id == row.createUser
          for (let i = 0; i < list.length; i++) {
            let item = list[i];
            delFlag = delFlag && item.createUser == this.userInfo.user_id;
          }
          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;
        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>
