<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"
                   :disabled="delBatchBtn"
                   plain
                   v-if="permission.postchange_delete"
                   @click="handleDelete">刪 除
        </el-button>
        <el-button type="success"
                   size="small"
                   icon="el-icon-setting"
                   plain
                   v-if="permission.postchange_setting"
                   @click="handleSetting">設置審批人
        </el-button>
        <el-button type="primary"
                   size="small"
                   icon="el-icon-download"
                   plain
                   v-if="permission.postchange_download"
                   @click="handleDownload">下載
        </el-button>
        <el-button type="success"
                   size="small"
                   icon="el-icon-refresh"
                   plain
                   v-if="permission.postchange_transfer"
                   @click="handleTransfer">一鍵移交
        </el-button>
      </template>
      <template slot="process" slot-scope="{row, index}">
        <el-tag size="small " type="warning" plain v-if="row.process == 2">待確認</el-tag>
        <el-tag size="small " type="success" plain v-if="row.process == 3">已確認</el-tag>
      </template>

      <template slot="menu" slot-scope="{row, index}">
        <el-button size="small" class="el-button--text" v-if="permission.postchange_view"  @click="handleView(row, index)"><i class="el-icon-view"></i> 查 看</el-button>
        <el-button size="small" class="el-button--text" v-if="permission.postchange_edit && userInfo.user_id == row.createUser && row.process != 3" @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.postchange_delete && userInfo.user_id == row.createUser && row.process != 3" @click="$refs.crud.rowDel(row)"><i class="el-icon-delete"></i> 刪 除</el-button>
        <el-button size="small" class="el-button--text" v-if="permission.postchange_approve && row.process == 2 && row.personNo == userInfo.user_ehr" @click="approve(row, index)"><i class="el-icon-check"></i> 審 批</el-button>
      </template>

      <template slot="personNameForm">
        <select-dialog-user :disabled="selectDisabled" :id="form.personId" :name="form.personName" :ehr="form.personNo" :callback="selectCallback"></select-dialog-user>
      </template>

      <template slot="testForm" slot-scope="{row}">
        <div>
          <el-button type="primary"
                     size="small"
                     icon="el-icon-print"
                     style="position: fixed;right: 100px;top: 200px;border-radius: 73px"
                     download="myexcel.xls"
                     v-if="permission.postchange_download && row.process == 3 && type == 'view'"
                     @click="testExcel">下載Excel
          </el-button>
          <a href="" download="網點出納主管及專管員崗位變更記錄表.xls" id="dl" style="display: none"></a>

          <div id="mytable">
            <table v-show="false" border="1" cellpadding="5" cellspacing="5">
              <caption>網點出納主管及專管員崗位變更記錄表</caption><!--可以生成表格的标题-->
              <tr>
                <th>銀行號</th>
                <td>{{row.bankNo}}</td>
                <th></th>
                <th>機構號</th>
                <td>{{row.orgNo}}</td>
              </tr>
              <tr>
                <th>申請日期</th>
                <td>{{row.applyDate}}</td>
                <th></th>
                <th>生效日期</th>
                <td>{{row.effectiveDate}}</td>
              </tr>
              <tr>
                <th>審批人</th>
                <td>{{row.personName}}</td>
                <th></th>
                <th>審批人員工號</th>
                <td>{{row.personNo}}</td>
              </tr>
              <tr>
                <th>備註</th>
                <td>{{row.remark}}</td>
                <th></th>
                <th>填報人</th>
                <td>{{row.createUserName}}</td>
              </tr>
              <tr>
                <th>填報人員工號</th>
                <td>{{row.createUserNo}}</td>
                <th></th>
                <th>填報時間</th>
                <td>{{row.createTime}}</td>
              </tr>
            </table>
            <br v-show="false">

            <table border="1" cellpadding="5" cellspacing="5">
              <tr>
                <th>人員配置</th>
                <th></th>
                <th v-if="type != 'view'" colspan="3">網點出納主管</th>
                <th v-if="type != 'view'" colspan="3">網點出納專管員</th>
                <th  v-if="type == 'view'"colspan="6">網點出納主管</th>
                <th  v-if="type == 'view'"colspan="6">網點出納專管員</th>
              </tr>
              <tr>
                <th></th>
                <th></th>
                <th v-if="type != 'view'">持有人</th>
                <th v-if="type == 'view'">上期持有人</th>
                <th v-if="type == 'view'">當前持有人</th>
                <th v-if="type != 'view'" colspan="2">後備人員</th>
                <th v-if="type == 'view'" colspan="2">上期後備人員</th>
                <th v-if="type == 'view'" colspan="2">當前後備人員</th>
                <th v-if="type != 'view'">持有人</th>
                <th v-if="type == 'view'">上期持有人</th>
                <th v-if="type == 'view'">當前持有人</th>
                <th v-if="type != 'view'" colspan="2">後備人員</th>
                <th v-if="type == 'view'" colspan="2">上期後備人員</th>
                <th v-if="type == 'view'" colspan="2">當前後備人員</th>
              </tr>
              <tr>
                <th></th>
                <th></th>
                <th v-if="type == 'view'">
                  <span v-for="item in userList">
                    <span v-if="item.ehr == row.preholderDirector">{{item.text}}</span>
                  </span>
                </th>
                <th>

                  <span v-if="type == 'view'" v-for="item in userList">
                    <span v-if="item.ehr == row.holderDirector">{{item.text}}</span>
                  </span>

                  <el-select v-if="type != 'view'" clearable filterable v-model="row.holderDirector" placeholder="請選擇" :disabled="selectDisabled" @clear="clearSelect('holder1')">
                    <el-option
                      v-for="item in userList"
                      :key="item.ehr"
                      :label="item.text"
                      :value="item.ehr">
                    </el-option>
                  </el-select>
                </th>
                <th v-if="type == 'view'">
                  <span v-for="item in userList">
                    <span v-if="item.ehr == row.prebackupDirector1">{{item.text}}</span>
                  </span>
                </th>
                <th v-if="type == 'view'">
                  <span v-for="item in userList">
                    <span v-if="item.ehr == row.prebackupDirector2">{{item.text}}</span>
                  </span>
                </th>
                <th>
                  <span v-if="type == 'view'" v-for="item in userList">
                    <span v-if="item.ehr == row.backupDirector1">{{item.text}}</span>
                  </span>
                  <el-select v-if="type != 'view'" clearable filterable  v-model="row.backupDirector1" placeholder="請選擇" :disabled="selectDisabled" @clear="clearSelect('backup1')">
                    <el-option
                      v-for="item in userList"
                      :key="item.ehr"
                      :label="item.text"
                      :value="item.ehr">
                    </el-option>
                  </el-select>
                </th>
                <th>
                  <span v-if="type == 'view'" v-for="item in userList">
                    <span v-if="item.ehr == row.backupDirector2">{{item.text}}</span>
                  </span>
                  <el-select v-if="type != 'view'" clearable filterable  v-model="row.backupDirector2" placeholder="請選擇" :disabled="selectDisabled" @clear="clearSelect('backup11')">
                    <el-option
                      v-for="item in userList"
                      :key="item.ehr"
                      :label="item.text"
                      :value="item.ehr">
                    </el-option>
                  </el-select>
                </th>
                <th v-if="type == 'view'">
                  <span v-for="item in userList">
                    <span v-if="item.ehr == row.preholderManage">{{item.text}}</span>
                  </span>
                </th>
                <th>
                  <span v-if="type == 'view'" v-for="item in userList">
                    <span v-if="item.ehr == row.holderManage">{{item.text}}</span>
                  </span>
                  <el-select v-if="type != 'view'" clearable filterable  v-model="row.holderManage" placeholder="請選擇" :disabled="selectDisabled" @clear="clearSelect('holder2')">
                    <el-option
                      v-for="item in userList"
                      :key="item.ehr"
                      :label="item.text"
                      :value="item.ehr">
                    </el-option>
                  </el-select>
                </th>
                <th v-if="type == 'view'">
                  <span v-for="item in userList">
                    <span v-if="item.ehr == row.prebackupManage1">{{item.text}}</span>
                  </span>
                </th>
                <th v-if="type == 'view'">
                  <span v-for="item in userList">
                    <span v-if="item.ehr == row.prebackupManage2">{{item.text}}</span>
                  </span>
                </th>
                <th>
                  <span v-if="type == 'view'" v-for="item in userList">
                    <span v-if="item.ehr == row.backupManage1">{{item.text}}</span>
                  </span>
                  <el-select v-if="type != 'view'" clearable filterable  v-model="row.backupManage1" placeholder="請選擇" :disabled="selectDisabled" @clear="clearSelect('backup2')">
                    <el-option
                      v-for="item in userList"
                      :key="item.ehr"
                      :label="item.text"
                      :value="item.ehr">
                    </el-option>
                  </el-select>
                </th>
                <th>
                  <span v-if="type == 'view'" v-for="item in userList">
                    <span v-if="item.ehr == row.backupManage2">{{item.text}}</span>
                  </span>
                  <el-select v-if="type != 'view'" clearable filterable  v-model="row.backupManage2" placeholder="請選擇" :disabled="selectDisabled" @clear="clearSelect('backup22')">
                    <el-option
                      v-for="item in userList"
                      :key="item.ehr"
                      :label="item.text"
                      :value="item.ehr">
                    </el-option>
                  </el-select>
                </th>
              </tr>

              <tr v-for="(item1, index1) in dicts">
                <th v-if="!(item1.index != 0 && item1.parentName == dicts[index1-1].parentName)" :rowspan="item1.rowspan + ''">{{item1.parentName}}</th>
                <th>{{item1.dictValue}}</th>
                <th v-if="type == 'view'">
                  <el-tag size="small " type="success" plain v-if="row['preholder1' + item1.code + '' + item1.dictKey]">√</el-tag>
                </th>
                <th>
                  <el-checkbox v-if="type != 'view'" :disabled="selectDisabled || !row.holderDirector" v-model="row['holder1' + item1.code + '' + item1.dictKey]"></el-checkbox>
                  <el-tag size="small " type="success" plain v-if="row['holder1' + item1.code + '' + item1.dictKey]">√</el-tag>
                </th>
                <th v-if="type == 'view'">
                  <el-tag size="small " type="success" plain v-if="row['prebackup1' + item1.code + '' + item1.dictKey]">√</el-tag>
                </th>
                <th v-if="type == 'view'">
                  <el-tag size="small " type="success" plain v-if="row['prebackup11' + item1.code + '' + item1.dictKey]">√</el-tag>
                </th>
                <th>
                  <el-checkbox v-if="type != 'view'" :disabled="selectDisabled || !row.backupDirector1" v-model="row['backup1' + item1.code + '' + item1.dictKey]"></el-checkbox>
                  <el-tag size="small " type="success" plain v-if="row['backup1' + item1.code + '' + item1.dictKey]">√</el-tag>
                </th>
                <th>
                  <el-checkbox v-if="type != 'view'" :disabled="selectDisabled || !row.backupDirector2" v-model="row['backup11' + item1.code + '' + item1.dictKey]"></el-checkbox>
                  <el-tag size="small " type="success" plain v-if="row['backup11' + item1.code + '' + item1.dictKey]">√</el-tag>
                </th>
                <th v-if="type == 'view'">
                  <el-tag size="small " type="success" plain v-if="row['preholder2' + item1.code + '' + item1.dictKey]">√</el-tag>
                </th>
                <th>
                  <el-checkbox v-if="type != 'view'" :disabled="selectDisabled || !row.holderManage" v-model="row['holder2' + item1.code + '' + item1.dictKey]"></el-checkbox>
                  <el-tag size="small " type="success" plain v-if="row['holder2' + item1.code + '' + item1.dictKey]">√</el-tag>
                </th>
                <th v-if="type == 'view'">
                  <el-tag size="small " type="success" plain v-if="row['prebackup2' + item1.code + '' + item1.dictKey]">√</el-tag>
                </th>
                <th v-if="type == 'view'">
                  <el-tag size="small " type="success" plain v-if="row['prebackup22' + item1.code + '' + item1.dictKey]">√</el-tag>
                </th>
                <th>
                  <el-checkbox v-if="type != 'view'" :disabled="selectDisabled || !row.backupManage1" v-model="row['backup2' + item1.code + '' + item1.dictKey]"></el-checkbox>
                  <el-tag size="small " type="success" plain v-if="row['backup2' + item1.code + '' + item1.dictKey]">√</el-tag>
                </th>
                <th>
                  <el-checkbox v-if="type != 'view'" :disabled="selectDisabled || !row.backupManage2" v-model="row['backup22' + item1.code + '' + item1.dictKey]"></el-checkbox>
                  <el-tag size="small " type="success" plain v-if="row['backup22' + item1.code + '' + item1.dictKey]">√</el-tag>
                </th>
              </tr>

            </table>

          </div>
        </div>
      </template>

      <template slot="titleForm" slot-scope="{row, index}">
        <div v-html="title" style="white-space: pre-line;color: red;font-weight: bold;"></div>
      </template>
      <template slot="titleLabel" slot-scope="{row, index}">
        <span style="color: red;font-weight: bold;">注意事項：</span>
      </template>

    </avue-crud>

    <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>

    <div v-show="false">
      <avue-crud :option="optionForm" :data="data" v-model="viewForm" ref="crudView" :row-update="approveSubmit"></avue-crud>
    </div>

    <el-dialog :append-to-body="true" :modal-append-to-body="false" :visible.sync="transferVisible" title="一鍵移交">
      <div v-if="transferVisible">
        <select-dialog-user :callback="transferCallback"></select-dialog-user>
      </div>
    </el-dialog>

  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove, approve, settingSave, getDictByCode, getSetting, getLastRecord, transfer} from "@/api/bank/postchange";
  import {mapGetters} from "vuex";
  import { getCurrentDept } from "@/api/system/dept";
  import {dateFormat} from "../../util/date";
  import FlowSettings from "../../components/common/flow-settings";
  import {getUserListDeptChild} from "@/api/system/user";
  import {getDeptTree, getTree} from "@/api/system/dept";
  import {getStandardByCode} from "@/api/bank/handoverstandard";
  import SelectDialogUser from "../../components/select-dialog/select-dialog-user";
  import {getDictByCodes} from "../../api/system/dict";
  import {tableToExcel} from "../../util/util";

  export default {
    name: "tobeconfirm-postchange",
    components: {SelectDialogUser, FlowSettings},
    data() {
      return {
        isManageUser: false,

        dicts: [],
        transferVisible: false,

        selectDisabled: false,
        approveFlag: false,
        delBatchBtn: true,

        type: 'add',
        form: {},
        viewForm: {},
        query: {},
        loading: true,
        settingVisible: false,
        viewVisible: false,
        personId: null,
        personNo: null,
        personName: null,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        userList: [],
        option: {
          addTitle: '新增【網點出納主管及專管員崗位變更記錄表】',
          editTitle: '編輯【網點出納主管及專管員崗位變更記錄表】',
          viewTitle: '查看【網點出納主管及專管員崗位變更記錄表】',
          height:'auto',
          calcHeight: 30,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          dialogFullscreen: true,
          border: true,
          index: false,
          viewBtn: false,
          // addBtn: true,
          editBtn: false,
          delBtn: false,
          selection: true,
          dialogClickModal: false,
          column: [
            {
              label: '注意事項',
              prop: 'title',
              hide: true,
              formslot: true,
              type: 'text',
              span: 24
            },
            {
              label: "銀行號",
              prop: "bankNo",
              span: 24,
              hide: true,
              disabled: true,
              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: "applyDate",
              type: "datetime",
              disabled: true,
              format: "yyyy-MM-dd",
              valueFormat: "yyyy-MM-dd",
              rules: [{
                required: true,
                message: "請輸入申請日期",
                trigger: "blur"
              }]
            },
            {
              label: "生效日期",
              prop: "effectiveDateRange",
              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: "effectiveDate",
              type: "date",
              format: "yyyy-MM-dd",
              valueFormat: "yyyy-MM-dd",
              pickerOptions: {
                disabledDate(time) {
                  return time.getTime() < Date.now() - 8.64e7;
                }
              },
              rules: [{
                required: true,
                message: "請輸入生效日期",
                trigger: "blur"
              }]
            },
            {
              label: "審批人",
              prop: "personName",
              formslot:  true,
              rules: [{
                required: true,
                message: "請輸入審批人姓名",
                trigger: "change"
              }]
            },
            {
              label: "審批人員工號",
              prop: "personNo",
              disabled: true,
              rules: [{
                required: true,
                message: "請輸入審批人員工號",
                trigger: "blur"
              }]
            },
            {
              label: "備註",
              prop: "remark",
              rules: [{
                required: false,
                message: "請輸入備註",
                trigger: "blur"
              }]
            },
            {
              label: "填報人",
              prop: "createUserName",
              addDisplay: false,
              editDisplay: false,
            },
            {
              label: "填報人員工號",
              prop: "createUserNo",
              addDisplay: false,
              editDisplay: false,
            },
            {
              label: "填報時間",
              prop: "createTime",
              addDisplay: false,
              editDisplay: false,
            },
            {
              label: "進度",
              prop: "process",
              // slot: true,
              viewDisplay: false,
              addDisplay: false,
              editDisplay: false,
            },
          ],
          group: [
            {
              label: "人員配置",
              column: [
                {
                  // label: "人員配置",
                  prop: "test",
                  span: 24,
                },
              ]
            }
          ],
        },
        optionForm: {
          dialogClickModal: false,
          submitText: "確認",
          column: [
            {
              label: "銀行號",
              prop: "bankNo",
              span: 24,
              hide: true,
              disabled: true,
              display: false,
              rules: [{
                required: true,
                message: "請輸入銀行號",
                trigger: "blur"
              }]
            },
            {
              label: "機構號",
              prop: "orgNo",
              hide: true,
              disabled: true,
              display: false,
              rules: [{
                required: true,
                message: "請輸入機構號",
                trigger: "blur"
              }]
            },
            {
              label: "機構名稱",
              prop: "orgName",
              span: 24,
              disabled: true,
              rules: [{
                required: true,
                message: "請輸入機構號",
                trigger: "blur"
              }]
            },
            {
              label: "申請日期",
              prop: "applyDate",
              type: "datetime",
              disabled: true,
              format: "yyyy-MM-dd",
              valueFormat: "yyyy-MM-dd",
              rules: [{
                required: true,
                message: "請輸入申請日期",
                trigger: "blur"
              }]
            },
            {
              label: "生效日期",
              prop: "effectiveDate",
              type: "date",
              disabled: true,
              format: "yyyy-MM-dd",
              valueFormat: "yyyy-MM-dd",
              rules: [{
                required: true,
                message: "請輸入生效日期",
                trigger: "blur"
              }]
            },
            {
              label: "審批人",
              prop: "personName",
              formslot:  true,
              rules: [{
                required: true,
                message: "請輸入審批人姓名",
                trigger: "blur"
              }]
            },
            {
              label: "審批人員工號",
              prop: "personNo",
              disabled: true,
              rules: [{
                required: true,
                message: "請輸入審批人員工號",
                trigger: "blur"
              }]
            },
            {
              label: "備註",
              prop: "remark",
              disabled: true,
              rules: [{
                required: false,
                message: "請輸入備註",
                trigger: "blur"
              }]
            },
          ],
        },
        groupEdit: [
          {
            label: "人員配置",
            prop: "personSetting",
            column: [
              {
                label: "網點出納主管",
                prop: "director",
                type: "text",
                span: 2,

              },
              {
                label: "持有人",
                prop: "holder1",
                span: 11,
                type: "select",
                // multiple: true,
                props: {
                  label: "text",
                  value: "ehr"
                },
                rules: [{
                  required: true,
                  message: "請輸入持有人",
                  trigger: "blur"
                }]
              },
              {
                label: "後備人員",
                prop: "backupPerson1",
                span: 11,
                type: "select",
                multiple: true,
                props: {
                  label: "text",
                  value: "ehr"
                },

                rules: [{
                  required: true,
                  message: "請輸入後備人員",
                  trigger: "blur"
                }]
              },
              {
                label: "網點出納專管員",
                prop: "manager",
                type: "text",
                span: 2,
              },
              {
                label: "持有人",
                prop: "holder2",
                span: 11,
                type: "select",
                multiple: true,
                props: {
                  label: "text",
                  value: "ehr"
                },

                rules: [{
                  required: true,
                  message: "請輸入持有人",
                  trigger: "blur"
                }]
              },
              {
                label: "後備人員",
                prop: "backupPerson2",
                span: 11,
                type: "select",
                multiple: true,
                props: {
                  label: "text",
                  value: "ehr"
                },
                rules: [{
                  required: true,
                  message: "請輸入後備人員",
                  trigger: "blur"
                }]
              },
            ]
          },
        ],
        groupView: [
          {
            label: "人員配置",
            prop: "personSetting",
            column: [
              {
                label: "網點出納主管",
                prop: "director",
                type: "text",
                span: 4,
              },
              {
                label: "上期持有人",
                prop: "preholder1",
                span: 5,
                type: "select",
                multiple: true,
                props: {
                  label: "text",
                  value: "ehr"
                },
                rules: [{
                  required: true,
                  message: "請輸入持有人",
                  trigger: "blur"
                }]
              },
              {
                label: "目前持有人",
                prop: "holder1",
                span: 5,
                type: "select",
                multiple: true,
                props: {
                  label: "text",
                  value: "ehr"
                },
                rules: [{
                  required: true,
                  message: "請輸入持有人",
                  trigger: "blur"
                }]
              },
              {
                label: "上期後備人員",
                prop: "prebackupPerson1",
                span: 5,
                type: "select",
                multiple: true,
                props: {
                  label: "text",
                  value: "ehr"
                },

                rules: [{
                  required: true,
                  message: "請輸入後備人員",
                  trigger: "blur"
                }]
              },
              {
                label: "目前後備人員",
                prop: "backupPerson1",
                span: 5,
                type: "select",
                multiple: true,
                props: {
                  label: "text",
                  value: "ehr"
                },

                rules: [{
                  required: true,
                  message: "請輸入後備人員",
                  trigger: "blur"
                }]
              },
              {
                label: "網點出納專管員",
                prop: "manager",
                type: "text",
                span: 4,
              },
              {
                label: "上期持有人",
                prop: "preholder2",
                span: 5,
                type: "select",
                multiple: true,
                props: {
                  label: "text",
                  value: "ehr"
                },
                rules: [{
                  required: true,
                  message: "請輸入持有人",
                  trigger: "blur"
                }]
              },
              {
                label: "目前持有人",
                prop: "holder2",
                span: 5,
                type: "select",
                multiple: true,
                props: {
                  label: "text",
                  value: "ehr"
                },
                rules: [{
                  required: true,
                  message: "請輸入持有人",
                  trigger: "blur"
                }]
              },
              {
                label: "後備人員",
                prop: "prebackupPerson2",
                span: 5,
                type: "select",
                multiple: true,
                props: {
                  label: "text",
                  value: "ehr"
                },
                rules: [{
                  required: true,
                  message: "請輸入後備人員",
                  trigger: "blur"
                }]
              },
              {
                label: "目前後備人員",
                prop: "backupPerson2",
                span: 5,
                type: "select",
                multiple: true,
                props: {
                  label: "text",
                  value: "ehr"
                },
                rules: [{
                  required: true,
                  message: "請輸入後備人員",
                  trigger: "blur"
                }]
              },
            ]
          },
        ],
        data: []
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      ...mapGetters(["userInfo"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.postchange_add, false),
          viewBtn: this.vaildData(this.permission.postchange_view, false),
          delBtn: this.vaildData(this.permission.postchange_delete, false),
          editBtn: this.vaildData(this.permission.postchange_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    created() {
      const _this = this;
      getUserListDeptChild().then(res => {
        const data = res.data.data;
        for (let i = 0; i < data.length; i++) {
          let item = data[i];
          item.text = item.name + '-' + item.ehr;
        }
        this.userList = data;
        /*this.groupEdit[0].column.forEach(item => {
          if (item.prop.indexOf('holder') > -1 || item.prop.indexOf('backup') > -1){
            item.dicData = data;
          }
        })
        this.groupView[0].column.forEach(item => {
          if (item.prop.indexOf('holder') > -1 || item.prop.indexOf('backup') > -1){
            item.dicData = data;
          }
          item.disabled = true;
        })*/
        this.initForm();
      })
    },
    mounted() {
      // this.initForm();
      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("postchange").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: {
      clearSelect(propPrefix){
        let keyArr = Object.keys(this.form);
        for (let i = 0; i < keyArr.length; i++) {
          let prop = keyArr[i];
          if (prop.indexOf(propPrefix) == 0 && prop.indexOf(propPrefix + '1') && prop.indexOf(propPrefix + '2') == -1){
            this.form[''+prop] = false;
          }
        }
      },
      testExcel(){
        let $a = document.getElementById("dl");
        $a.href = tableToExcel('mytable', 'testname');
        $a.click();
      },
      handleTransfer(){
        if (this.selectionList.length === 0) {
          this.$message.warning("請選擇至少一條數據");
          return;
        }
        let personSet = new Set(), processSet = new Set();
        for (let i = 0; i < this.selectionList.length; i++) {
          let item = this.selectionList[i];
          personSet.add(item.personNo);
          processSet.add(item.process)
        }
        if (personSet.size > 1 || processSet.size > 1 || !processSet.has(2)){
          this.$message.warning("請選擇同一人員的待確認任務！");
          return;
        }
        this.transferVisible = true;
      },
      transferCallback(row){

        if (this.selectionList && this.selectionList.length > 0 && this.selectionList[0].personNo == row.ehr){
          this.$message.warning("移交人不能為原審批人，請重新選擇！")
          return;
        }
        transfer(this.ids, row.ehr).then(() => {
          this.onLoad(this.page);
          this.transferVisible = false;
          this.$message({
            type: "success",
            message: "移交成功!"
          });
        });
      },
      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
        });
      },
      approveSubmit(row){

      },
      handleView(row, index){
        this.form = row;
        this.$refs.crud.rowView(row, index)
        /*getDetail(this.form.id).then(res => {
          let data = res.data.data;
          let holder = JSON.parse(data.holder);
          let backupPerson = JSON.parse(data.backupPerson);
          Object.assign(data, holder, backupPerson)
          this.form = data;

          this.form.previousId && getDetail(this.form.previousId).then(res => {
            let preData = res.data.data;
            let preholderStr = preData.holder.replace(/holder/ig, 'preholder');
            let prebackupPersonStr = preData.backupPerson.replace(/backup/ig, 'prebackup');
            let propreholder = JSON.parse(preholderStr);
            let prebackupPerson = JSON.parse(prebackupPersonStr);
            Object.assign(data, propreholder, prebackupPerson)
            this.form = data;
          })
        });*/
        // this.viewForm = row;
        // this.$refs.crudView.rowView(row, index)
      },
      approve(row, index){
        this.approveFlag = true;
        this.$refs.crud.rowEdit(row, index)
      },
      selectCallback(value){
        this.form.personId = value.id;
        this.form.personNo = value.ehr;
        this.form.personName = value.name;
      },
      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;
      },
      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();
          });
      },
      rowSave(row, done, loading) {
        this.beforeSave(row)
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
        // done();
      },
      rowUpdate(row, index, done, loading) {
        if (this.approveFlag){
          approve(row.id).then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            done();
          }, error => {
            loading();
            console.log(error);
          })
        }else{
          // delete row.id;
          delete row.backupPerson;
          delete row.holder;
          this.beforeSave(row)
          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();
          });
      },
      handleEdit(){
        // this.form = this.data[0];
        getLastRecord().then(res => {
          const data = res.data.data || {};
          data.applyDate = '',data.effectiveDate = '',data.remark = '';
          this.approveFlag = false;
          this.$refs.crud.rowEdit(data, 0)
        });

        /*let form = this.deepClone(this.data[0]);
        form.applyDate = '',form.effectiveDate = '',form.remark = '';
        this.approveFlag = false;
        this.$refs.crud.rowEdit(form, 0)*/
      },

      beforeOpen(done, type) {
        this.selectDisabled = type == 'view';
        this.type = type;
        let _this = this;
        let createUserName = this.form.createUserName;
        let createUserNo = this.form.createUserNo;
        if (this.form.id){
          getDetail(this.form.id).then(res => {
            preDeal(res);
          });
        }else {
          preDeal()
        }

        function preDeal(res){
          let data = !!res ? res.data.data : {};
          let holder = !!res ? JSON.parse(data.holder) : {};
          let backupPerson = !!res ? JSON.parse(data.backupPerson) : {};
          Object.assign(data, holder, backupPerson)
          data.createUserName = createUserName;
          data.createUserNo = createUserNo;
          if (type === 'edit' || type === 'add'){
            if (_this.approveFlag){
              _this.selectDisabled = true;
              _this.option.updateBtnText = '確認';
              _this.option.editTitle = '信息審核【網點出納主管及專管員崗位變更記錄表】';
              _this.option.column.forEach(item => {
                item.disabled = true;
              })
              _this.option.group.forEach(g => {
                g.column.forEach(item => {
                  item.disabled = true;
                })
              })

              _this.form = data;
            }else{
              // data.applyDate = '',data.remark = '',delete data.id;
              if (type === 'add'){
                data.applyDate = dateFormat(new Date(), "yyyy-MM-dd");
              }
              getCurrentDept().then(res => {
                const data2 =  res.data.data;
                data.bankNo = data2.bankNo;
                data.orgNo = data2.orgNo;
                data.orgName = data2.deptName;
                _this.form = data;
              });
              /*getSetting().then((res) => {
                let data = res.data.data;
                if (!!data){
                  _this.form.personId = data.personId;
                  _this.form.personNo = data.personNo;
                  _this.form.personName = data.personName;
                }
              });*/
              _this.option.updateBtnText = '提交';
              _this.option.editTitle = '編輯【網點出納主管及專管員崗位變更記錄表】';
              _this.option.column.forEach(item => {
                if (item.prop == 'bankNo' || item.prop == 'orgNo' ||item.prop == 'orgName' || item.prop == 'applyDate'|| item.prop == 'personNo'){
                  item.disabled = true;
                }else{
                  item.disabled = false;
                }
              })
              _this.option.group.forEach(g => {
                g.column.forEach(item => {
                  item.disabled = false;
                })
              })

            }
          }else{
            _this.form = data;
            if (_this.form.previousId && _this.form.previousId > 0){
              getDetail(_this.form.previousId).then(res => {
                let preData = res.data.data;
                let preholderStr = preData.holder.replace(/holder/ig, 'preholder');
                let prebackupPersonStr = preData.backupPerson.replace(/backup/ig, 'prebackup');
                let propreholder = JSON.parse(preholderStr);
                let prebackupPerson = JSON.parse(prebackupPersonStr);
                Object.assign(data, propreholder, prebackupPerson)
                _this.form = data;
              })
            }
          }
        }
        done();
      },
      initForm(){
        /*let holderObj = {
          label: "持有人",
          prop: "holder",
          span: 11,
          type: "select",
          multiple: true,
          dicData: this.userList,
          props: {
            label: "text",
            value: "ehr"
          },
        }
        let backupObj = {
          label: "後備人員",
          prop: "backupPerson",
          span: 11,
          type: "select",
          multiple: true,
          dicData: this.userList,
          props: {
            label: "text",
            value: "ehr"
          },
        }

        getDictByCode("cashier_key_type").then(res => {
          const data = res.data.data;
          let $groupEdit = this.groupEdit;
          let $groupView = this.groupView;
          data.forEach(item => {
            let code = item.dictKey;
            let value = item.dictValue;
            let $item = {};
            let $item12 = {};
            $item.label = value;
            $item12.label = value;
            let column = [];
            let column12 = [];
            getDictByCode(code).then(res2 => {
              const data2 = res2.data.data;
              data2.forEach(item2 => {
                let $item2 = {}
                let $item22 = {}
                $item2.label = item2.dictValue;
                $item22.label = item2.dictValue;
                // $item2.prop = item2.dictKey;
                $item2.type = 'text';
                $item22.type = 'text';
                $item2.span = 2;
                $item22.span = 4;
                column.push($item2)
                column12.push($item22)
                let holderItem = this.deepClone(holderObj);
                let holderItem2 = this.deepClone(holderObj);
                let backupItem = this.deepClone(backupObj);
                let backupItem2 = this.deepClone(backupObj);
                holderItem.prop = 'holder-' + item.dictKey + '-' + item2.dictKey;
                holderItem2.prop = 'preholder-' + item.dictKey + '-' + item2.dictKey;
                holderItem.span = 5;
                holderItem2.span = 5;
                // holderItem.label = '目前' + holderItem.label;
                holderItem2.label = '上期' + holderItem2.label;
                let h1 = this.deepClone(holderItem);
                h1.span = 11;
                column.push(h1)
                column12.push(holderItem2)
                column12.push(holderItem)
                backupItem.prop = 'backupPerson-' + item.dictKey + '-' + item2.dictKey;
                backupItem2.prop = 'prebackupPerson-' + item.dictKey + '-' + item2.dictKey;
                backupItem.span = 5;
                backupItem2.span = 5;
                // backupItem.label = '目前' + backupItem.label;
                backupItem2.label = '上期' + backupItem2.label;
                let b1 = this.deepClone(backupItem);
                b1.span = 11;
                column.push(b1)
                column12.push(backupItem2)
                column12.push(backupItem)
              })
            });
            $item.column = column;
            $item12.column = column12;
            $groupEdit.push($item)
            $groupView.push($item12)
            this.option.group = $groupEdit;
            this.optionForm.group = $groupView
          })
        });*/
        getDictByCodes("cashier_key_type").then(res => {
          const data = res.data.data;
          let dictData = [];

          let codeArr = [];
          let dictKV = {};

          for (let i = 0; i < data.length; i++) {
            let item = data[i];
            let code = item.dictKey;
            let value = item.dictValue;
            codeArr.push(code);
            dictKV[''+code] = value;
            /*getDictByCode(code).then(res2 => {
              const data2 = res2.data.data;
              // item.children = data2;
              for (let h = 0; h < data2.length; h++) {
                let item2 = data2[h], index = h;
                item2.index = index;
                item2.parentName = value;
                item2.rowspan = data2.length;
                dictData.push(item2)
              }
            });*/
          }
          getDictByCodes(codeArr.join()).then(res => {
            dictData = res.data.data;
            let rowspanKV = {};
            for (let j = 0; j < data.length; j++) {
              let item = data[j];
              let code = item.dictKey;
              let value = item.dictValue;
              let index = 0;
              for (let k = 0; k < dictData.length; k++) {
                let item2 = dictData[k];
                if (code == item2.code){
                  if (!rowspanKV[''+code]){
                    rowspanKV[''+code] = 1;
                  }else {
                    rowspanKV[''+code]++;
                  }
                  // rowspanKV[''+code] = item2.rowspan;
                  item2.parentName = value;
                  item2.index = index;
                  index++;
                }
              }
            }
            for (let m = 0; m < dictData.length; m++) {
              let item = dictData[m];
              item.rowspan = rowspanKV[''+item.code]
            }

            this.dicts = dictData;
          })
          // this.dicts = dictData;
          // console.table(dictData)
        });
      },
      beforeSave(row){
        let holder = {}, backupPerson = {};
        let keys = Object.keys(row);
        for (let i = 0; i < keys.length; i++) {
          let key = keys[i];
          if (key.indexOf('holder') > -1){
            holder['' + key] = row['' + key];
            delete row['' + key];
          }
          if (key.indexOf('backup') > -1){
            backupPerson['' + key] = row['' + key];
            delete row['' + key];
          }
          delete row['undefined']
        }
        row.holder = JSON.stringify(holder);
        row.backupPerson = JSON.stringify(backupPerson);
        return row;
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {

        if (params.effectiveDateRange){
          params.effectiveDate_begin = params.effectiveDateRange[0], params.effectiveDate_end = params.effectiveDateRange[1];
          params.effectiveDateRange = null;
        }
        if (params.orgNos){
          params.orgNostr = params.orgNos.join();
          params.orgNos = '';
        }

        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 && item.process != 3;
          }
          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;
        params.process = 2;
        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>
