<template>
  <ifbp-page>
    <ifbp-breadcrumb name="公司编辑"></ifbp-breadcrumb>
    <ifbp-main-area type="detail">
      <ifbp-panel-group>
      <ifbp-panel title="组织-公司" :icons="orgIcons">
        <ifbp-template
          ref="orgFormRef"
          show-type="form"
          tpl-id="orgId"
          :tpl-data="orgFormData"
          :funnode="orgFunnode"
          :nexuskey="orgNexuskey"
          :editable="isEdit"
          :form-show-message="isEdit">
        </ifbp-template>
      <div class="fr" v-if="isEdit">
        <el-button type="default"  @click="cancel">取消</el-button>
        <el-button type="primary"  @click="confirm">确定</el-button>
      </div>
      <div style="clear:both;"></div>
      </ifbp-panel>
      <ifbp-panel title="联系人" :icons="contactsIcons">
        <ifbp-template
          ref="contactsTableFormRef"
          show-type="table-form"
          tpl-id="contactsTableFormId"
          :tpl-data="contactsTableFormData"
          :funnode="contactsTableFormFunnode"
          :nexuskey="contactsTableFormNexuskey"
          :tpl-reset-fun="contactsTableFormTplResetFun"
          :editable="contactsTableFormIsEdit"
          :form-show-message="contactsTableFormIsEdit"
          @edit-table-click="contactsTableFormEdit"
          @delete-table-click="contactsTableFormDelete"
          @form-cancel-click="contactsTableFormCancel"
          @form-confirm-click="contactsTableFormConfirm">
        </ifbp-template>
      </ifbp-panel>
      <ifbp-panel title="银行账户" :icons="bankIcons">
        <ifbp-template
          ref="bankTableRef"
          show-type="table"
          tpl-id="bankTableId"
          :tpl-data="bankTplData"
          :funnode="bankFunnode"
          :nexuskey="bankNexuskey"
          :tpl-reset-fun="bankTableResetFun"
          @search-table-click="bankTableCheck"
          @edit-table-click="bankTableEdit"
          @delete-table-click="bankTableDelete">
        </ifbp-template>
        <el-dialog
          title="增加银行账户"
          size="large"
          v-model="showBankForm"
          :before-close="closeBankForm"
          @update:visible="val => multiDelDialogVisible = val">
          <ifbp-template ref="bankFormRef"
                        tpl-id="bankTableIdForm"
                        show-type="form"
                        :methods="bankMethods"
                        :tpl-data="bankTplData"
                        :funnode="bankFunnode"
                        :nexuskey="bankNexuskey"
                        :editable="isEditBankForm"
                        :form-show-message="isEditBankForm"
                        :tpl-reset-fun="bankFormResetFun">
          </ifbp-template>
          <div class="fr editBank" v-if="!isEditBankForm">
            <el-button @click="cancelShowBankForm">返 回</el-button>
            <el-button  type="primary" @click="isEditBankForm = true">编 辑</el-button>
          </div>
          <span v-else slot="footer" class="dialog-footer">
            <el-button @click="cancelShowBankForm">取 消</el-button>
            <el-button type="primary" @click="addBankForm">确 定</el-button>
          </span>
        </el-dialog>
      </ifbp-panel>
      </ifbp-panel-group>
    </ifbp-main-area>
  </ifbp-page>
</template>

