<template>
  <basic-container>
    <basic-container>
      <el-select v-model="value" filterable placeholder="請選擇" @change="selectTable">
        <el-option
          v-for="(item, idx) in tableList"
          :key="idx"
          :label="item.name"
          :value="item.id">
        </el-option>
      </el-select>
    </basic-container>

    <div v-if="show">
      <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">
        </template>

        <template slot="fileForm" slot-scope="{row}">
          <avue-form ref="form" :option="attachOption" v-model="attachForm" :upload-after="uploadAfter" :upload-error="uploadError" :upload-delete="uploadDelete" :upload-preview="uploadPreview">
          </avue-form>
        </template>

        <template slot="receiverNameForm" slot-scope="{row}">
          <select-user :multiple="false" :name="approvePerson.name" :callback="selectCallback"></select-user>
<!--          <select-dialog-user :id="approvePerson.id" :name="approvePerson.name" :ehr="approvePerson.ehr" :disabled="false" :callback="selectCallback"></select-dialog-user>-->
        </template>

        <template slot-scope="{row, index}" slot="menu">
          <el-button size="small" class="el-button--text" v-if="userInfo.user_id == row.createUser && tableEditBtn && ((approveType == 1 && (row.processStatus == '已退回' || (row.processStatus == '待審核' && !row.approveHistory))) || (approveType == 2 && !row.approveHistory))"
                     @click="formEdit(row, index)"><i class="el-icon-edit"></i> 編 輯</el-button>
          <el-button type="text" icon="el-icon-download" size="small" v-if="row.file" @click="handleDownload(row)">下載</el-button>
          <el-button type="text" icon="el-icon-check" size="small" v-if="approveSwitch == 1 && ( (approveType == 1 && row.process > 0 && row.process <= approveNum) || approveType == 2 )  && row.receiverId.indexOf(userInfo.user_id) > -1 && userInfo.user_id != row.createUser"
                     @click.native="approveShow(row)">審批</el-button>

        </template>
      </avue-crud>


      <el-dialog :append-to-body="true" :modal-append-to-body="false" :destroy-on-close="true" :visible.sync="approveVisible" title="審批" width="70%">
        <div v-if="approveVisible">
          <avue-form ref="approveForm" :option="approveOption" v-model="approveForm" @submit="approveYes">
            <template slot="receiverName">
              <select-user :multiple="false" :name="approvePerson.name" :callback="selectCallback"></select-user>
