<template lang="html">
<div class="scene-manage-detail">
  <div class="scene-detail-opro">
    <el-button type="primary" @click="sceneDetailSave" v-if="sceneDetailEdit">保存</el-button>
    <el-button @click="sceneCancal" v-if="sceneDetailEdit">取消</el-button>
    <el-button type="primary" @click="changeEdit" v-if="!sceneDetailEdit"><i class="el-icon-edit"></i></el-button>
    <div class="fr">
      <!-- <el-button type="primary" @click="goBack">返回</el-button> -->
    </div>
  </div>
  <div class="scene-detail-form">
    <ifbp-template ref="sceneManageForm"
              tplId="baseTemplate"
              :pkTemp="sceneDetailPk"
              show-type="form"
              :tplData="sceneDetailData"
              :editable="sceneDetailEdit"
              :tpl-reset-fun="sceneFormResetFun"
              @after-create="templateAfterCreate">
    </ifbp-template>
  </div>
  <div class="scene-prompt">
    请为模型视图关联客户类型实体的属性
  </div>
  <div class="scenedetail-info">
    <div class="scenedetail-sets" v-for="(item,index1) in sceneManageSetHeader">
      <div class="scenedetail-set-header">
        <span>{{item.displayname}}</span>
        <span @click="sceneExpand(item)">
          <i class="el-icon-arrow-down" v-if="(item.primary ? !flag[item.id]:flag[item.id])"></i>
          <i class="el-icon-arrow-up" v-if="(item.primary ? flag[item.id]:!flag[item.id])"></i>
        </span>
        <!-- <span v-else>
          <i class="el-icon-arrow-down" v-if="(item.primary ? !flag[item.id]:flag[item.id])"></i>
          <i class="el-icon-arrow-up" v-if="(item.primary ? flag[item.id]:!flag[item.id])"></i>
        </span> -->
      </div>
      <div class="sceneDetailSetChecked" v-if="(item.primary ? !flag[item.id]:flag[item.id])">
        <el-checkbox class="sceneAllCheck" :indeterminate="isIndeterminate[item.id]" v-model="checkAll[item.id]" @change="handleCheckAllChange(index1,item,$event)" :disabled="!sceneDetailEdit">全选</el-checkbox>
        <div style="margin: 0;"></div>
        <el-checkbox-group v-model="checkedSceneItem[item.id]"  style="overflow:hidden">
           <div class="sceneCheck" v-for="(item1,index) in item.propertyList" :key="item1.id" @click=""  v-if="!item1.key">
             <span class="sceneCheck-title">{{item1.displayname}}</span>
            <el-checkbox :label="item1.id" class="checkedItems" @change="function(ev,value){handleCheckedSceneChange(ev,value,item1, item,index,index1)}" :disabled="!sceneDetailEdit" :key="item.id">{{""}}</el-checkbox>
          </div>
        </el-checkbox-group>
      </div>
    </div>
  </div>

</div>
</template>

