<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.cardswallow_delete"
                   @click="handleDelete">刪 除
        </el-button>
        <!--<el-button type="success"
                   size="small"
                   icon="el-icon-setting"
                   plain
                   v-if="permission.cardswallow_setting"
                   @click="handleSetting">設置發佈人
        </el-button>-->
        <el-button type="primary"
                   size="small"
                   icon="el-icon-upload"
                   plain
                   v-if="permission.cardswallow_upload"
                   @click="attachBox = true">上 傳
        </el-button>
        <el-button type="primary"
                   size="small"
                   icon="el-icon-download"
                   plain
                   v-if="permission.cardswallow_download"
                   @click="handleDownload">下載
        </el-button>
        <el-button type="primary" size="small" :disabled="confirmBatchBtn" v-if="permission.cardswallow_confirm" @click="confirmBatch">批量簽收</el-button>
      </template>
      <template slot="process" slot-scope="{row, index}">
        <el-tag size="small " type="primary" plain v-if="row.process == 2">待發送</el-tag>
        <el-tag size="small " type="warning" plain v-if="row.process == 3">待簽收</el-tag>
        <el-tag size="small " type="success" plain v-if="row.process == 4">已簽收</el-tag>
      </template>
      <template slot="menu" slot-scope="{row, index}">
        <el-button size="small" class="el-button--text" v-if="row.process <= 3 && permission.cardswallow_edit && ((row.personId && row.personId.indexOf(userInfo.user_id) != -1) || row.createUser == userInfo.user_id)" @click="$refs.crud.rowEdit(row, index)"><i class="el-icon-edit"></i> 編 輯</el-button>
        <el-button size="small" class="el-button--text" v-if="row.process <= 3 && permission.cardswallow_delete&& ((row.personId && row.personId.indexOf(userInfo.user_id) != -1) || row.createUser == userInfo.user_id)" @click="$refs.crud.rowDel(row, index)"><i class="el-icon-delete"></i> 刪 除</el-button>
        <!--        <el-button size="mini " type="primary" plain v-if="permission.cardswallow_issue && row.process == 2 && row.personNo == userInfo.user_ehr" @click="form = row,issueVisible = true">去發佈</el-button>-->
        <el-button size="small" class="el-button--text" v-if="permission.cardswallow_confirm && row.process == 3" @click="form = row,issueVisible = true">去簽收</el-button>
      </template>
    </avue-crud>

    <el-dialog :append-to-body="true" :modal-append-to-body="false" :visible.sync="issueVisible">
      <cardswallow-issue :form="form" @close="issueVisible = false, onLoad(page)"></cardswallow-issue>
    </el-dialog>

    <el-dialog :append-to-body="true" :modal-append-to-body="false" :visible.sync="settingVisible" title="設置">
      <flow-settings :id="personId" :ehr="personNo" :name="personName" :callback="settingCallback" @close="settingVisible = false"></flow-settings>
    </el-dialog>

    <el-dialog title="文檔上傳"
               append-to-body
               :visible.sync="attachBox"
               width="555px">
      <avue-form ref="form" :option="attachOption" v-model="attachForm" :upload-after="uploadAfter">
      </avue-form>
    </el-dialog>

    <el-dialog title="信息分解"
               append-to-body
               :visible.sync="temVisible"
               :fullscreen="true"
               :close-on-press-escape="false"
               @close="attachBox = false,onLoad(page)"
    >
      <cardswallow-comfirm :data="data2"></cardswallow-comfirm>
    </el-dialog>

  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove, settingSave, getSetting, signin, getDownloadList} from "@/api/bank/cardswallow";
  import {mapGetters} from "vuex";
  import FlowSettings from "../../components/common/flow-settings";
  import {dateFormat} from "../../util/date";
  import CardswallowIssue from "../../components/common/cardswallow-issue";
  import CardswallowComfirm from "../../components/common/cardswallow-comfirm";
  import {getDeptTree, getTree} from "@/api/system/dept";
  import {getStandardByCode} from "@/api/bank/handoverstandard";
  import { getCurrentDept } from "@/api/system/dept";

  export default {
    name: "confirmed-cardswallow",
    components: {CardswallowComfirm, CardswallowIssue, FlowSettings},
    data() {
      return {
        issueVisible: false,
        delBatchBtn: true,
        confirmBatchBtn: true,

        personId: null,
        personNo: null,
        personName: null,
        settingVisible: false,

        temVisible: false,
        attachBox: false,
        attachForm: {},
        attachOption: {
          submitBtn: false,
          emptyBtn: false,
          column: [
            {
              label: '文檔上傳',
              prop: 'attachFile',
              type: 'upload',
              drag: true,
              loadText: '文檔上傳中，請稍等',
              span: 24,
              propsHttp: {
                res: 'data'
              },
              action: "/api/bank/cardswallow/readExcel"
            }
          ]
        },

        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,
          addBtn: false,
          editBtn: false,
          delBtn: false,
          selection: true,
          dialogClickModal: false,
          column: [
            {
              label: "銀行號",
              prop: "bankNo",
              span: 24,
              hide: true,
              disabled: true,
              display: false,
              search: false,
              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: "serialNo",
               rules: [{
                 required: true,
                 message: "請輸入序號",
                 trigger: "blur"
               }]
             },*/
            {
              label: "發送日期",
              prop: "sendDate",
              rules: [{
                required: true,
                message: "請輸入發送時間",
                trigger: "blur"
              }]
            },
            {
              label: "發送日期",
              prop: "sendDateRange",
              type: "date",
              format: "yyyy-MM-dd",
              valueFormat: "yyyy-MM-dd",
              searchRange:true,
              hide: true,
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false,
              search: true,
              rules: [{
                required: true,
                message: "請輸入交接日期",
                trigger: "blur"
              }]
            },
            {
              label: "發送支行",
              prop: "sendBank",
              rules: [{
                required: true,
                message: "請輸入發送支行",
                trigger: "blur"
              }]
            },
            {
              label: "發送支行機構號",
              prop: "sendOrgNo",
              hide: true,
              display: false,
              rules: [{
                required: true,
                message: "請輸入發送支行機構號",
                trigger: "blur"
              }]
            },
            {
              label: "卡號",
              prop: "cardNo",
              search: true,
              searchSpan: 4,
              rules: [{
                required: true,
                message: "請輸入卡號",
                trigger: "blur"
              }]
            },
            {
              label: "卡序號",
              prop: "cardSerialNo",
              rules: [{
                required: true,
                message: "請輸入卡序號",
                trigger: "blur"
              }]
            },
            {
              label: "其他",
              prop: "machine",
              rules: [{
                required: true,
                message: "請輸入其他",
                trigger: "blur"
              }]
            },
            {
              label: "機號",
              prop: "machineNo",
              rules: [{
                required: true,
                message: "請輸入機號",
                trigger: "blur"
              }]
            },
            {
              label: "沒收卡日期",
              prop: "swallowDate",
              type: "date",
              format: "yyyy-MM-dd",
              valueFormat: "yyyy-MM-dd",
              rules: [{
                required: true,
                message: "請輸入沒收卡日期",
                trigger: "blur"
              }]
            },
            {
              label: "卡狀態",
              prop: "cardStatus",
              rules: [{
                required: true,
                message: "請輸入卡狀態",
                trigger: "blur"
              }]
            },
            {
              label: "發送狀態",
              prop: "sendStatus",
              type: "select",
              display: false,
              // dataType: "string",
              dicUrl: `/api/blade-system/dict/dictionary?code=send_status`,
              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: "sendStatusSearch",
              type: "select",
              display: false,
              hide: true,
              search: true,
              searchSpan: 4,
              searchMultiple: true,
              // dataType: "string",
              dicUrl: `/api/blade-system/dict/dictionary?code=send_status`,
              props: {
                label: "dictValue",
                value: "dictKey"
              },
            },
            {
              label: "備註",
              prop: "remark",
              rules: [{
                required: false,
                message: "請輸入備註",
                trigger: "blur"
              }]
            },
            {
              label: "進度",
              prop: "process",
              display: false,
              hide: true,
              rules: [{
                required: false,
                message: "請輸入進度",
                trigger: "blur"
              }]
            },

            {
              label: "支行確認人員工號",
              prop: "bankConfirmNo",
              editDisplay: false,
              hide: true,
              rules: [{
                required: true,
                message: "請輸入支行確認人員工號",
                trigger: "blur"
              }]
            },
            {
              label: "支行確認人姓名",
              prop: "bankConfirmName",
              editDisplay: false,
              hide: true,
              rules: [{
                required: true,
                message: "請輸入支行確認人姓名",
                trigger: "blur"
              }]
            },
            {
              label: "確認日期",
              prop: "bankConfirmTime",
              editDisplay: false,
              hide: true,
              rules: [{
                required: true,
                message: "請輸入確認日期",
                trigger: "blur"
              }]
            },
          ]
        },
        data: [],
        data2: [],
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      ...mapGetters(["userInfo"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.cardswallow_add, false),
          viewBtn: this.vaildData(this.permission.cardswallow_view, false),
          delBtn: this.vaildData(this.permission.cardswallow_delete, false),
          editBtn: this.vaildData(this.permission.cardswallow_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    created() {
      /*getCurrentDept().then(res => {
        const data =  res.data.data;
        this.orgNo = data.orgNo;
      });*/
    },
    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("cardswallow").then(res => {
        const data = res.data.data;
        if (Object.keys(data).length > 0){
          this.option.addTitle = data.content;
          this.option.editTitle = data.content;
          this.option.viewTitle = data.content;
        }
      });
    },
    methods: {
      uploadAfter(res, done, loading, column){
        if (res && res.length > 0){
          for (let i = 0; i < res.length; i++) {
            let row = res[i];
            row = this.infoFormat(row);
          }
          this.data2 = res;
        }
        this.temVisible = true;
        loading = false;
        done();
      },
      infoFormat(row){
        let arr = row.sendBank.split(' ');
        row.sendOrgNo = arr[0];
        row.sendBank = arr[1];
        return row;
      },
      settingCallback(row){
        this.form.personId = row.personId;
        this.form.personNo = row.personNo;
        this.form.personName = row.personName;
        settingSave(this.form).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log('error');
        });
      },
      handleSetting(){
        getSetting().then((res) => {
          let data = res.data.data;
          if (!!data){
            this.personId = data.personId;
            this.personNo = data.personNo;
            this.personName = data.personName;
          }
        });
        this.settingVisible = true;
      },
      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: "操作成功!"
            });
          });
      },
      confirmBatch(){
        let _this = this;
        this.$prompt("請輸入備註?", {
          confirmButtonText: "提交",
          cancelButtonText: "取消",
          // type: "warning"
        })
          .then(({value}) => {
            for (let i = 0; i < this.selectionList.length; i++) {
              let row = this.selectionList[i];
              row.remark = value;
              signin(row).then(() => {})
            }
            this.$confirm("批量簽收成功！",{
              type: "success",
              showCancelButton: false,
              showClose: false,
            }).then(() => {
              _this.onLoad(this.page)
            })
          })
      },
      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
        });
      },
      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)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        if (params.orgNos){
          params.orgNostr = params.orgNos.join();
          params.orgNos = '';
        }
        if (params.sendDateRange){
          params.sendDate_begin = params.sendDateRange[0], params.sendDate_end = params.sendDateRange[1];
          params.sendDateRange = null;
        }

        if (params.sendStatusSearch){
          params.sendStatus = params.sendStatusSearch.join();
        }

        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, confirmFlag = true;
          // userInfo.user_id == row.createUser && row.process != 3
          for (let i = 0; i < list.length; i++) {
            let item = list[i];
            delFlag = delFlag && item.process <= 3 && ((item.personId && item.personId.indexOf(this.userInfo.user_id) != -1) || item.createUser == this.userInfo.user_id);
            confirmFlag = confirmFlag && item.process == 3;
          }
          this.delBatchBtn = !delFlag;
          this.confirmBatchBtn = !confirmFlag;
        }else{
          this.delBatchBtn = true;
          this.confirmBatchBtn = 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;
        params.process = 4;
        params.personNo = this.userInfo.user_ehr;
        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>
