<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.returns_delete"
                   @click="handleDelete">刪 除
        </el-button>
        <el-button type="primary"
                   size="small"
                   icon="el-icon-upload"
                   plain
                   v-if="permission.returns_upload"
                   @click="handleUpload">上 傳
        </el-button>
        <!--<el-button type="success"
                   size="small"
                   icon="el-icon-setting"
                   plain
                   v-if="permission.returns_setting"
                   @click="handleSetting">設置發佈人
        </el-button>-->
        <el-button type="primary"
                   size="small"
                   icon="el-icon-download"
                   plain
                   v-if="permission.returns_download"
                   @click="handleDownload">下載
        </el-button>
        <el-button type="primary" size="small" :disabled="issueBatchBtn" v-if="permission.returns_issue" @click="issueBatch">批量發佈</el-button>
        <el-button type="primary" size="small" v-if="permission.returns_approve" @dblclick="approveBatch(true)" @click="approveBatch(false)"><i class="el-icon-check"></i>批量確認</el-button>
      </template>

      <template slot="menu" slot-scope="{row, index}">
        <el-button size="small" class="el-button--text" v-if="permission.returns_view" @click="$refs.crud.rowView(row, index)"><i class="el-icon-view"></i> 查 看</el-button>
        <el-button size="small" class="el-button--text" v-if="permission.returns_edit && row.process <= 2 && ((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="permission.returns_delete && row.process <= 2 && ((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="small" class="el-button--text" v-if="permission.returns_issue && row.process == 2 && (row.personId && row.personId.indexOf(userInfo.user_id) != -1)" @click="form = row,issueVisible = true">去發佈</el-button>
        <el-button size="small" class="el-button--text" v-if="permission.returns_approve && row.process == 3" @click="approve(row, index)"><i class="el-icon-check"></i> 確 認</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="personNo" slot-scope="{row}">
        <span v-if="row.process != 4">{{row.personName + '-' + row.personNo}}</span>
      </template>
    </avue-crud>

    <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)"
    >
      <returns-comfire :data="data2"></returns-comfire>
    </el-dialog>

    <el-dialog title="批量確認"
               append-to-body
               :visible.sync="approveBatchVisible"
               width="70%">
      <returns-approve-batch :data="this.selectionList" @close="approveBatchVisible = false, onLoad(page)"></returns-approve-batch>
    </el-dialog>

    <el-dialog title="信息確認"
               append-to-body
               :visible.sync="approveVisible"
               width="70%">
      <returns-approve :form="approveForm" @close="approveVisible = false, onLoad(page)"></returns-approve>
    </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 :append-to-body="true" :modal-append-to-body="false" :visible.sync="issueVisible">
      <returns-issue :form="form" @close="issueVisible = false, onLoad(page)"></returns-issue>
    </el-dialog>

  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove, returnsSubmit, settingSave, getSetting, issue, getDownloadList} from "@/api/bank/returns";
  import {mapGetters} from "vuex";
  import {dateFormat} from "../../util/date";
  import ReturnsComfire from "../../components/common/returns-comfire";
  import ReturnsApprove from "../../components/common/returns-approve";
  import FlowSettings from "../../components/common/flow-settings";
  import ReturnsIssue from "../../components/common/returns-issue";
  import {getDeptTree, getTree} from "@/api/system/dept";
  import {getStandardByCode} from "@/api/bank/handoverstandard";
  import ReturnsApproveBatch from "../../components/common/returns-approve-batch";
  import {getDictValue} from "../../api/system/dict";
  import {getDictByCodes} from "../../api/system/dict";

  export default {
    components: {ReturnsApproveBatch, ReturnsIssue, FlowSettings, ReturnsApprove, ReturnsComfire},
    data() {
      return {
        dictReturnsStatus: [],
        dictBusinessType: [],

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

        delBatchBtn: true,
        issueBatchBtn: true,
        approveBatchBtn: false,

        form: {},
        approveForm: {},
        query: {},
        loading: true,
        temVisible: false,
        approveVisible: false,
        approveBatchVisible: false,
        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: false,
          editBtn: false,
          addBtn: false,
          delBtn: false,
          selection: true,
          dialogClickModal: false,
          column: [
            {
              label: "業務類型",
              prop: "isPublic",
              type: "select",
              // hide: true,
              viewDisplay: false,
              dataType: "string",
              dicUrl: `/api/blade-system/dict/dictionary?code=business_type`,
              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: "isPublicSearch",
              type: "select",
              hide: true,
              display: false,
              search: true,
              searchSpan: 4,
              dataType: "string",
              dicUrl: `/api/blade-system/dict/dictionary?code=business_type`,
              props: {
                label: "dictValue",
                value: "dictKey"
              },
            },
            {
              label: "銀行號",
              prop: "bankNo",
              span: 24,
              hide: true,
              display: false,
              search: false,
              searchSpan: 4,
              rules: [{
                required: true,
                message: "請輸入銀行號",
                trigger: "blur"
              }]
            },
            {
              label: "機構號",
              prop: "orgNo",
              hide: true,
              display: false,
              rules: [{
                required: true,
                message: "請輸入機構號",
                trigger: "blur"
              }]
            },
            {
              label: "機構名稱",
              prop: "orgName",
              hide: true,
              disabled: true,
              display: false,
              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: "subBank",
              rules: [{
                required: true,
                message: "請輸入支行",
                trigger: "blur"
              }]
            },
            {
              label: "支行機構號",
              prop: "subOrgNo",
              rules: [{
                required: true,
                message: "請輸入支行機構號",
                trigger: "blur"
              }]
            },
            {
              label: "客戶名稱",
              prop: "customerName",
              search: true,
              searchSpan: 4,
              rules: [{
                required: true,
                message: "請輸入客戶名稱",
                trigger: "blur"
              }]
            },
            {
              label: "狀態",
              prop: "status",
              type: "select",
              dataType: "string",
              dicUrl: `/api/blade-system/dict/dictionary?code=returns_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: "reason",
              rules: [{
                required: true,
                message: "請輸入退件原因",
                trigger: "blur"
              }]
            },
            {
              label: "備註",
              prop: "remark",
              rules: [{
                required: false,
                message: "請輸入備註",
                trigger: "blur"
              }]
            },
            {
              label: "條碼",
              prop: "barCode",
              rules: [{
                required: false,
                message: "請輸入條碼",
                trigger: "blur"
              }]
            },
            {
              label: "接辦行經辦",
              prop: "handlingBank",
              search: true,
              searchSpan: 4,
              rules: [{
                required: true,
                message: "請輸入接辦行經辦",
                trigger: "blur"
              }]
            },
            {
              label: "接辦行覆核",
              prop: "handlingBankReview",
              search: true,
              searchSpan: 4,
              rules: [{
                required: false,
                message: "請輸入接辦行覆核",
                trigger: "blur"
              }]
            },
            {
              label: "處理日期",
              prop: "handlingDate",
              type: "date",
              format: "yyyy-MM-dd",
              valueFormat: "yyyy-MM-dd",
              rules: [{
                required: true,
                message: "請輸入處理日期",
                trigger: "blur"
              }]
            },
            {
              label: "退件日期",
              prop: "handlingDateRange",
              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: "handler",
              rules: [{
                required: true,
                message: "請輸入經辦",
                trigger: "blur"
              }]
            },
            {
              label: "跟進情況",
              prop: "handlingStatus",
              type: "select",
              dataType: "string",
              dicUrl: `/api/blade-system/dict/dictionary?code=processing_status`,
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              dicFormatter: (res) => {
                res.data.forEach(item => {item.disabled = item.isSealed == 1;})
                return res.data;
              },
              rules: [{
                required: false,
                message: "請輸入跟進情況",
                trigger: "blur"
              }]
            },
            {
              label: "支行備註",
              prop: "bankRemark",
              viewDisplay: false,
              editDisplay: false,
              // hide: true,
              rules: [{
                required: false,
                message: "請輸入支行備註",
                trigger: "blur"
              }]
            },
            {
              label: "支行確認人員工號",
              prop: "bankConfirmNo",
              viewDisplay: false,
              editDisplay: false,
              // hide: true,
              rules: [{
                required: true,
                message: "請輸入支行確認人員工號",
                trigger: "blur"
              }]
            },
            {
              label: "支行確認人姓名",
              prop: "bankConfirmName",
              viewDisplay: false,
              editDisplay: false,
              // hide: true,
              rules: [{
                required: true,
                message: "請輸入支行確認人姓名",
                trigger: "blur"
              }]
            },
            {
              label: "確認日期",
              prop: "bankConfirmTime",
              type: "datetime",
              format: "yyyy-MM-dd HH:mm:ss",
              valueFormat: "yyyy-MM-dd HH:mm:ss",
              viewDisplay: false,
              editDisplay: false,
              // hide: true,
              rules: [{
                required: true,
                message: "請輸入確認日期",
                trigger: "blur"
              }]
            },
            /*{
              label: "待辦人",
              prop: 'personNo'
            },*/
            {
              label: "進度",
              prop: "process",
              viewDisplay: false,
              editDisplay: false,
              rules: [{
                required: true,
                message: "請輸入節點",
                trigger: "blur"
              }]
            },
          ]
        },
        data: [],
        data2: [],

        temForm: {},
        attachForm: {},
        attachBox: false,
        attachOption: {
          submitBtn: false,
          emptyBtn: false,
          column: [
            {
              label: '文檔上傳',
              prop: 'attachFile',
              type: 'upload',
              drag: true,
              loadText: '文檔上傳中，請稍等',
              span: 24,
              propsHttp: {
                res: 'data'
              },
              action: "/api/bank/returns/readExcel"
            }
          ]
        }
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      ...mapGetters(["userInfo"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.returns_add, false),
          viewBtn: this.vaildData(this.permission.returns_view, false),
          delBtn: this.vaildData(this.permission.returns_delete, false),
          editBtn: this.vaildData(this.permission.returns_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("returns").then(res => {
        const data = res.data.data;
        if (data){
          this.option.addTitle = data.content;
          this.option.editTitle = data.content;
          this.option.viewTitle = data.content;
        }
      });
      if (this.dictReturnsStatus.length == 0){
        getDictByCodes('returns_status').then(res => {
          let data = res.data.data;
          this.dictReturnsStatus = data;
        })
      }
      if (this.dictBusinessType.length == 0){
        getDictByCodes('business_type').then(res => {
          let data = res.data.data;
          this.dictBusinessType = data;
        })
      }

    },
    methods: {
      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');
        });
      },
      handleDownload(){
        if (this.selectionList.length === 0) {
          let tip = "確定下載篩選的" + this.page.total + "條數據嗎？"
          this.$confirm(tip, {
            confirmButtonText: "確定",
            cancelButtonText: "取消",
            type: "warning"
          })
            .then(() => {
              getDownloadList(this.query).then(res => {
                let data = res.data.data;
                if (data && data.length > 0){
                  data.forEach(item => {
                    item.status = item.returnStatus;
                  });
                }
                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
        });
      },
      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;
      },
      issueBatch(){
        let _this = this;
        this.$confirm("確定將選擇數據發佈?", {
          confirmButtonText: "確定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            for (let i = 0; i < this.selectionList.length; i++) {
              let row = this.selectionList[i];
              issue(row).then(() => {})
            }
            this.$confirm("批量發佈成功！",{
              type: "success",
              showCancelButton: false,
              showClose: false,
            }).then(() => {
              _this.onLoad(this.page)
            })
          })

      },
      approveBatch(isDbclick){
        if (this.selectionList.length > 0){
          if (this.approveBatchBtn){
            //选中的必须都为待确认信息
            this.$message.warning("選中的必須都為待確認信息！");
            return;
          }else{
            this.approveBatchVisible = true;
          }
        }else {
          this.$refs.crud.toggleSelection();
          let toApproveArr = [];
          for (let i = 0; i < this.data.length; i++) {
            let item = this.data[i];
            if (item.process == 3){
              toApproveArr.push(item)
            }
          }
          if (toApproveArr.length  == 0){
            this.$message.warning("當前頁沒有符合條件的記錄！")
            return;
          }
          this.$refs.crud.toggleSelection(toApproveArr);
          if (isDbclick){
            this.approveBatchVisible = true;
          }
        }




      },
      approve(row, index){
        this.approveVisible = true;
        this.approveForm = row;
      },
      getDictValueByLabel(dict, label){
        for (let i = 0; i < dict.length; i++) {
          let item = dict[i];
          if (item.dictValue == label){
            return item.dictKey;
          }
        }
        return null;
      },
      infoFormat(row){
        let arr = row.subBank.split(' ');
        row.subOrgNo = arr[0];
        row.subBank = arr[1];
        /*row.isPublic = row.isPublic == '對公' ? 1 : 0;
        if (row.status == '退件'){
          row.status = '1';
        }else if (row.status == 'HOLD'){
          row.status = '2';
        }else if (row.status == '完成'){
          row.status = '3';
        }*/
        row.isPublic = this.getDictValueByLabel(this.dictBusinessType, row.isPublic);
        row.status = this.getDictValueByLabel(this.dictReturnsStatus, row.status);
        debugger

        /*let userInfoStr = localStorage.getItem("saber-userInfo");
        let userInfo = JSON.parse(userInfoStr);
        row.bankConfirmNo = userInfo.content.user_ehr;
        row.bankConfirmName = userInfo.content.user_name;
        row.bankConfirmTime = dateFormat(new Date(), "yyyy-MM-dd HH:mm:ss");*/

        return row;
      },
      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();
      },
      handleUpload(){
        this.attachBox = 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: "操作成功!"
            });
          });
      },
      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;
          });*/
          if (type == "view"){
            this.findObject(this.option.column, "bankRemark").viewDisplay = this.form.process == 4;
            this.findObject(this.option.column, "bankConfirmNo").viewDisplay = this.form.process == 4;
            this.findObject(this.option.column, "bankConfirmName").viewDisplay = this.form.process == 4;
            this.findObject(this.option.column, "bankConfirmTime").viewDisplay = this.form.process == 4;
          }
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        if (params.handlingDateRange){
          params.handlingDate_begin = params.handlingDateRange[0], params.handlingDate_end = params.handlingDateRange[1];
          params.handlingDateRange = null;
        }
        if (params.orgNos){
          params.orgNostr = params.orgNos.join();
          params.orgNos = '';
        }
        if (params.customerName){
          params.customerName = params.customerName.trim()
        }
        if (params.isPublicSearch){
          params.isPublic = params.isPublicSearch;
        }

        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
        if (list && list.length > 0){
          let issueFlag = true, approveFlag = true, delFlag = true;
          for (let i = 0; i < list.length; i++) {
            let item = list[i];
            delFlag = delFlag && item.process <= 2 && ((item.personId && item.personId.indexOf(this.userInfo.user_id) != -1) || item.createUser == this.userInfo.user_id);
            issueFlag = issueFlag && item.process == 2  && (item.personId && item.personId.indexOf(this.userInfo.user_id) != -1);
            approveFlag = approveFlag && item.process == 3 && this.permission.returns_approve;
          }
          this.delBatchBtn = !delFlag;
          this.issueBatchBtn = !issueFlag;
          this.approveBatchBtn = !approveFlag;
        }else{
          this.delBatchBtn = true;
          this.issueBatchBtn = true;
          this.approveBatchBtn = 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;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      }
    }
  };
</script>

<style>
</style>