<script>
// import Json1 from './1.json';
export default {
  data() {
    // debugger;
    var self = this;
    var id = this.$root.$router.currentRoute.params.id;
    var code = this.$root.$router.currentRoute.params.code;
    var isCreate = this.$route.fullPath.indexOf('add') > -1;
    return {
      sceneDetailPk: 'c31006ed-b410-46ca-954c-46234427a34d',
      sceneDetailData: {
        PubSceneEntity: {},
        sceneCode11:false,
        rules: {
          code: [{
            required: true,
            message: "编码不能为空",
            trigger: "blur"
          }],
          name: [{
            required: true,
            message: "名称不能为空",
            trigger: "blur"
          }]
        }
      },
      sceneDetailEdit: isCreate,
      checkAll: {}, //全选的
      checkedSceneItem: {}, //勾选的项
      checkedSceneItemOrg: {},
      sceneDetail: {
        // "pubScene":{
        //   "name":"",
        //   "code":"",
        // },
      }, //大的json
      originalSceneDetail: {},
      sceneAllItem: {},
      isIndeterminate: {},
      sceneDetailId: id,
      sceneDetailCode: code,
      sceneCreate: isCreate,
      sceneManageSetHeader: [],
      sceneExpandHeader: {},
      flag: {},
      sceneFormResetFun: function($node) {
        var $sceneCode = this.getNodeById($node, "usikpndfaie");
        $sceneCode.attr(':disabled', "sceneCode11");
        return $node[0].outerHTML;
      },
      // checkedCountjy:{}
    };
  },
  methods: {
    sceneDetailSave() {
      var vm = this;
      if (!this.sceneDetailEdit) {
        return;
      }
      // for (var i = 0; i < vm.sceneDetail.cmpDto.entityList.length; i++) {
      //   if (vm.checkedSceneItem[vm.sceneDetail.cmpDto.entityList[i].id].length <= 0) {
      //     vm.$message({
      //       message: vm.sceneDetail.cmpDto.entityList[i].displayname + '必须勾选一项',
      //       type: 'error'
      //     });
      //     return;
      //   }
      // }
      for (var i = 0; i < vm.sceneDetail.cmpDto.entityList.length; i++) {
        if(vm.sceneDetail.cmpDto.entityList[i].primary === true ){
          if (vm.checkedSceneItem[vm.sceneDetail.cmpDto.entityList[i].id].length <= 0) {
              vm.$message({
                message: vm.sceneDetail.cmpDto.entityList[i].displayname + '必须勾选一项',
                type: 'error'
              });
              return;
            }
        }
      }
      this.$refs.sceneManageForm.getFormComp().validate(valid => {
        if (valid) {
          var url = '/ifbp-app-sm-infoset-web/scenedetail/saveSceneDetailSetting'
          var data = this.sceneDetail;
          var pub = this.$refs.sceneManageForm.comp.PubSceneEntity;
          this.sceneDetail.pubScene = pub;
          this.$http({
            url: url,
            method: 'post',
            data: data,
            dataType: 'json',
          }).then((res) => {
            if (res) {
              if (res.data.success) {
                this.$message({
                  message: '保存成功'
                });
                this.sceneDetailEdit = false;
              } else {
                this.$message({
                  message: res.data.error.errorMessage,
                  type: 'error'
                });
              }
            }
          }).catch(() => {
            this.$message({
              message: '保存失败',
              type: 'error'
            });
          });
        }
      });
    },
    sceneCancal() {
      if (!this.sceneDetailEdit || this.sceneCreate) {
        return;
      } else {
        this.sceneDetail = JSON.parse(JSON.stringify(this.originalSceneDetail));
        this.$nextTick(() => {
          if(this.$refs['sceneManageForm']){
            this.$refs['sceneManageForm'].setData(
              "PubSceneEntity",
              // JSON.parse(JSON.stringify(originalValue))
              this.sceneDetail.pubScene
            );
          } else {
            this.$set(this.sceneDetailData, 'PubSceneEntity', this.sceneDetail.pubScene);
          }
        })
        this.checkedSceneItem = JSON.parse(JSON.stringify(this.checkedSceneItemOrg));
        this.sceneDetailEdit = false;
      }

    },
    sceneExpand(item) {
      this.$set(this.flag, item.id, !this.flag[item.id]);
    },
    goBack() {
      this.$router.push('/sceneManage');
    },
    changeEdit() {
      this.sceneDetailEdit = !this.sceneDetailEdit;
    },
    handleCheckAllChange(index1,item, event) {
      // debugger;
      var checked =event.target.checked;
      for (var i = 0; i < this.sceneDetail.cmpDto.entityList[index1].propertyList.length; i++) {
        this.sceneDetail.cmpDto.entityList[index1].propertyList[i].select=checked;
      }
      this.sceneDetail.cmpDto.entityList[index1].select = checked;
      this.$set(this.checkedSceneItem, item.id, event.target.checked ? this.sceneAllItem[item.id] : []);
      this.$set(this.isIndeterminate, item.id, false);

    },
    handleCheckedSceneChange(ev, value, item1, item, index, index1) {
      var checked = ev.target.checked;
      this.sceneDetail.cmpDto.entityList[index1].propertyList[index].select = checked;

      let checkedCount = this.checkedSceneItem[item.id].length;
      // this.checkedCountjy = checkedCount;
      //设置主表的select
      if (checkedCount > 0) {
        this.sceneDetail.cmpDto.entityList[index1].select = true;
      } else {
        this.sceneDetail.cmpDto.entityList[index1].select = false;
      }
      //设置外层的主键的select属性
      for (var j = 0; j < this.sceneDetail.cmpDto.entityList[index1].propertyList.length; j++) {
        if (this.sceneDetail.cmpDto.entityList[index1].propertyList[j].key === true) {
          if (checkedCount > 0) {
            this.sceneDetail.cmpDto.entityList[index1].propertyList[j].select = true;
          } else {
            this.sceneDetail.cmpDto.entityList[index1].propertyList[j].select = false;
          }
        }

      }
      // debugger;
      this.$set(this.checkAll, item.id, checkedCount === this.sceneAllItem[item.id].length);
      this.$set(this.isIndeterminate, item.id, checkedCount > 0 && checkedCount < this.sceneAllItem[item.id].length);
    },
    sceneDetailRequest() {
      var url = "/ifbp-app-sm-infoset-web/scene/queryPubSceneDetailSetting";
      var data = this.sceneDetailId;
      if (this.sceneCreate) {
        url = "/ifbp-app-sm-infoset-web/scene/toCreate";
        data = this.sceneDetailCode;
      }
      this.$http({
          url: url,
          method: "post",
          headers: {
            "Content-Type": "application/json"
          },
          data: data
        }).then(res => {
          if (res.data.success === true) {
            this.sceneDetail = res.data.data;
            this.originalSceneDetail = JSON.parse(JSON.stringify(this.sceneDetail));
            this.sceneManageSetHeader = res.data.data.cmpDto.entityList;
            for (var i = 0; i < res.data.data.cmpDto.entityList.length; i++) {
              var scenesItem = [];
              var checkedScene = [];
              // debugger;
              for (var j = 0; j < res.data.data.cmpDto.entityList[i].propertyList.length; j++) {
                if (res.data.data.cmpDto.entityList[i].propertyList[j].key !== true) {
                  scenesItem.push(res.data.data.cmpDto.entityList[i].propertyList[j].id);
                  if (res.data.data.cmpDto.entityList[i].propertyList[j].select) {
                    checkedScene.push(res.data.data.cmpDto.entityList[i].propertyList[j].id);
                    // scenesItem.push(res.data.data.cmpDto.entityList[i].propertyList[j].id);
                  }
                }

              }
              this.$set(this.sceneAllItem, res.data.data.cmpDto.entityList[i].id, scenesItem);
              this.$set(this.checkedSceneItem, res.data.data.cmpDto.entityList[i].id, checkedScene);
              this.$set(this.checkAll, res.data.data.cmpDto.entityList[i].id, checkedScene.length === scenesItem.length);
              this.$set(this.isIndeterminate, res.data.data.cmpDto.entityList[i].id, checkedScene.length > 0 && checkedScene.length < scenesItem.length);
            }
            this.checkedSceneItemOrg = JSON.parse(JSON.stringify(this.checkedSceneItem));
            var originalValue = res.data.data.pubScene;
            this.$nextTick(() => {
              var sceneRef = this.$refs['sceneManageForm'];
              if(sceneRef) {
                this.$refs['sceneManageForm'].setData(
                  "PubSceneEntity",
                  // JSON.parse(JSON.stringify(originalValue))
                  this.sceneDetail.pubScene
                );
              }
            })

          } else {
            this.$message({
              message: res.data.msg,
              type: "error"
            });
          }
        }).catch(e => {
          this.$message({
            message: "模型视图信息详情获取失败",
            type: "error"
          });
        });
    },
    templateAfterCreate(UIComp){
      if(this.sceneDetailId){
        UIComp.setData('sceneCode11',true);
      }
    }
  },
  created() {

  },
  mounted() {
    this.sceneDetailRequest();
  }
}
</script>

