<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.userlog_delete"
                   @click="handleDelete">删 除
        </el-button>
        <el-button type="primary"
                   size="small"
                   icon="el-icon-download"
                   plain
                   @click="handleDownload">下載
        </el-button>
      </template>

      <template slot="menu" slot-scope="{row, index}">
        <el-button size="small" class="el-button--text" v-if="permission.userlog_view"  @click="viewData = row, detailVisible = true"><i class="el-icon-view"></i> 查 看</el-button>
      </template>
    </avue-crud>

    <el-dialog :append-to-body="true" :modal-append-to-body="false" :destroy-on-close="true" :fullscreen="true" :visible.sync="detailVisible" title="填报详情">
      <div v-if="detailVisible">
        <user-log-view :form="viewData"></user-log-view>
      </div>
    </el-dialog>

  </basic-container>
</template>

<script>
  import {getList, getDownloadList, add, update, remove} from "@/api/report/userlog";
  import {mapGetters} from "vuex";
  import UserLogView from "../bank/user-log-view";

  export default {
    components: {UserLogView},
    data() {
      return {
        detailVisible: false,
        viewData: {},

        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          height:'auto',
          calcHeight: 30,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          viewBtn: false,
          selection: true,
          dialogClickModal: false,
          column: [
            {
              label: "銀行號",
              prop: "bankNo",
              span: 24,
              hide: true,
              rules: [{
                required: true,
                message: "請输入銀行號",
                trigger: "blur"
              }]
            },
            {
              label: "機構號",
              prop: "orgNo",
              hide: true,
              search: true,
              rules: [{
                required: true,
                message: "請输入機構號",
                trigger: "blur"
              }]
            },
            {
              label: "機構名稱",
              prop: "orgName",
              disabled: true,
              rules: [{
                required: true,
                message: "請輸入機構號",
                trigger: "blur"
              }]
            },
            {
              label: "表名",
              prop: "tableName",
              type: "select",
              search: true,
              dicData: [
                {
                  label: "網點鎖匙/密碼/實物交接登記表", value: "keypwd"
                },
                {
                  label: "業務印章交接登記表", value: "sealhandover"
                },
                {
                  label: "網點出納主管及專管員崗位變更記錄表", value: "postchange"
                },
                {
                  label: "查庫流水賬記錄表", value: "checkwarehouse"
                },
                {
                  label: "核對記錄表", value: "checklist"
                },
                {
                  label: "櫃員尾箱檢查流水賬記錄表", value: "tellertrunk"
                },
                {
                  label: "使用及出入庫登記表", value: "goodsuse"
                },
                {
                  label: "新開戶退件登記表", value: "returns"
                },
                {
                  label: "自助設備吞卡資料", value: "cardswallow"
                },
                {
                  label: "信息發佈", value: "message"
                },
              ],
              rules: [{
                required: true,
                message: "請输入表名",
                trigger: "blur"
              }]
            },
            {
              label: "員工號",
              prop: "personNo",
              search: true,
              rules: [{
                required: true,
                message: "請输入員工號",
                trigger: "blur"
              }]
            },
            {
              label: "用戶姓名",
              prop: "personName",
              rules: [{
                required: true,
                message: "請输入用戶姓名",
                trigger: "blur"
              }]
            },
            {
              label: "操作類型",
              prop: "operationType",
              type: "select",
              search: true,
              dicData: [
                {
                  label: "新增", value: "add"
                },
                {
                  label: "上繳", value: "turnin"
                },
                {
                  label: "編輯", value: "edit"
                },
                {
                  label: "刪除", value: "del"
                },
                {
                  label: "上傳", value: "upload"
                },
                {
                  label: "發佈", value: "issue"
                },
                {
                  label: "審核", value: "approve"
                },
                {
                  label: "確認", value: "sure"
                },
                {
                  label: "簽收", value: "signin"
                },
                {
                  label: "一鍵移交", value: "transfer"
                },
              ],
              rules: [{
                required: true,
                message: "請输入操作類型",
                trigger: "blur"
              }]
            },
            {
              label: "舊數據",
              prop: "oldData",
              type: "textarea",
              hide: true,
              rules: [{
                required: true,
                message: "請输入舊數據",
                trigger: "blur"
              }]
            },
            {
              label: "新數據",
              prop: "newData",
              type: "textarea",
              hide: true,
              rules: [{
                required: true,
                message: "請输入新數據",
                trigger: "blur"
              }]
            },
            {
              label: "操作時間",
              prop: "createTime",
              disabled: true,
              type: "datetime",
              format: "yyyy-MM-dd HH:mm",
              valueFormat: "yyyy-MM-dd HH:mm",
            },
            {
              label: "操作時間",
              prop: "createTimeRange",
              hide: true,
              display: false,
              search: true,
              searchRange:true,
              type: "date",
              format: "yyyy-MM-dd",
              valueFormat: "yyyy-MM-dd",
            },
          ]
        },
        data: []
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.userlog_add, false),
          viewBtn: this.vaildData(this.permission.userlog_view, false),
          delBtn: this.vaildData(this.permission.userlog_delete, false),
          editBtn: this.vaildData(this.permission.userlog_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
      handleDownload(){
        if (this.selectionList.length === 0) {
          let tip = "確定下載篩選的" + this.page.total + "條數據嗎？"
          this.$confirm(tip, {
            confirmButtonText: "確定",
            cancelButtonText: "取消",
            type: "warning"
          })
            .then(() => {
              let tableNameDict = {}, operationTypeDict = {};
              let tableName = this.findObject(this.option.column, "tableName").dicData;
              let operationType = this.findObject(this.option.column, "operationType").dicData;
              tableName.forEach(item => {
                tableNameDict[''+item.value] = item.label;
              })
              operationType.forEach(item => {
                operationTypeDict[''+item.value] = item.label;
              })

              getDownloadList(this.query).then(res => {
                let data = res.data.data;
                data.forEach(item => {
                  item.tableName = tableNameDict[''+item.tableName];
                  item.operationType = operationTypeDict[''+item.operationType];
                })
                this.downLoadData(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
        });
      },
      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) {
        if (["edit", "view"].includes(type)) {
          const newData = JSON.parse(this.form.newData);
          const tableName = this.form.tableName;
          let arr = this[tableName + 'Group'][0].column;
          if (this.form.operationType == 'edit'){
            const oldData = JSON.parse(this.form.oldData);
            for (let i = 0; i < arr.length; i++) {
              let item = arr[i];
              let prop = item.prop;
              let newVal = newData[''+prop];
              let oldVal = oldData[''+prop];
              if (newVal && newVal != oldVal){
                item.labelTip = oldVal
              }else{
                delete item.labelTip;
              }
            }
          }else{
            for (let i = 0; i < arr.length; i++) {
              let item = arr[i];
              delete item.labelTip
            }
          }
          this[tableName + 'Group'][0].column = arr;
          delete this.option.group;
          this.option.group = this[tableName + 'Group'];
          Object.assign(this.form, newData)
          this.$forceUpdate()
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {

        if (params.createTimeRange){
          params.createTime_begin = params.createTimeRange[0], params.createTime_end = params.createTimeRange[1];
          params.createTimeRange = 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;
        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>
