<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.message_delete"
                   @click="handleDelete">刪 除
        </el-button>
      </template>
      <template slot="fileForm" slot-scope="{row}">
        <!--<el-button type="primary" size="small" icon="el-icon-upload" plain
                   v-if="permission.message_delete"
                   @click="attachBox = true">上 傳
        </el-button>-->
        <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-scope="{row}"
                slot="attachSize">
        <el-tag>{{`${row.attachSize} KB`}}</el-tag>
      </template>

      <template slot-scope="{row}" slot="menu">
        <el-button size="small" class="el-button--text" v-if="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="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.message_download && row.file" @click="handleDownload(row)">下載</el-button>
      </template>
    </avue-crud>

    <!--    <el-dialog title="附件管理"-->
    <!--               append-to-body-->
    <!--               :destroy-on-close="true"-->
    <!--               :visible.sync="attachBox"-->
    <!--               width="555px">-->
    <!--      <avue-form ref="form" :option="attachOption" v-model="attachForm" :upload-after="uploadAfter" :upload-error="uploadError" :upload-delete="uploadDelete">-->
    <!--      </avue-form>-->
    <!--    </el-dialog>-->

  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove} from "@/api/bank/message";
  import {mapGetters} from "vuex";
  import {downloadFileBase64} from "@/util/util";
  import {getDeptTree, getTree} from "@/api/system/dept";
  import {getStandardByCode} from "@/api/bank/handoverstandard";
  import {getRoleTree} from "@/api/system/role";
  import website from '@/config/website';


  export default {
    data() {
      return {
        delBatchBtn: true,

        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,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          viewBtn: true,
          editBtn: false,
          delBtn: false,
          columnBtn: false,
          selection: true,
          dialogClickModal: false,
          column: [
            {
              label: "標題",
              prop: "title",
              span: 24,
              rules: [{
                required: true,
                message: "請輸入標題",
                trigger: "blur"
              }]
            },
            {
              label: "內文",
              prop: "content",
              type: "textarea",
              rules: [{
                required: false,
                message: "請輸入內文",
                trigger: "blur"
              }]
            },
            {
              label: "附件",
              prop: "file",
              formslot: true,
              hide: true,
              rules: [{
                required: false,
                message: "請輸入附件",
                trigger: "blur"
              }]
            },

            {
              label: "通知方式",
              prop: "type",
              type: "radio",
              value: '1',
              hide: true,
              editDisplay: false,
              viewDisplay: false,
              dicData: [{
                label: '機構',
                value: '1'
              }, {
                label: '廣播',
                value: '2'
              }],
              change: ({value}) => {
                if (!value) return;
                let $deptId = this.findObject(this.option.column, "deptId");
                if (value == '1'){
                  // $deptId.multiple = false;
                  $deptId.checkStrictly = true;
                }else{
                  // $deptId.multiple = true;
                  $deptId.checkStrictly = false;
                }
              },
            },
            {
              label: "查閱部門",
              prop: "deptName",
              display: false,
              hide: true,
            },
            {
              label: "查閱部門",
              prop: "deptId",
              type: "tree",
              multiple: true,
              hide: true,
              dataType: "string",
              dicData: [],
              props: {
                label: "title"
              },
              checkStrictly: false,
              hide: true,
              editDisplay: false,
              viewDisplay: false,
              rules: [{
                required: true,
                message: "請選擇查閱部門",
                trigger: "click"
              }]
            },
            {
              label: "查閱角色",
              prop: "roleName",
              hide: true,
              display: false
            },
            {
              label: "查閱角色",
              prop: "roleId",
              hide: true,
              editDisplay: false,
              viewDisplay: false,
              // search: true,
              multiple: true,
              type: "tree",
              dataType: "string",
              dicData: [],
              props: {
                label: "title"
              },
              checkStrictly: false,
              // slot: true,
              rules: [{
                required: false,
                message: "請選擇所屬角色",
                trigger: "click"
              }]
            },
            {
              label: "附件原名",
              prop: "originalName",
              addDisplay: false,
              editDisplay: false,
              rules: [{
                required: true,
                message: "請輸入附件原名",
                trigger: "blur"
              }]
            },
            {
              label: "附件拓展名",
              prop: "extension",
              addDisplay: false,
              hide: true,
              viewDisplay: false,
              editDisplay: false,
              rules: [{
                required: true,
                message: "請輸入附件拓展名",
                trigger: "blur"
              }]
            },
            {
              label: "附件大小",
              prop: "attachSize",
              addDisplay: false,
              hide: true,
              editDisplay: false,
              viewDisplay: false,
              append: "KB",
              slot: true,
              rules: [{
                required: true,
                message: "請輸入附件大小",
                trigger: "blur"
              }]
            },
            {
              label: "發佈時間",
              prop: "createTime",
              addDisplay: false,
              editDisplay: false,

            }
          ]
        },
        data: []
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      ...mapGetters(["userInfo"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.message_add, false),
          viewBtn: this.vaildData(this.permission.message_view, false),
          delBtn: this.vaildData(this.permission.message_delete, false),
          editBtn: this.vaildData(this.permission.message_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, "deptId");
        let treeData = getTree(res.data.data, this.userInfo.dept_id);
        column.dicData = treeData;
      });
      getRoleTree(website.tenantId).then(res => {
        const column = this.findObject(this.option.column, "roleId");
        column.dicData = res.data.data;
      });
      getStandardByCode("message").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) {
          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
        });
      },*/
      uploadError(error,column){
        this.$message.warning(error + '，不能大於' + column.fileSize + 'KB');
      },
      uploadAfter(res, done, loading, column) {
        this.attachForm.attachFile = [res];
        this.form.file = res.link;
        this.attachBox = false;
        done(res);
      },
      uploadDelete(column,file) {
        return this.$confirm(`是否確定移除該選項？`);
      },
      uploadPreview(){
      },
      handleDownload(row) {
        // window.open(`${row.link}`);
        // this.downFile(row.file, row.originalName)
        downloadFileBase64(row.file, row.originalName);

      },

      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.attachForm = {};
        this.attachOption.column[0].disabled = type == 'view';
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            const data = res.data.data;
            if (data.file){
              data.name = data.originalName;
              this.attachForm.attachFile = [
                {label: data.name, value: data.originalName}
              ];
            }
            this.form = data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        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;
          }
          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;

         /* data.records.forEach(item => {
            item.roleId = item.roleId.split(",");
          })*/
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      }
    }
  };
</script>

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