<style>
.scene-manage-detail {
  padding: 20px 30px;
}

.scene-detail-opro {
  background-color: #fff;
  height: 56px;
  line-height: 56px;
  padding: 0 5px;
  margin: 5px 0;
}

.scene-detail-form {
  background: #fff;
  margin: 10px 0 0 0;
  padding: 10px 0;
}

.scene-detail-form .el-button {
  margin: 5px 0 0 5px;
}

.scenedetail-set-header {
  font-size: 16px;
  margin: 10px 5px;
}

.sceneDetailSetChecked {
  background: #fff;
}

.sceneAllCheck {
  margin: 10px 0 0 5px;
}

.sceneCheck {
  width: 100px;
  height: 50px;
  float: left;
  margin: 10px 10px 10px 5px;
  line-height: 50px;
  background-color: rgb(126, 203, 250);
  position: relative;
  text-align: center;
}

.sceneCheck .sceneCheck-title {
  display: inline-block;
  width: 100px;
  line-height: 50px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  font-size: 14px;
}

.scene-manage-detail .el-checkbox.checkedItems {
  height: 20px;
  width: 18px;
  line-height: 20px;
  position: absolute !important;
  right: 2px;
  bottom: 1px;
}

.scene-prompt {
  background: #fff;
  height: 36px;
  line-height: 36px;
  font-size: 16px;
  color: #949494;
  margin: 10px 0 5px 0;
  padding-left: 5px;
}
</style>
