<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
                   v-if="permission.checkwarehouse_delete"
                   @click="handleDelete">刪 除
        </el-button>
        <el-button type="primary"
                   size="small"
                   icon="el-icon-download"
                   plain
                   v-if="permission.checkwarehouse_download"
                   @click="handleDownload">下載
        </el-button>
      </template>

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

        <el-button type="text" icon="el-icon-download" size="small" v-if="permission.checkwarehouse_download_file && row.enclosure" @click="fileDownload(row)">附件下載</el-button>
      </template>

      <!-- <template slot="checkPersonNameForm">
         <select-dialog-user :name="form.checkPersonName" :ehr="form.checkPersonNo" :disabled="false" :callback="selectCallback"></select-dialog-user>
       </template>-->

      <template slot="enclosureForm" slot-scope="{row}">
        <avue-form ref="form" :option="attachOption" v-model="attachForm" :upload-after="uploadAfter" :upload-error="uploadError" :upload-delete="uploadDelete" :upload-preview="uploadPreview">
        </avue-form>
      </template>

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

    </avue-crud>

  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove, getDownloadList} from "@/api/bank/checkwarehouse";
  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 {getStandardByCode} from "@/api/bank/handoverstandard";
  import {downloadFileBase64} from "@/util/util";

  export default {
    name: "init-checkwarehouse",
    components: {SelectDialogUser},
    data() {
      return {
        title: "",
        attachBox: false,
        attachForm: {},
        attachOption: {
          submitBtn: false,
          emptyBtn: false,
          column: [
            {
              // label: '附件上傳',
              prop: 'attachFile',
              type: 'upload',
              disabled: true,
              drag: true,
              loadText: '模板上傳中，請稍等',
              span: 24,
              fileSize: 5120,
              propsHttp: {
                res: 'data'
              },
              name: "namesrc",
              action: "/api/blade-resource/oss/endpoint/put-file-attach"
            }
          ]
        },

        form: {
        },
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          addTitle: '新增【查庫流水帳記錄表】',
          editTitle: '編輯【查庫流水帳記錄表】',
          viewTitle: '查看【查庫流水帳記錄表】',
          height:'auto',
          calcHeight: 30,
          index: false,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          viewBtn: true,
          editBtn: false,
          delBtn: false,
          selection: true,
          dialogClickModal: false,
          column: [
            {
              label: '交接標準',
              prop: 'title',
              formslot: true,
              hide: true,
              type: 'text',
              span: 24
            },
            {
              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"
              }]
            },
            {
              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: "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: "checkTimeRange",
              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: "checkTimeBegin",
              type: "datetime",
              format: "yyyy-MM-dd HH:mm",
              valueFormat: "yyyy-MM-dd HH:mm",
              rules: [{
                required: true,
                message: "請輸入檢查時間開始",
                trigger: "blur"
              }]
            },
            {
              label: "檢查時間結束",
              prop: "checkTimeEnd",
              type: "datetime",
              format: "yyyy-MM-dd HH:mm",
              valueFormat: "yyyy-MM-dd HH:mm",
              rules: [{
                required: true,
                message: "請輸入檢查時間結束",
                trigger: "blur"
              }]
            },
            {
              label: "檢查單位",
              prop: "checkUnit",
              type: "select",
              search: true,
              searchSpan: 4,
              multiple: true,
              dicUrl: "/api/blade-system/dict/dictionary?code=unit_type",
              props:{
                label: "dictValue",
                value: "dictKey",
              },
              dicFormatter: (res) => {
                res.data.forEach(item => {item.disabled = item.isSealed == 1;})
                return res.data;
              },
              change: ({value, column}) => {
                /*if (!value) return;
                let $nameOut = this.findObject(this.option.column, 'checkPersonNameOut');
                $nameOut.display = value != '1';
                let $noOut = this.findObject(this.option.column, 'checkPersonNoOut');
                $noOut.display = value != '1';
                let $name = this.findObject(this.option.column, 'checkPersonName');
                $name.display = value == '1';
                let $no = this.findObject(this.option.column, 'checkPersonNo');
                $no.display = value == '1';
                $no.disabled = value == '1';
                if (!this.form.checkResult) return;
                let $remark = this.findObject(this.option.column, 'remark');
                if (value == '1' && this.form.checkResult == '1'){
                  $remark.rules[0].required = false;
                }else{
                  $remark.rules[0].required = true;
                }*/
              },
              rules: [{
                required: true,
                message: "請輸入檢查單位",
                trigger: "blur"
              }]
            },
            {
              label: "檢查目的",
              prop: "checkPurpose",
              type: "select",
              dicUrl: "/api/blade-system/dict/dictionary?code=check_purpose",
              props:{
                label: "dictValue",
                value: "dictKey",
              },
              multiple: true,
              search: true,
              searchSpan: 4,
              dicFormatter: (res) => {
                res.data.forEach(item => {item.disabled = item.isSealed == 1;})
                return res.data;
              },
              rules: [{
                required: true,
                message: "請輸入檢查目的",
                trigger: "blur"
              }]
            },
            {
              label: "檢查內容",
              prop: "checkContent",
              type: "select",
              search: true,
              searchSpan: 4,
              multiple: true,
              dicUrl: "/api/blade-system/dict/dictionary?code=check_content_warehouse",
              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: "checkResult",
              type: "select",
              dicUrl: "/api/blade-system/dict/dictionary?code=check_result",
              props:{
                label: "dictValue",
                value: "dictKey",
              },
              dicFormatter: (res) => {
                res.data.forEach(item => {item.disabled = item.isSealed == 1;})
                return res.data;
              },
              tip: "不能為空值；如選擇〝帳實不符〞需要在備註欄解釋原因",
              change: ({value, column}) => {
                /* if (!this.form.checkUnit || !value) return;
                 let $remark = this.findObject(this.option.column, 'remark');
                 if (this.form.checkUnit == '1' && value == '1'){
                   $remark.rules[0].required = false;
                 }else{
                   $remark.rules[0].required = true;
                 }*/
              },
              rules: [{
                required: true,
                message: "請輸入核對結果",
                trigger: "blur"
              }]
            },
            {
              label: "查庫人員",
              prop: "checkPersonName",
              // formslot: true,
              type: "array",
              span: 12,
              dataType: 'string',
              rules: [{
                required: true,
                message: "請輸入查庫人員姓名",
                trigger: "change"
              }]
            },
            {
              label: "查庫人員工號或身份證後四位",
              prop: "checkPersonNo",
              type: "array",
              span: 12,
              dataType: 'string',
              rules: [{
                required: true,
                message: "請輸入查庫人員工號或身份證後四位",
                trigger: "blur"
              }]
            },
            {
              label: "備註",
              prop: "remark",
              // span: 24,
              type: 'textarea',
              rules: [{
                required: false,
                message: "請輸入備註(可間要補充檢查發現情況)",
                trigger: "blur"
              }]
            },

            {
              label: "附件",
              prop: "enclosure",
              formslot: true,
              hide: true,
              rules: [{
                required: false,
                message: "請上傳附件",
                trigger: "blur"
              }]
            },
          ]
        },
        data: []
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      ...mapGetters(["userInfo"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.checkwarehouse_add, false),
          viewBtn: this.vaildData(this.permission.checkwarehouse_view, false),
          delBtn: this.vaildData(this.permission.checkwarehouse_delete, false),
          editBtn: this.vaildData(this.permission.checkwarehouse_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      },
    },
    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("checkwarehouse").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: {
      fileDownload(row){
        downloadFileBase64(row.enclosure, row.enclosureName);
      },
      uploadPreview(){
      },
      uploadError(error,column){
        this.$message.warning(error + '，不能大於' + column.fileSize + 'KB');
      },
      uploadAfter(res, done, loading, column) {
        this.attachForm.attachFile = [res];
        this.form.enclosure = res.link;
        this.form.enclosureName = res.originalName;
        this.attachBox = false;
        done(res);
      },
      uploadDelete(column,file) {
        return this.$confirm(`是否確定移除該選項？`);
      },
      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
        });
      },
      selectCallback(value){
        this.form.checkPersonNo = value.ehr;
        this.form.checkPersonName = value.name;
      },
      rowSave(row, done, loading) {
        if ( row.checkUnit instanceof Array)  row.checkUnit = row.checkUnit.join();
        if ( row.checkPurpose instanceof Array)  row.checkPurpose = row.checkPurpose.join();
        if ( row.checkContent instanceof Array)  row.checkContent = row.checkContent.join();
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        if ( row.checkUnit instanceof Array)  row.checkUnit = row.checkUnit.join();
        if ( row.checkPurpose instanceof Array)  row.checkPurpose = row.checkPurpose.join();
        if ( row.checkContent instanceof Array)  row.checkContent = row.checkContent.join();
        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.attachForm = {};
        this.attachOption.column[0].disabled = type == 'view';
        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 => {
            const data = res.data.data;
            data.name = data.enclosureName;
            if (data.name){
              this.attachForm.attachFile = [
                {label: data.name, value: data.originalName}
              ];
            }
            this.form = data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        if (params.orgNos){
          params.orgNostr = params.orgNos.join();
          params.orgNos = '';
        }
        if (params.checkTimeRange){
          params.checkTime_begin = params.checkTimeRange[0], params.checkTime_end = params.checkTimeRange[1];
          params.checkTimeRange = 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;
        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;

          data.records.forEach(item => {
            item.checkPurpose = item.checkPurpose.split(',');
            item.checkContent = item.checkContent.split(',');
            item.checkUnit = item.checkUnit.split(',');
          })

          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      }
    }
  };
</script>

<style scoped>
  >>>.el-form-item__content{
    margin-left: 10px !important;
  }
</style>