<script>

  export default{
    data() {
      var vm = this;
      var patterns = {
          identity: /^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[A-Z])$/, // 身份证[17位数字校验+1位数字或字母X]
          residence: /^([0-9]){9}$/, // 户口簿[9位数字校验]
          passport: /^[a-z|A-Z]{1}[0-9]{8}$/, // 中国护照[1位字母+8位数字校验]
          officers: /^[0-9]{8}$/, // 军官证[8位数字校验]
          driving: /^[0-9]{18}$/, // 驾驶证[18位数字校验]
          macaoPermit: /^[a-z|A-Z]{1}[0-9]{8}$/, // 港澳通行证[1位字母+8位数字校验]
          taiwanPermit: /^[a-z|A-Z]{1}[0-9]{8}$/, // 台湾通行证[1位字母+8位数字校验]
          returnCard: /^[a-z|A-Z]{1}[0-9]{10}$/, // 返乡证[1位字母+10位数字校验]
          soldbuch: /^[0-9]{7}$/, // 士兵证[7位数字校验]
      };
      var documentidValidator = function(rule, val, callback) {
        var formData = vm.$refs.contactsTableFormRef.getFormData();
        if(formData && formData.document_type) {
          var typeName = vm.documentTypeMap[formData.document_type];
          if(typeName) {
            var pattern = patterns[typeName];
            if(!pattern.test(val)) {
              callback(new Error("证件号格式未匹配到 pattern: ") + pattern);
              return;
            }
          }
        }
        callback();
      };
      return {
        /* ==================== org ====================*/
        orgFunnode: 'ZZGL',
        orgNexuskey: 'ZZGL_GS',
        orgIcons: [{
          icon: 'edit',
          show: true,
          click: function() {
            vm.isEdit = true;
            vm.orgIcons[0].show = false;
          }
        }],
        orgFormData: {
          corp:{}
        },
        originalOrgFormData: {},
        /*===================== contacts ===================*/
        contactsTableFormFunnode: 'ZZGL',
        contactsTableFormNexuskey: 'ZZGL_LXR',
        contactsIcons: [{
          icon: 'plus',
          click: function() {
            // 关闭展开的列
            vm.$refs.contactsTableFormRef.getTableComp().closeExpandRow();
            // 重置新增的表单
            vm.$refs.contactsTableFormRef.resetFormData();
            // 显示表单新增区域
            vm.$refs.contactsTableFormRef.tableShow = false;
            vm.$refs.contactsTableFormRef.formShow = true;
            // 设置为编辑态
            vm.contactsTableFormIsEdit = true;
          }
        }],
        contactsTableFormIsEdit: false,
        contactsTableFormData: {
          corpcontacts_t: [],
          corpcontacts: {},
          rules:{
            document_id: [{
              validator: documentidValidator,
              trigger: 'blur',
              message: '证件号格式错误'
            }]
          }
        },
        contactsTableFormTplResetFun: function($node){
          let $table = $node.find('el-table');
          let operateArr = [
                {
                    icon: 'edit',
                    title: "编辑"
                },
                {
                    icon: "delete",
                    title: "删除"
                }
            ];
          let operateHtml = this.getTableOperateHtml(operateArr);
          $table.append(operateHtml);
        },
        /*===================== bank ===================*/
        bankFunnode: 'ZZGL',
        bankNexuskey: 'ZZGL_BANK',
        bankIcons: [{
          icon: 'plus',
          click: function () {
            vm.isAddBankForm = true;
            vm.isEditBankForm = true;
            vm.showBankForm = true;
            vm.$nextTick(() => {
              vm.$refs.bankFormRef.resetFormData();
            });
          }
        }],
        bankTplData: {
          BankAccBas_t: [],
          BankAccBas: {},
          bankdocQueryParams: {},
          bankdocBeforeQuery: function() {
            if(this.field === 'pk_bankdoc'){
              if(!vm.$refs['bankFormRef'].getFormData().pk_banktype){
                vm.$message('请选择银行类别');
                return false;
              }
            }
            return true;
          }
        },
        bankMethods: {
          banktypeRefChange(type, val) {
            var banktypeId = val.value[0].id;
            if(type="change") {
              vm.$refs.bankFormRef.setData("bankdocQueryParams", {pk_banktype: banktypeId});
            }
          },
        },
        bankTableResetFun: function($node){
          let $table = $node.find('el-table');
          let operateArr = [
                {
                    icon: 'search',
                    title: "查看"
                },
                {
                    icon: 'edit',
                    title: "编辑"
                },
                {
                    icon: "delete",
                    title: "删除"
                }
            ];
          let operateHtml = this.getTableOperateHtml(operateArr);
          $table.append(operateHtml);
        },
        bankFormResetFun: function($node){
          let $form = $node.find("el-form");
          var $banktypeRef = $node.find("el-ref[field='pk_banktype']");
          $banktypeRef.attr("v-on:trigger", "banktypeRefChange");
          var $bankdocRef = $node.find("el-ref[field='pk_bankdoc']");
          $bankdocRef.attr("v-bind:before-query", "bankdocBeforeQuery");
        },
        documentTypeMap: { // document_type to document_id Map
          '0': 'identity', // 身份证
          '1': 'residence',// 户口簿
          '2':'passport', // 中国护照
          '3':'officers', // 军官证
          'D':'driving', // 驾驶证
          'B':'macaoPermit', // 港澳通行证
          'C':'taiwanPermit', // 台湾通行证
          'E':'returnCard', // 返乡证
          '4':'soldbuch' // 士兵证
        },
        isEdit: false,
        orgId:'',
        isCreate: false, //主表是否已经保存
        isEditBankForm: false, //是否是编辑状态
        showBankForm: false, //显示银行账户表单
        isAddBankForm:false,
        list: '',
      };
    },
    methods:{
      // 取消新增银行账户
      cancelShowBankForm(){
        this.showBankForm = false;
        this.isEditBankForm = false;
      },
      //点击银行账户查看按钮
      bankTableCheck(scope){
        var bankRecordForm = JSON.parse(JSON.stringify(scope.row));
        this.showBankForm = true;
        this.isEditBankForm = false;
        this.$nextTick(() => {
          this.$refs.bankFormRef.setFormData(bankRecordForm);
        });
      },
      //点击银行账户编辑按钮
      bankTableEdit(scope){
        // if (!this.isCreate) {
        //   this.$message('请先修改并保存主表数据');
        //   return;
        // }
        var bankRecordForm = JSON.parse(JSON.stringify(scope.row));
        this.isAddBankForm = false;
        this.showBankForm = true;
        this.isEditBankForm = true;
        this.bankRowId = scope.$index;
        this.$nextTick(() => {
          this.$refs.bankFormRef.setFormData(bankRecordForm);
        });
      },
      //点击银行账户删除数据
      bankTableDelete (scope) {
        const self = this;
        self.$confirm('是否删除当前记录?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          self.$http({
            url: '/ifbp-app-bd/bd/org/corp/deleteBank?id=' + scope.row.pk_bankaccbas,
            method: 'DELETE',
          }).then((res) => {
            if (res.data.success === true) {
              var bankTableData = self.$refs.bankTableRef.getTableData();
              bankTableData.splice(scope.$index,1);
              self.$message('删除成功');
            } else {
              self.$message('删除失败');
            }
            }).catch(() => {
              self.$message('删除失败');
            });
        }).catch(() => {
          self.$message('已取消删除');
        });
      },
      bankRowClick(row){
        this.bankRowId = row;
      },
      //点击新增银行账户按钮
      addBankRow() {
        // if (!this.isCreate) {
        //   this.$message('请先修改并保存主表数据');
        //   return;
        // }
        this.isAddBankForm = true;
        this.isEditBankForm = true;
        this.showBankForm = true;
        this.$nextTick(() => {
          this.$refs.bankFormRef.resetFormData();
        });
      },
      //请求组织银行信息
      requestBankValues(){
        const self = this;
        this.$http({
          url:'/ifbp-app-bd/bd/org/corp/bankList?id='+this.orgId,
          type:'get'
        }).then((res) => {
          if(res.data.success === true){
            this.$nextTick(() => {
              if(self.$refs.bankTableRef) {
                self.$refs.bankTableRef.setTableData(res.data.data);
              } else {
                self.$set(self.bankTplData, 'uitemplateTableData', res.data.data);
              }
            });
          }
        }).catch(() => {
          this.$message.error('请求银行信息失败');
        });
      },
      //点击保存新增银行账户按钮
      addBankForm () {
        const self = this;
        var submitData = {};
        var bankaccbas = this.$refs.bankFormRef.getFormData();
        this.$set(submitData,'BankAccBas',bankaccbas);
        this.$set(submitData,'id',self.orgId);
        this.$refs.bankFormRef.getFormComp().validate((valid) => {
          if(valid){
            self.$http({
            url: '/ifbp-app-bd/bd/org/corp/addBank',
            method: 'post',
            dataType: 'json',
            data: submitData,
          }).then((res) => {
            if(res.data.success === true){
              var bankTableData = self.$refs.bankTableRef.getTableData();
              if(self.isAddBankForm){
                bankTableData.unshift(res.data.data);
                self.$message({
                message:'保存成功',
              });
              }else {
                bankTableData.splice(self.bankRowId,1,res.data.data);
                self.$message({
                  message:'修改成功',
                });
              }
              self.showBankForm = false;
            } else {
              self.$message.error(res.data.error.errorMessage);
            }
          }).catch(() => {
            self.$message({
              message: '请求出错！',
              type: 'error'
            });
          });
          }else{
            self.$message({
              message: '验证失败',
              type: 'error'
            });
          }
        })
      },
      // 获取组织-公司的id，orgId
      getOrgId(){
        var url = window.location.href;
        var orgId = url.split('organization')[1].split('/')[1];
        this.orgId = orgId;
      },
      // 请求组织的详细信息,包括银行和联系人（id_corpcontacts）的信息
      request(){
        const self = this;
        this.$http({
          url: '/ifbp-app-bd/bd/org/corp/' + this.orgId,
          method: 'get'
        }).then((res) => {
          if(res.data.success){
            self.$nextTick(() => {
              if(self.$refs.orgFormRef) {
                this.originalOrgFormData = JSON.parse(JSON.stringify(res.data.data));
                self.$refs.orgFormRef.setFormData(JSON.parse(JSON.stringify(res.data.data)));
                if(res.data.data.id_corpcontacts.length !== 0){
                  self.$refs.contactsTableFormRef.setTableData(res.data.data.id_corpcontacts);
                }
              } else {
                self.$set(self.orgFormRef, 'uitemplateTableData', res.data.data);
              }
            });
          }
        }).catch(() => {
          this.$message({
            message: '获取公司信息失败！',
            type: 'error'
          });
        });
      },
      // 保存组织公司信息
      confirm(){
        const self = this;
        this.$refs.orgFormRef.getFormComp().validate((valid) => {
          if(valid) {
            var submitData = self.$refs.orgFormRef.getFormData();
            this.$http({
              url: '/ifbp-app-bd/bd/org/corp/',
              method: 'PUT',
              data: submitData
            }).then((res) => {
              if (res.data.success === true) {
                if (window.env === 'dev') {
                  this.$message({
                    message: '修改成功',
                    type: 'success'
                  });
                }
                self.isEdit = false;
                self.isCreate = true;
                self.orgIcons[0].show = true;
              } else {
                this.$message({
                  message: res.data.error.errorMessage,
                  type: 'error'
                });
              }
            }).catch(() => {
              this.$message({
                message: '修改接口调用失败！',
                type: 'error'
              });
            });
          } else {
            // 验证失败
          }
        });
      },
      closeBankForm(done){
        this.showBankForm = false;
        done();
      },
      cancel(){
        this.isEdit = false;
        this.isCreate = true;
        this.orgIcons[0].show = true;
        this.$nextTick(() => {
          this.$refs.orgFormRef.setFormData(JSON.parse(JSON.stringify(this.originalOrgFormData)));
        });
      },
      backInfo(){
        this.$router.push('/HR010003');
      },
      // // 新增联系人
      // addContacts(){
      //   // 关闭展开的列
      //   this.$refs.contactsTableFormRef.getTableComp().closeExpandRow();
      //   // 重置新增的表单
      //   this.$refs.contactsTableFormRef.resetFormData();
      //   // 显示表单新增区域
      //   this.$refs.contactsTableFormRef.tableShow = false;
      //   this.$refs.contactsTableFormRef.formShow = true;
      //   // 设置为编辑态
      //   this.contactsTableFormIsEdit = true;
      // },
      // 编辑联系人
      contactsTableFormEdit(scope){
        this.$refs.contactsTableFormRef.getTableComp().closeExpandRow();
        this.$refs.contactsTableFormRef.setFormData(scope.row);
        this.$refs.contactsTableFormRef.tableShow = false;
        this.$refs.contactsTableFormRef.formShow = true;
        this.contactsTableFormIsEdit = true;
      },
      // 删除联系人
      contactsTableFormDelete(scope){
        const self = this;
        this.$http({
          method: 'delete',
          url: '/ifbp-app-bd/bd/org/corp/child?idtype=id_corpcontacts&id='+ scope.row.id,
        }).then((res) => {
          if(res.data.success === true){
            self.request();
            self.$message({
              type: 'success',
              message: '删除成功'
            });
          }
        }).catch(() => {
          slef.$message({
            type: 'error',
            message: '删除失败'
          });
        });
      },
      // 展现为form是按钮的操作
      contactsTableFormConfirm(type){
        const self = this;
        this.$refs.contactsTableFormRef.validate((valid) => {
          if(valid){
            var formData = self.$refs.contactsTableFormRef.getFormData();
            var submitData = {
              Corpcontacts: formData,
              id: self.orgId
            };
            self.$http({
              method: 'post',
              url: '/ifbp-app-bd/bd/org/corp/contacts',
              data: submitData
            }).then((res) => {
              if(res.data.success === true){
                if(formData.id === ''){
                  self.$message({
                    type: 'success',
                    message: '新增成功'
                  });
                } else {
                  self.$message({
                    type: 'success',
                    message: '修改成功'
                  });
                }
                self.$refs.contactsTableFormRef.formShow = false;
                self.$refs.contactsTableFormRef.tableShow = true;
                self.contactsTableFormIdIsEdit = false;
                self.request();
              } else{
                self.$message({
                  type: 'error',
                  message: res.data.error.errorMessage
                });
              }
            }).catch(() => {
              self.$message({
                type: 'error',
                message: '接口调用出错'
              });
            });
          }
        });
      },
      contactsTableFormCancel(type){
        if(type === 'form'){
          this.$refs.contactsTableFormRef.formShow = false;
          this.$refs.contactsTableFormRef.tableShow = true;
          this.contactsTableFormIsEdit = false;
        } else{
          this.$refs.contactsTableFormRef.formShow = false;
          this.$refs.contactsTableFormRef.tableShow = true;
          this.contactsTableFormIsEdit = false;
          this.$refs.contactsTableFormRef.getTableComp().closeExpandRow();
        }
      },
    },
    created() {
      this.getOrgId();
      this.requestBankValues();
      this.request();
    },
    watch:{
      bankRecordCurrentValue:{
        handler: function(){
          var type  = this.bankRecordCurrentValue.pk_banktype;
          if(type){
            this.refQueryParamsBank =[{itemCode:'BankAccBas.pk_bankdoc',params:{pk_banktype:type}}];
            this.$refs['bank-record-form'].$refs.form.$refs.pk_bankdoc1[0].changeRefQueryParams(this.refQueryParamsBank);
          }
        },
        deep: true
      }
    }
  };
</script>