<!--              <select-dialog-user :id="approvePerson.id" :name="approvePerson.name" :ehr="approvePerson.ehr" :disabled="false" :callback="selectCallback"></select-dialog-user>-->
            </template>

            <template slot-scope="scope" slot="menuForm">
              <el-button type="warning" size="small" v-if="bohuiBtn" icon="el-icon-close" @click="approveReject">退回</el-button>
              <el-button type="danger" size="small"
                         v-if="approveSwitch == 1 && approveType == 2"
                         icon="el-icon-close" @click="approveNo">不通過</el-button>
            </template>
          </avue-form>
        </div>
      </el-dialog>
    </div>
  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove, approveYes, approveNo, approveReject} from "@/api/bank/autodata";
  import {mapGetters} from "vuex";
  import {getSelectAndPermissionByDept} from "@/api/bank/autostruct";
  import {opStr2opObj} from "../../api/bank/autostruct";
  import { getCurrentDept } from "@/api/system/dept";
  import {downloadFileBase64, downloadFileBlob} from "@/util/util";
  import SelectDialogUser from "../../components/select-dialog/select-dialog-user";
  import SelectUser from "../../components/select-dialog/select-user";

  export default {
    components: {SelectUser, SelectDialogUser},
    data() {
      return {

        attachBox: false,
        attachForm: {},
        attachOption: {
          submitBtn: false,
          emptyBtn: false,
          column: [
            {
              // label: '附件上傳',
              prop: 'attachFile',
              type: 'upload',
              disabled: true,
              drag: true,
              loadText: '模板上傳中，請稍等',
              span: 24,
              fileSize: 5120,
              propsHttp: {
                res: 'data'
              },
              name: "namesrc",
              action: "/api/blade-resource/oss/endpoint/put-file-attach"
            }
          ]
        },

        approvePerson: {
          id: '',
          name: '',
          ehr: '',
        },
        tableEditBtn: false,
        approveSwitch: false,
        approveType: '',
        bohuiBtn: false,
        approveNum: 0,
        approveVisible: false,
        approveForm: {},
        approveOption: {
          submitText: "通過",
          emptyBtn: false,
          column: []
        },

        show: false,
        value: '',
        tableList: [],

        form: {},
        query: {},
        loading: true,
        deleteBatch: false,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          height:'auto',
          calcHeight: 30,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          viewBtn: true,
          selection: true,
          dialogClickModal: false,
          column: [
          ]
        },
        data: [],
        defaultColumn: [
          {
            label: "填報時間",
            prop: "createTime",
            viewDisplay: false,
            addDisplay: false,
            editDisplay: false,
            rules: [{
              required: true,
              message: "請輸入填報時間",
              trigger: "blur"
            }]
          },
          {
            label: "填報人",
            prop: "createUserName",
            viewDisplay: false,
            addDisplay: false,
            editDisplay: false,
            rules: [{
              required: true,
              message: "請輸入填報人",
              trigger: "blur"
            }]
          },
          {
            label: "審批人",
            prop: "receiverName",
            viewDisplay: false,
            addDisplay: true,
            editDisplay: true,
            formslot: true,
            rules: [{
              required: true,
              message: "請選擇審批人",
              trigger: "change"
            }]
          },
          {
            label: "備註",
            prop: "remark",
            type: "textarea",
            span: 24,
          }
        ]
      };
    },
    computed: {
      ...mapGetters(["permission", "userInfo"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.autodata_add, false),
          viewBtn: this.vaildData(this.permission.autodata_view, false),
          delBtn: this.vaildData(this.permission.autodata_delete, false),
          editBtn: this.vaildData(this.permission.autodata_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    mounted() {
      // let data = {column:[{type:'input',label:'姓名',span:12,display:true,prop:'name',required:true,rules:[{required:true,message:'姓名必須填寫'}]},{type:'input',label:'年齡',span:12,display:true,prop:'age'},{type:'input',label:'手機號',span:12,display:true,prop:'phone',maxlength:11},{type:'input',label:'住址',span:12,display:true,prop:'address'}],labelPosition:'right',labelSuffix:'：',labelWidth:120,gutter:0,menuBtn:true,submitBtn:true,submitText:'提交',emptyBtn:true,emptyText:'清空',menuPosition:'center'};
      // this.option = data;
      this.initTableList();
    },
    methods: {
      formEdit(row, index){
        let columns = this.option.column;
        for (let i = 0; i < columns.length; i++) {
          let item = columns[i];
          item.editDisabled = false;
        }
        this.$refs.crud.rowEdit(row, index);
      },
      approveYes(data, done){
        let row = this.deepClone(this.approveForm);
        delete row.createTime,delete row.createUser,delete row.createUserName;
        let form = this.beforeSave(row);
        form.id = row.id, form.remark = row.remark;
        approveYes(form).then(res => {
          this.approveVisible = false;
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "審批成功!"
          });
        })
        done();
      },
      approveReject(){
        let row = this.deepClone(this.approveForm);
        delete row.createTime,delete row.createUser,delete row.createUserName;
        let form = this.beforeSave(row);
        form.id = row.id, form.remark = row.remark;
        approveReject(form).then(res => {
          this.approveVisible = false;
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "退回成功!"
          });
        })
      },
      approveNo(){
        let row = this.deepClone(this.approveForm);
        delete row.createTime,delete row.createUser,delete row.createUserName;
        let form = this.beforeSave(row);
        form.id = row.id, form.remark = row.remark;
        approveNo(form).then(res => {
          this.approveVisible = false;
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "審批成功!"
          });
        })
      },
      approveShow(row){
        this.bohuiBtn = row.process > 1;
        this.approveForm = row;
        delete this.approveForm.receiverName;
        this.approvePerson.name = '';
        this.approveVisible = true;
      },
      selectCallback(list){
        let data = list[0];
        this.form.receiverName = data.name;
        this.approveForm.receiverName = data.name;
        this.approvePerson.id = data.id;
        this.approvePerson.name = data.name;
        this.approvePerson.ehr = data.ehr;
      },
      handleDownload(row) {
        let fileName = row.file.split("/").pop();
        downloadFileBase64(row.file, fileName);
      },

      uploadError(error,column){
        this.$message.warning(error + '，不能大於' + column.fileSize + 'KB');
      },
      uploadAfter(res, done, loading, column) {
        this.attachForm.attachFile = [res];
        this.form.file = res.link;
        this.attachBox = false;
        done(res);
      },
      uploadDelete(column,file) {
        return this.$confirm(`是否確定移除該選項？`);
      },
      uploadPreview(){
      },

      initTableList(){
        getSelectAndPermissionByDept().then(res => {
          const data = res.data.data;
          this.tableList = data;
          if (this.tableList.length > 0){
            this.value = this.tableList[0].id;
            this.selectTable(this.value)
          }
        });
      },
      selectTable(value){
        let _this = this;
        this.show = false;
        let tableStruct = this.getItemById(value);
        this.approveSwitch = tableStruct.approveSwitch;
        this.approveType = tableStruct.approveType;
        this.approveNum = tableStruct.num;
        let option = opStr2opObj(tableStruct.columns);
        option.addBtn = tableStruct.canWrite;
        _this.deleteBatch = tableStruct.isManageRole;
        option.delBtn = tableStruct.isManageRole;
        option.excelBtn = tableStruct.isManageRole;
        option.editBtn = false;
        option.viewBtn = true;
        this.tableEditBtn = tableStruct.approveSwitch == 1;
        option.searchMenuSpan = 6;
        option.column.forEach((item, index) => {
          item.search = index >= 3 && index < 7 && item.type != 'title';
          item.editDisabled = true;
          if (item.dicUrl){
            item.dicFormatter = (res) => {
              res.data.forEach(item => {item.disabled = item.isSealed == 1;})
              return res.data;
            };
          }
          if (item.prop === 'file'){
            item.hide = true;
          }
        });
        option.column.push(this.defaultColumn[0]);
        option.column.push(this.defaultColumn[1]);
        //開流程 && 串行 && 逐級審批
        if (tableStruct.approveSwitch == 1 && tableStruct.approveType == 1 && tableStruct.settingType == 2){
          // 增加審批人選擇
          option.column.push(this.defaultColumn[2])
        }
        this.option = option;
        this.approveOption.column = this.deepClone(option.column);
        this.approveOption.column.forEach(item => {
          item.disabled = true;
          if (item.prop == 'receiverName'){
            item.disabled = false;
          }
        })
        this.approveOption.column.push(this.defaultColumn[3])

        setTimeout(() => {
          _this.show = true;
          _this.onLoad(this.page)
        }, 50)

      },
      getItemById(id){
        for (let i = 0; i < this.tableList.length; i++) {
          let item = this.tableList[i];
          if (item.id == id){
            return item;
          }
        }
      },
      beforeSave(row){
        let  keys = Object.keys(row);
        let form = {}
        let n = 1;
        for(let i = 0; i < keys.length; i++){
          let item = {};
          if (keys[i].indexOf("$") == 0 || keys[i] == ("id") || keys[i] == "createTime" || keys[i]=="createUser" || keys[i]=="createDept" || keys[i]=="receiverId" || keys[i]=="receiverName"
            || keys[i]=="receiverNo" || keys[i]=="approveId" || keys[i]=="approveName" || keys[i]=="approveNo" || keys[i]=="remark" || keys[i] == "process" || keys[i] == "key"
            || keys[i] == "processStatus" || keys[i] == "approveHistory"){
          }else{
            item['' + keys[i]] = row[''+keys[i]];
            form['params'+(n++)] = JSON.stringify(item);
          }
        }
        form.tableId = this.value;
        if (this.approvePerson.id && this.approvePerson.name && this.approvePerson.ehr){
          form.receiverId = this.approvePerson.id;
          form.receiverName = this.approvePerson.name;
          form.receiverNo = this.approvePerson.ehr;
        }
        return form;
      },
      rowSave(row, done, loading) {
        delete row.createTime,delete row.createUser,delete row.createUserName;
        let form = this.beforeSave(row)
        add(form).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        let formTem = this.deepClone(row);
        delete formTem.$index,delete formTem.createDept,delete formTem.createTime,delete formTem.createUser,delete formTem.createUserName;
      // ,delete formTem.id
        let form = this.beforeSave(formTem);
        form.id = row.id;
        let columns = this.option.column;
        update(form).then(() => {
          columns.forEach(item => {
            item.editDisabled = true;
          })
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          console.log(error);
        });
      },
      rowDel(row) {
        this.$confirm("確定將選擇數據刪除?", {
          confirmButtonText: "確定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("請選擇至少一條數據");
          return;
        }
        this.$confirm("確定將選擇數據刪除?", {
          confirmButtonText: "確定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {

        // 查看時，把上傳組件設為禁用
        this.attachForm = {};
        this.attachOption.column[0].disabled = type == 'view';

        let data = this.form;
        if (data.file){
          let fileName = data.file.split("/").pop();
          // data.name = fileName;
          this.attachForm.attachFile = [
            {label: fileName, value: fileName}
          ];
        }

        if (["edit", "view"].includes(type)) {
          /*getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });*/
        }
        if (type == 'add'){
          getCurrentDept().then(res => {
            const data =  res.data.data;
            this.form.bankNo = data.bankNo;
            this.form.orgNo = data.orgNo;
            this.form.orgName = data.deptName;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },

      initSearchParams(params){
        let keys = Object.keys(params);
        let resultParams = {};
        keys.forEach(key => {
          this.option.column.forEach((item, index) => {
            if (item.prop == key){
              let obj = {};
              let value = params[''+key];
              let length = key.length + 5 + value.length;
              obj[''+key] = params[''+key];
              resultParams['params' + (index+1)] = JSON.stringify(obj).substring(0,length);
            }
          })
        })
        return resultParams;
      },

      searchChange(params, done) {
        this.query = this.initSearchParams(params);
        // this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      initData(data){
        let newData = [];
        for (let i = 0; i < data.length; i++) {
          let row = data[i];
          let form = {};
          form.id = row.id, form.createUser = row.createUser,form.createUserName = row.createUserName, form.createTime = row.createTime, form.createDept = row.createDept;
          form.processStatus = row.processStatus, form.createUser = row.createUser,form.createUserName = row.createUserName, form.createTime = row.createTime, form.createDept = row.createDept;
          delete row.processStatus, delete row.createUser, delete row.createUserName, delete row.createTime, delete row.createDept;
          form.receiverId = row.receiverId, form.receiverNo = row.receiverNo, form.receiverName = row.receiverName;
          delete row.receiverId, delete row.receiverNo, delete row.receiverName;
          form.process = row.process, form.remark = row.remark, form.approveId = row.approveId, form.approveName = row.approveName, form.approveNo = row.approveNo;
          delete row.process, delete row.remark, delete row.approveId, delete row.approveName, delete row.approveNo;
          form.approveHistory = row.approveHistory;
          delete row.key, delete row.approveHistory;
          let keys = Object.keys(row);
          for (let j = 0; j < keys.length; j++) {
            let key = keys[j];
            if (key.indexOf("params") != -1){
              let value = row['' + key];
              console.log('value' + value)
              if (value != ''){
                let item = JSON.parse(value);
                item.key = key;
                Object.assign(form, item);
              }
            }
          }
          newData.push(form)
        }
        // 設置審核按鈕權限
        /*if (this.userInfo.user_id == form.receiverId){
        }*/
        return newData;
      },
      onLoad(page, params = {}) {
        this.loading = true;
        params.tableId = this.value;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = this.initData(data.records);
          console.log(this.data)
          this.loading = false;
          this.selectionClear();
        });
      }
    }
  };
</script>

<style>
</style>
