<template>
  <div class="">
    <div class="" v-for="(item, index) in dynamicPanelData">
      <ifbp-panel :title="item.title" :icons="childIcons" :data-index="index" :data-code="item.code"  :id="item.code">
            <ifbp-template :ref="'dynamic_'+item.code"
                      :tplId="'dynamic_'+item.code"
                      :funnode="item.funnode"
                      :nexuskey="item.nexuskey"
                      show-type="table-form"
                      :tpl-data="dynamicData[item.id]"
                      :tpl-reset-fun="typicalDemoChildResetFun"
                      @edit-table-click="function(scope){childEditClick(item,index,scope)}"
                      @delete-table-click="function(scope){childDeleteClick(item,index,scope)}"
                      @form-confirm-click="function(type){childFormConfirm(item,index,type)}"
                      @form-cancel-click="function(type){childFormCancel(item,index,type)}"
                      >
            </ifbp-template>
            <ifbp-del-dialog
            v-model="childDelDialogVisible"
            message="确认删除该数据？删除后无法恢复。"
            @click="childDeleteDialogClick"
            >
          </ifbp-del-dialog>
      </ifbp-panel>
    </div>


  </div>
</template>

<script>
export default {
  name: 'IfbpDynamicPanel',
  data() {
    return {
      childIcons: [{
        icon: 'plus',
        click: (e) => {
          var parentDom = e.currentTarget.parentNode.parentNode;
          if (parentDom) {
            var index = parentDom.getAttribute('data-index');
            var code = parentDom.getAttribute('data-code');
          } else {
            return;
          }
          if (!this.parentId) {
            this.$message({
              message: '请先保存主表信息',
              type: 'error'
            });
          } else {
            // 关闭table中的编辑区
            this.$refs['dynamic_' + code][0].getTableComp().closeExpandRow();
            // 重置新增数据
            this.$refs['dynamic_' + code][0].resetFormData();
            // 显示新增区域
            this.$refs['dynamic_' + code][0].formShow = true;
          }
        }
      }],
      dynamicData: {},
      childBaseData: {},
      childDelData: {},
      childDelDialogVisible: false,
      typicalDemoChildResetFun($node) {
        var $table = this.getTableDom($node);
        var $operateHtml = this.getBaseTableOperateHtml();
        $table.append($operateHtml);
        return $node[0].outerHTML;
      }
    };
  },
  props:{
    busiCode:{
      type:String
    },
    dynamicCode:{
      type:String
    },
    dynamicPanelData:{
      default: []
    },
    isCreate:{
      type:Boolean,
      default:true
    },
    parentId:{
      type:String
    },
    defaultCrud:{
      type:String,
      default:"true"
    }
  },
  watch: {
    dynamicPanelData(val) {
      // var dynamicTplData = {};
      for (var i = 0; i < val.length; i++) {
         // dynamicTplData[={};
         this.dynamicData[val[i].id] = {};
      }
    },
  },
  methods: {
    /**
     *返回所有数据
     */
    getAllData(){
      var datas = {};
      for (let i = 0; i < this.dynamicPanelData.length; i++) {
        var code  = this.dynamicPanelData[i].code;
        var uitemplate = this.$refs['dynamic_' + code][0]; 
        datas[code] =  uitemplate.getTableData() || uitemplate.getFormData();
      }  
      return datas;
    },
    /**
     *获取数据
     */
    getDataByCode(code){
        var uitemplate = this.$refs['dynamic_' + code][0]; 
        var data =  uitemplate.getTableData() || uitemplate.getFormData();
        return data;
    },
    /**
     *设置数据
     */
    setDataByCode(code, data){
        var uitemplate = this.$refs['dynamic_' + code][0]; 
        if (uitemplate.showType == 'form'){
          uitemplate.setFormData(data);
        }else{
          uitemplate.setTableData(data);
        }
    },
    childEditClick(item, index, scope) {
      this.$refs['dynamic_' + item.code][0].getTableComp().expandRow(scope.row);
      this.$refs['dynamic_' + item.code][0].formShow = false;
      this.$refs['dynamic_' + item.code][0].setFormData(scope.row);
      // 备份数据
      this.childBaseData = JSON.parse(JSON.stringify(scope.row));
      this.childEditIndex = scope.$index;
    },
    childDeleteClick(item, index, scope) {
      this.childDelDialogVisible = true;
      this.childDelData = scope.row;
      this.childIndex = index;

    },
    childDeleteDialogClick() {
      var data = this.childDelData;
      var url = this.dynamicPanelData[this.childIndex].deleteURL;
      if (this.defaultCrud === "true"){
        this.$http({
            url: url,
            method: 'post',
            data: data,
            headers: {
              'Content-Type': 'application/json'
            },
            dataType: 'application/json'
          })
          .then(res => {
            this.$emit('requestDynamic', res.data);
            if (res.data.success === true) {
              this.$message({
                message: '删除成功',
                type: 'success'
              });
              this.childDelDialogVisible = false;
              this.dynamicRequest();
            } else {
              this.$message({
                message: res.data.error.errorMessage,
                type: 'error'
              });
            }
          })
          .catch(() => {
            this.$message({
              message: '删除失败',
              type: 'error'
            });
          });
      }
    },
    childFormConfirm(item, index, type) {
      var vm = this;
      var url = this.dynamicPanelData[index].updateURL;
      this.$refs['dynamic_' + item.code][0].validate(valid => {
        if (valid) {
          var data = vm.$refs['dynamic_' + item.code][0].getFormData();
          // 拼接主表的id
          data = $.extend(data, {
            pk_example: vm.parentId
          });
          if (type === 'form') {
            url = this.dynamicPanelData[index].saveURL;
          }
          if (this.defaultCrud === "true"){
            vm.$http({
              url: url,
              method: 'post',
              data: data,
              headers: {
                'Content-Type': 'application/json'
              },
              dataType: 'application/json'
            })
            .then(res => {
              if (res.data.success) {
                vm.$message({
                  message: '保存成功'
                });
                vm.$refs['dynamic_' + item.code][0].tableShow = true;
                // 隐藏新增区域
                vm.$refs['dynamic_' + item.code][0].formShow = false;
                // 关闭Table中的编辑区域
                vm.$refs['dynamic_' + item.code][0].getTableComp().closeExpandRow();
                if (type === 'form') {
                  vm.dynamicRequest();
                }
              } else {
                vm.$message({
                  message: res.data.error.errorMessage,
                  type: 'error'
                });
              }
            })
            .catch(() => {
              vm.$message({
                message: '保存失败',
                type: 'error'
              });
            });
          }else{
            var data = vm.$refs['dynamic_' + item.code][0].getFormData();
            var tableData = vm.$refs['dynamic_' + item.code][0].getTableData() || [];
            tableData.push(data);
            vm.$refs['dynamic_' + item.code][0].setTableData(tableData);
            vm.$refs['dynamic_' + item.code][0].tableShow = true;
            // 隐藏新增区域
            vm.$refs['dynamic_' + item.code][0].formShow = false;
            // 关闭Table中的编辑区域
            vm.$refs['dynamic_' + item.code][0].getTableComp().closeExpandRow();
          }
        } else {
          vm.$message('校验未通过');
        }
      }, type);
      this.$emit('FormConfirm');
    },
    childFormCancel(item, index, type) {
      // console.log(index);
      if (type === 'form') {
        this.$refs['dynamic_' + item.code][0].formShow = false;
      } else {
        this.$refs['dynamic_' + item.code][0].getTableComp().closeExpandRow();
        var childT = this.$refs['dynamic_' + item.code][0].getTableData();
        childT[this.childEditIndex] = this.childBaseData;
        this.$refs['dynamic_' + item.code][0].setTableData(childT);
      }
      this.$emit('FormCancel');
    },
    loadDynamic(){
        this.$http({
            url: '/ifbp-app-sm-infoset-web/page_layout_child/getByCode',
            method: 'post',
            data: {"busicode":this.busiCode,"code":this.dynamicCode},
            dataType: 'json'
          }).then((res)=>{
            if (res.data.success === true) {
              this.$nextTick(() => {
                this.dynamicPanelData = res.data.data;
              });
            } else {
              this.$message({
                message: res.data.msg,
                type: 'error'
              });
            }            
          }).catch((e) =>{
            this.$message({
              message: '子表信息获取失败',
              type: 'error'
            });
            this.$logger.error(e);
          })
    },
    dynamicRequest() {
      if (!this.parentId) {
        this.$nextTick(() => {
          for (var item in this.$refs) {
            if (item.indexOf('dynamic') > -1) {
              this.$refs[item][0].tableShow = false;
            }
          }
        });
        return;
      }
      var url;
      for (let i = 0; i < this.dynamicPanelData.length; i++) {
        let resData;
        var data = {
        searchParams: {
          searchMap: {
            pk_example: this.parentId
            }
          }
        };
        var code = this.dynamicPanelData[i].code;
        this.$http({
            url: this.dynamicPanelData[i].queryURL,
            method: 'post',
            data: data,
            dataType: 'json'
          })
          .then((res) => {
            if (res.data.success === true) {
              resData = res.data.data.content;
              this.$nextTick(() => {
                if (this.$refs['dynamic_' + code][0]) {
                  this.$refs['dynamic_' + code][0].setTableData(resData);
                } else {
                  this.$refs['dynamic_' + code][0].$set(this.dynamicData[this.dynamicPanelData[i].id], 'uitemplateTableData', resData);
                }
                if (resData.length < 1) {
                  this.$refs['dynamic_' + code][0].tableShow = false;
                } else {
                  this.$refs['dynamic_' + code][0].tableShow = true;
                }
                // this.$refs['dynamic' + i][0].tableShow = resData.length < 1 ? false : true;
              });
            } else {
              this.$message({
                message: res.data.msg,
                type: 'error'
              });
            }
          })
          .catch((e) => {
            this.$message({
              message: '子表信息获取失败',
              type: 'error'
            });
          });
      }

    }

  },
  mounted() {
    this.loadDynamic();
    if (this.defaultCrud === "true")
      this.dynamicRequest();
  },
  created() {
    for (var i = 0; i < this.dynamicPanelData.length; i++) {
      this.dynamicData[this.dynamicPanelData[i].id] = {};
    }

  }

};
</script>

<style>
</style>
