<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               :search.sync="search"
               @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 @click="handleDownload">下載
        </el-button>
      </template>

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

      <template slot-scope="{disabled,size}" slot="categorySearch">
        <avue-input-tree :check-strictly="false" v-model="search.category" placeholder="請選擇內容" type="tree" :dic="typeList" :props="props"></avue-input-tree>
      </template>


    </avue-crud>
  </basic-container>
</template>

<script>
  import {getKeepList, getDetail, add, update, remove, getByCategoryAndType, getKeyType} from "@/api/bank/keypwd";
  import {mapGetters} from "vuex";
  import {dateFormat} from "../../util/date";
  import SelectDialogUser from "../../components/select-dialog/select-dialog-user";
  import { getCurrentDept } from "@/api/system/dept";
  import {getDeptTree, getTree} from "@/api/system/dept";

  export default {
    name: "keypwd-keep",
    components: {SelectDialogUser},
    data() {
      return {
        search: {},
        typeList: [],
        props:{
          label: "dictValue",
          value: "dictKey",
        },

        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        disabeldReceiver: false,
        disabeldHandover: true,
        selectionList: [],
        selectReceiver: '',
        selectHandover: '',
        type: '',
        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,

          dialogClickModal: false,
          column: [
            {
              label: "銀行號",
              prop: "bankNo",
              hide: true,
              disabled: true,
              search: true,
              searchSpan: 4,
              rules: [{
                required: true,
                message: "請輸入銀行號",
                trigger: "blur"
              }]
            },
            {
              label: "機構號",
              prop: "orgNo",
              hide: true,
              disabled: true,
              rules: [{
                required: true,
                message: "請輸入機構號",
                trigger: "blur"
              }]
            },
            {
              label: "機構名稱",
              prop: "orgName",
              disabled: 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: "category",
              search: true,
              checkStrictly: true,
              // multiple: true,
              dataType: "string",
              type: "tree",
              // dicUrl: "/api/blade-system/dict/dictionary?code=key_type",
              dicData: [],
              props:{
                label: "dictValue",
                value: "dictKey",
              },
              searchslot: true,
              change: ({value, column}) => {
                if (!value || this.type == 'view' || this.type == 'edit') return;
                getByCategoryAndType(value, this.form.orgNo).then(res => {
                  const data = res.data.data;
                  let $handoverNo = this.findObject(this.option.column, 'handoverPersonNo');
                  let $handoverName = this.findObject(this.option.column, 'handoverPersonName');
                  if (Object.keys(data).length == 0){
                    // $handoverNo.disabled = false;
                    this.form.handoverPersonNo = '';
                    this.form.handoverPersonName = '';
                  } else {
                    $handoverNo.disabled = true;
                    this.form.handoverPersonNo = data.receiverNo;
                    this.form.handoverPersonName = data.receiverName;
                  }
                });
              },
              rules: [{
                required: true,
                message: "請輸入分類",
                trigger: "blur"
              }]
            },

            /*{
              label: "種類",
              prop: "type",
              type: "select",
              dicUrl: "/api/blade-system/dict/dictionary?code={{key}}",
              props:{
                label: "dictValue",
                value: "dictKey",
              },
              change: ({value, column}) => {
                if (!value || this.type == 'view' || this.type == 'edit') return;
                getByCategoryAndType(this.form.category, value, this.form.orgNo).then(res => {
                  const data = res.data.data;
                  let $handoverNo = this.findObject(this.option.column, 'handoverPersonNo');
                  let $handoverName = this.findObject(this.option.column, 'handoverPersonName');
                  if (Object.keys(data).length == 0){
                    // $handoverNo.disabled = false;
                    this.form.handoverPersonNo = '';
                    this.form.handoverPersonName = '';
                  } else {
                    $handoverNo.disabled = true;
                    this.form.handoverPersonNo = data.receiverNo;
                    this.form.handoverPersonName = data.receiverName;
                  }
                });
              },
              rules: [{
                required: true,
                message: "請輸入種類",
                trigger: "blur"
              }]
            },*/
            {
              label: "數量",
              prop: "number",
              type: "number",
              disabled: true,
              rules: [{
                required: true,
                message: "請輸入數量",
                trigger: "blur"
              }]
            },
            {
              label: "交出人",
              prop: "handoverPersonName",
              formslot:  true,
              hide: true,
              rules: [{
                required: false,
                message: "請輸入交出人姓名",
                trigger: "blur"
              }]
            },
            {
              label: "交出人員工號",
              prop: "handoverPersonNo",
              disabled: true,
              hide: true,
              rules: [{
                required: false,
                message: "請輸入交出人員工號",
                trigger: "blur"
              }]
            },
            {
              label: "保管人",
              prop: "receiverName",
              search: true,
              searchPlaceholder: "保管人",
              searchTip: "保管人",
              searchSpan: 4,
              formslot:  true,
              rules: [{
                required: true,
                message: "請輸入接收人員工號",
                trigger: "focus"
              }]
            },
            {
              label: "保管人員工號",
              prop: "receiverNo",
              disabled: true,
              rules: [{
                required: true,
                message: "請輸入接收人員工號",
                trigger: "change"
              }]
            },
            {
              label: "開始保管時間",
              prop: "handoverDate",
              type: "datetime",
              format: "yyyy-MM-dd HH:mm",
              valueFormat: "yyyy-MM-dd HH:mm",
            },
            {
              label: "備註",
              prop: "remark",
              hide: true,
            },
            {
              label: "填報時間",
              prop: "fillingDate",
              addDisplay: false,
              editDisplay: false,
              hide: true,

            },
            {
              label: "填報人",
              prop: "fillingPerson",
              addDisplay: false,
              editDisplay: false,
              hide: true,
            },
          ]
        },
        data: []
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      ...mapGetters(["userInfo"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.keypwd_add, false),
          viewBtn: this.vaildData(this.permission.keypwd_view, false),
          delBtn: this.vaildData(this.permission.keypwd_delete, false),
          editBtn: this.vaildData(this.permission.keypwd_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    created() {
      this.initTypeDict();
      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
        });
      },
      initTypeDict(){
        getKeyType().then(res => {

          let data = res.data.data;
          let pid = new Set();
          for (let i = 0; i < data.length; i++) {
            let item = data[i];
            pid.add(item.parentId);
          }
          let arr = [];
          pid.forEach(id => {
            data.forEach(item => {
              if (id == item.id){
                arr.push(item)
              }
            })
          })
          arr.forEach(item => {
            data.forEach(it => {
              if (item.id == it.parentId){
                if (!item.children){
                  item.children = [];
                }
                it.dictValue = item.dictValue + '-' + it.dictValue;
                item.children.push(it)
                item.hasChildren = true;
              }
            })
          })
          this.typeList = arr;
          this.findObject(this.option.column, 'category').dicData = arr;
          return arr;
        })
      },
      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) {
        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'){
          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;
            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.category){
          params.category = params.category.join();
        }
        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;
      },
      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;
        getKeepList(params).then(res => {
          const data = res.data.data;
          this.data = data;
          this.loading = false;
          this.selectionClear();
        });
      }
    }
  };
</script>

<style>
</style>
