<template>
  <el-container>
    <div id="repositoryInfoProperty" style="height: 500px;width: 100%;overflow: auto;">
      <template v-for="(group, i) in propertyData">
        <div class="property-group"><p style="padding-left: 5px;"><b>{{group.groupPathName}}</b></p></div>
        <div style="margin: 0 50px 0 30px;">
          <template v-for="(item, j) in group.data">
            <!-- 模型名称单独处理 -->
            <template v-if="item.type=='string' && item.id == 'PLNAME'">
              <div class="property-item">
                <label class="property-label">{{item.label}}</label>
                <div class="property-value">
                  <el-input :size=size :disabled="item.readonly" v-model="item.value" @blur="saveRepositoryNameVal(item.value)"></el-input>
                </div>
              </div>
            </template>
            <!--string类型-->
            <template v-if="item.type=='string' && item.id != 'PLNAME'">
              <div class="property-item">
                <label class="property-label">{{item.label}}</label>
                <div class="property-value">
                  <el-input :size=size :disabled="item.readonly" v-model="item.value" @blur="saveStringPropVal(item.id, item.value, item.attrSource)"></el-input>
                </div>
              </div>
            </template>
            <!--textarea类型-->
            <template v-if="item.type=='textarea'">
              <div class="property-item">
                <label class="property-label" style="vertical-align: bottom;">{{item.label}}</label>
                <div class="property-value">
                  <el-input
                    :size=size
                    type="textarea"
                    :rows="2"
                    placeholder="请输入内容"
                    v-model="item.value"
                    :disabled="item.readonly"
                    @blur="saveStringPropVal(item.id, item.value, item.attrSource)"
                  >
                  </el-input>
                </div>
              </div>
            </template>
            <!--number类型-->
            <template v-if="item.type=='number'">
              <div class="property-item">
                <label class="property-label">{{item.label}}</label>
                <div class="property-value">
                  <el-input-number @change="saveNumberPropVal(item.id, item.value, item.attrSource)" :size=size style="width: 100%;cursor: pointer;" controls-position="right" :step="1" v-model="item.value" :disabled="item.readonly"></el-input-number>
                </div>
              </div>
            </template>
            <!--boolean类型-->
            <template v-if="item.type=='boolean'">
              <div class="property-item">
                <label class="property-label">{{item.label}}</label>
                <div class="property-value">
                  <template>
                    <el-select @change="saveSingleSelectVal(item.id, item.value, item.attrSource)" :disabled="item.readonly" clearable :size=size style="width: 100%" v-model="item.value" placeholder="请选择">
                      <el-option
                        v-for="option in item.options"
                        :key="option.value"
                        :label="option.label"
                        :value="option.value">
                      </el-option>
                    </el-select>
                  </template>
                </div>
              </div>
            </template>
            <!--select类型-->
            <template v-if="item.type=='select'">
              <div class="property-item">
                <label class="property-label">{{item.label}}</label>
                <div class="property-value">
                  <template>
                    <el-select @change="saveSingleSelectVal(item.id, item.value, item.attrSource)" :disabled="item.readonly" clearable :size=size style="width: 100%" v-model="item.value" placeholder="请选择">
                      <el-option
                        v-for="option in item.options"
                        :key="option.value"
                        :label="option.label"
                        :value="option.value">
                      </el-option>
                    </el-select>
                  </template>
                </div>
              </div>
            </template>
            <!--select_m类型-->
            <template v-if="item.type=='select_m'">
              <div class="property-item">
                <label class="property-label">{{item.label}}</label>
                <div class="property-value">
                  <template>
                    <el-select @change="saveMultipleSelectVal(item.id, item.value, item.attrSource)"  :disabled="item.readonly" :size=size style="width: 100%" multiple v-model="item.value" placeholder="请选择">
                      <el-option
                        v-for="option in item.options"
                        :key="option.value"
                        :label="option.label"
                        :value="option.value">
                      </el-option>
                    </el-select>
                  </template>
                </div>
              </div>
            </template>
            <!--deptAddress类型（平台部门地址簿）-->
            <template v-if="item.type=='deptAddress'">
              <div class="property-item">
                <label class="property-label">{{item.label}}</label>
                <div class="property-value">
                  <el-input :size=size :disabled="item.readonly" readonly @click.native="choiceBpmOrgAddressComponent(group.groupPath, item.type, item.id, item.readonly)" v-model="item.value"></el-input>
                </div>
              </div>
            </template>
            <!--userAddress类型（平台人员地址簿）-->
            <template v-if="item.type=='userAddress'">
              <div class="property-item">
                <label class="property-label">{{item.label}}</label>
                <div class="property-value">
                  <el-input :size=size :disabled="item.readonly" readonly @click.native="choiceBpmOrgAddressComponent(group.groupPath,item.type, item.id,  item.readonly)" v-model="item.value"></el-input>
                </div>
              </div>
            </template>
            <!--relation-org-shape类型（PAL组织形状调用）-->
            <template v-if="item.type=='relationOrg'">
              <div class="property-item">
                <label class="property-label">{{item.label}}</label>
                <div class="property-value">
                  <el-input :size=size :disabled="item.readonly" readonly v-model="item.value"></el-input>
                </div>
              </div>
            </template>
            <!--awsorg类型-->
            <template v-if="item.type=='awsorg'">
              <div class="property-item">
                <label class="property-label">{{item.label}}</label>
                <div class="property-value">
                  <el-input :size=size :disabled="item.readonly" readonly @click.native="choiceAwsOrgComponent(item.ref, item.type, item.id, item.label, item.readonly)" v-model="item.value"></el-input>
                </div>
              </div>
            </template>
            <!--relation类型-->
            <template v-if="item.type=='relation'">
              <div class="property-item">
                <label class="property-label">{{item.label}}</label>
                <div class="property-value">
                  <el-input :size=size :disabled="item.readonly" readonly @click.native="choiceRelationComponent(item.ref, item.type, item.id, item.label, item.readonly, item.fileIds, item.shapeIds)" v-model="item.value"></el-input>
                </div>
              </div>
            </template>
            <!--   link类型   -->
            <template v-if="item.type=='link' && item.id != 'PLNAME'">
              <div class="property-item">
                <label class="property-label">{{item.label}}</label>
                <div class="property-value">
                  <el-input :size=size :disabled="item.readonly" v-model="item.value" @blur="saveStringPropVal(item.id, item.value, item.attrSource)"></el-input>
                </div>
              </div>
            </template>
            <!--   DateTimePicker 类型 -->
            <template v-if="item.type=='DateTimePicker'">
              <div class="property-item">
                <label class="property-label">{{item.label}}</label>
                <div class="property-value">
                  <el-date-picker value-format="yyyy-MM-dd HH:mm:ss" style="width: 100%;" type="datetime" placeholder="请选择日期时间"  @blur="saveStringPropVal(item.id, item.value, item.attrSource)" :disabled="item.readonly" v-model="item.value" ></el-date-picker>
                </div>
              </div>
            </template>
            <!--   table 类型 -->
            <template v-if="item.type=='table'">
              <div class="property-item">
                <label class="property-label">{{item.label}}</label>
                <div class="property-value">
                  <el-input :size=size :disabled="item.readonly" v-model="item.value.name">
                    <template slot="suffix">
                      <i style="font-size: 20px;line-height: 36px" class="el-icon-s-grid" @click="openTableDialog(item.id,item.value,item.attrSource)"></i>
                    </template>
                  </el-input>
                </div>
              </div>
            </template>
          </template>
        </div>
      </template>
    </div>
    <BPMOrgAddress
      ref="palAwsOrgAddress"
      :visible.sync="bpmOrgAddress.visible"
      :addressType="bpmOrgAddress.addressType"
      v-on:cancel="bpmOrgAddress.visible = false"
      v-on:getResult="saveBpmOrgAddressResult"
      multiple
      :title="title"
      :multiple="bpmOrgAddress.multiple"
     />
    <pal-relation-address
          ref="palRelationAddress"
          :visible.sync="palRelationAddressVisible"
          v-on:cancel="palRelationAddressVisible = false"
          v-on:getResult="saveRelationResult"
          :title="title"
          :selectFileId="relation.selectFileId"
          :selectShapeId="relation.selectShapeId"
          :relationType="relation.relationType"
          :categorys="relation.category"
          :methods="relation.method"
          :wsId="relation.wsId"
          :teamId="relation.teamId"
          :multiple = relation.multiple
    />
    <el-container>
      <el-dialog
          id="tableDialog"
          width="500px"
          :visible.sync="tableDialogVisible"
          v-if="tableDialogVisible"
          :modal-append-to-body=true
          :close-on-click-modal=false
          :append-to-body=true
          :show-close=false
          destroy-on-close
      >
        <template slot="title">
          <el-tooltip placement="top-start">
            <div slot="content">{{ dialogTableNewValue.name }}</div>
            <el-input class="titleInput" v-model="dialogTableNewValue.name"/>
          </el-tooltip>
        </template>
        <div style="height: 300px;overflow: auto;">
          <table class="table">
            <tr>
              <td style="width: 25%">
                <el-tooltip placement="top-start">
                  <div slot="content">{{ dialogTableNewValue.table[0].name }}</div>
                  <el-input class="headInput" v-model="dialogTableNewValue.table[0].name" size="mini"/>
                </el-tooltip>
              </td>
              <td style="width: 55%">
                <el-tooltip placement="top-start">
                  <div slot="content">{{ dialogTableNewValue.table[0].name }}</div>
                  <el-input class="headInput" v-model="dialogTableNewValue.table[0].desc" size="mini"/>
                </el-tooltip>
              </td>
              <td><span style="font-size: 14px;color: #909399;font-weight: bold;font-family: PingFangSC-Light;">操作</span></td>
            </tr>
            <tr v-for="item in dialogTableNewValue.table.slice(1)">
              <td>
                <el-tooltip placement="top-start">
                  <div slot="content">{{ item.name }}</div>
                  <el-input class="contentInput" v-model="item.name" size="mini"/>
                </el-tooltip>
              </td>
              <td>
                <el-tooltip placement="top-start">
                  <div slot="content">{{ item.desc }}</div>
                  <el-input class="contentInput" v-model="item.desc" size="mini"/>
                </el-tooltip>
              </td>
              <td><span style="color: red;text-decoration: underline" @click="deleteTableTr(item.id)">删除</span></td>
            </tr>
          </table>
        </div>
        <awsui-button style="margin-top: 10px;" class="button-general-color" type="primary" @click="addNewTr">新增</awsui-button>
        <span slot="footer" class="dialog-footer">
        <awsui-button class="button-general-color" type="primary" @click="confirmTableDialog()">确定</awsui-button>
        <awsui-button @click="cancelTableDialog">取消</awsui-button>
      </span>
      </el-dialog>
    </el-container>
  </el-container>
</template>

<script>
  import BPMOrgAddress from  "@/components/common/BPMOrgAddress/index.js";// pal平台组织架构地址簿，调用平台部门人员角色
  import PalRelationAddress from  "@/components/common/PalRelationAddress/index.js";
  import awsuiAxios from "../../awsuiAxios";
  // pal关联关系地址簿
    export default {
      name: "RepositoryInfoProperty",
      components: {BPMOrgAddress, PalRelationAddress},
      props: {
        id: {
          type: String,
          default: ''
        },
        versionId: {
          type: String,
          default: ''
        },
        repositoryRefresh: {
          type: Function,
          default: null
        }
      },
      data() {
        return {
          bpmOrgAddress: {
            visible: false,
            addressType: "user",
            multiple: false
          },
          palRelationAddressVisible: false,
          title: '',
          relation: {
            selectFileId: '',
            selectShapeId: '',
            relationType: 'shape',
            category: '',
            method: '',
            wsId: this.$store.getters.getWsIdFn,
            teamId: this.$store.getters.getTeamIdFn,
            multiple: false
          },
          propertyData: [
            {
              groupPath: 'basic',
              groupPathName: '基本属性',
              data: []
            }
          ],
          size: 'medium',
          currPropertyId: '',
          currPropertyType: '',
          currGroup: '',
          currCategory: '',
          currMethod: '',
          currRelationType: '',
          currPropSource: '',
          tableDialogVisible: false,
          dialogTableId: '',
          dialogTableOldValue: {},    // 弹框表格值副本  刚打开dialog的值    点击取消会把该值保存到数据库
          dialogTableNewValue: {      // 弹框表格值  对表格的更新操作在此进行   点击确定会把该值保存到数据库
            name: '',
            table: [
                { id: '',name: '',desc: '' },
            ]
          },
          dialogTableAttrSource: undefined
        };
      },
      created() {
        this.initData();
      },
      methods: {
        initData() {
          const that = this;
          const data = {
            url:'jd',
            data:{
              cmd: 'com.actionsoft.apps.coe.pal_processlevel_property_data_query',
              id: that.id,
              wsId: that.$store.getters.getWsIdFn,
              teamId: that.$store.getters.getTeamIdFn
            }
          };
          // 查询数据
          awsuiAxios.post(data).then(function (ro) {
            if (ro.result == 'ok') {
              let propertyData = ro.data.propertyData;
              // table 类型value默认为空对象   初始赋值
              propertyData.forEach(item => {
                item.data.forEach(item1 => {
                  if (item1.type == 'table' && JSON.stringify(item1.value) == '{}') {
                    item1.value = {
                      name: '未命名表单',
                      table: [
                        { id: 'table_head',name: '命名',desc: '描述'}
                      ]
                    }
                  }
                })
              })
              that.propertyData = propertyData;
            } else {
              that.$message.error(ro.msg);
            }
          }).catch(error=>{
            console.log(error);
          })
        },
        openTableDialog(id,value,attrSource) {
          this.tableDialogVisible = true
          this.dialogTableId = id
          this.dialogTableOldValue = JSON.parse(JSON.stringify(value))
          this.dialogTableNewValue = value
          this.dialogTableAttrSource = attrSource
        },
        addNewTr() {
          this.dialogTableNewValue.table.push({
            id: Date.now().toString(36),name: '',desc: ''
          })
        },
        deleteTableTr(id) {
          let index = this.dialogTableNewValue.table.findIndex(item => {
            return item.id == id
          })
          this.dialogTableNewValue.table.splice(index,1)
        },
        confirmTableDialog() {
          if (this.dialogTableAttrSource && this.dialogTableAttrSource == 'default') {
            this.saveDefaultpropToDb(this.dialogTableId, JSON.stringify(this.dialogTableNewValue));
          } else {
            this.saveCustomPropToDb(this.dialogTableId, JSON.stringify(this.dialogTableNewValue));
          }
          this.tableDialogVisible = false
        },
        cancelTableDialog() {
          if (this.dialogTableAttrSource && this.dialogTableAttrSource == 'default') {
            this.saveDefaultpropToDb(this.dialogTableId, JSON.stringify(this.dialogTableOldValue));
          } else {
            this.saveCustomPropToDb(this.dialogTableId, JSON.stringify(this.dialogTableOldValue));
          }
          this.tableDialogVisible = false
        },
        saveStringPropVal(attrId, value, attrSource) {// 保存文本属性内容
          if (value == undefined) {
            value = '';
          }
          if (attrSource && attrSource == 'default') {
            this.saveDefaultpropToDb(attrId, value);
          } else {
            this.saveCustomPropToDb(attrId, value);
          }
        },
        saveNumberPropVal(attrId, value, attrSource) {// 保存数字类型内容
          if (value == undefined) {
            value = '';
          }
          if (attrSource && attrSource == 'default') {
            this.saveDefaultpropToDb(attrId, value);
          } else {
            this.saveCustomPropToDb(attrId, value);
          }
        },
        saveSingleSelectVal(attrId, value, attrSource) {// 保存boolean，单选类型内容
          if (value == undefined) {
            value = '';
          }
          if (attrSource && attrSource == 'default') {
            this.saveDefaultpropToDb(attrId, value);
          } else {
            this.saveCustomPropToDb(attrId, value);
          }
        },
        saveMultipleSelectVal(attrId, value, attrSource) {// 保存多选类型内容
          value = value.join(',');
          if (attrSource && attrSource == 'default') {
            this.saveDefaultpropToDb(attrId, value);
          } else {
            this.saveCustomPropToDb(attrId, value);
          }
        },
        saveDefaultpropToDb(attrId, value) {// 保存固定属性至数据库
          const that = this;
          const data = {
            url:'jd',
            data:{
              cmd: 'com.actionsoft.apps.coe.pal_processlevel_default_attr_content_save',
              uuid: that.id,
              josnKey: attrId,
              josnContent: value
            }
          };
          // 查询数据
          awsuiAxios.post(data).then(function (ro) {
            if (ro.result == 'ok') {
              // that.$message({
              //   message: '保存成功',
              //   type: 'success'
              // });
              that.initData();
            } else {
              that.$message.error(ro.msg);
            }
          }).catch(error=>{
            console.log(error);
          })
        },
        saveCustomPropToDb(attrId, value) {// 保存属性内容至数据库
          const that = this;
          const data = {
            url:'jd',
            data:{
              cmd: 'com.actionsoft.apps.coe.pal_processlevel_more_attr_content_save',
              uuid: that.id,
              josnKey: attrId,
              josnContent: value
            }
          };
          // 查询数据
          awsuiAxios.post(data).then(function (ro) {
            if (ro.result == 'ok') {
              // that.$message({
              //   message: '保存成功',
              //   type: 'success'
              // });
              that.initData();
            } else {
              that.$message.error(ro.msg);
            }
          }).catch(error=>{
            console.log(error);
          })
        },
        choiceRelationComponent(ref, type, id, label, readonly, fileIds, shapeIds) {// PAL模型/形状选择组件
          if (!readonly) {
            this.currPropertyId = id;
            this.currPropertyType = type;
            const method = ref.method;
            if (method.indexOf('.') > -1) {
              this.currCategory = method.substring(0, method.indexOf('.'));
              this.currMethod = method;
            } else {
              this.currCategory = method;
              this.currMethod = '';
            }
            this.currPropSource = 'custom';// 自定义扩展属性
            this.relation.multiple = true;
            this.currRelationType = ref.type;
            this.title = label;
            this.relation.selectFileId = fileIds;// 已选中文件id
            this.relation.selectShapeId = shapeIds;// 已选中形状id
            this.relation.relationType = ref.type;
            this.relation.category = this.currCategory;
            this.relation.method = this.currMethod;
            this.relation.multiple = ref.multiple;
            this.palRelationAddressVisible = true;
          }
        },
        choiceBpmOrgAddressComponent(group, type, id, readonly) {// 平台地址簿组件（责任部门责任人）
          if (!readonly) {
            this.currPropertyId = id;
            this.currPropertyType = type;
            if (type == "deptAddress") {// 责任部门
              this.title = '责任部门';
              this.bpmOrgAddress.addressType = 'dept';
              this.bpmOrgAddress.visible = true;
            } else if (type == "userAddress") {// 责任人
              this.title = '责任人';
              this.bpmOrgAddress.addressType = 'user';
              this.bpmOrgAddress.visible = true;
            }
          }
        },
        choiceAwsOrgComponent(ref, type, id, label, readonly) {// AWS平台部门/人员/角色组件
          if (!readonly) {
            this.currPropertyId = id;
            this.currPropertyType = type;
            this.title = label;
            this.bpmOrgAddress.addressType = ref.scope.join(',');
            this.bpmOrgAddress.multiple = ref.multiple;
            this.bpmOrgAddress.visible = true;
          }
        },
        saveBpmOrgAddressResult(data) {
          this.bpmOrgAddress.visible = false;
          // 保存
          const params = [];
          for (let i = 0; i < data.length; i++) {
            params.push({name: data[i].name, id: data[i].id, type: data[i].type})
          }
          this.saveCustomPropToDb(this.currPropertyId, JSON.stringify(params));
        },
        // 调用关联组件保存函数
        saveRelationResult(data) {
          // 返回结果
          const jsonContent = {
            fileId : this.id,
            shapeId : "",
            shapeText : "",
            attrId : this.currPropertyId,
            relationFileId : '',
            relationShapeId : '',
            relationShapeText : '',
            groupPath : this.currGroup
          }
          const relationType = this.currRelationType;
          if (relationType == 'file') {
            const fileIds = [];
            for (let i = 0; i < data.length; i++) {
              fileIds.push(data[i].versionId);
            }
            jsonContent.relationFileId = fileIds.join(",");
          }
          else if (relationType == 'shapeAndFile') {
            let fileIds = [];
            let shapeIds = [];
            let shapeNames = [];
            for (let i = 0; i < data.length; i++) {
              if (data[i].children.length == 0) {    // 文件
                fileIds.push(data[i].versionId);
                shapeNames.push(data[i].name);
                shapeIds.push(' ')  // push 空格
              }else {  // 形状
                for (let j = 0; j < data[i].children.length; j++) {
                  fileIds.push(data[i].versionId)
                  shapeIds.push(data[i].children[j].shapeId)
                  shapeNames.push(data[i].children[j].name)
                }
              }
            }
            jsonContent.relationFileId = fileIds.join(",");
            jsonContent.relationShapeId = shapeIds.join(",");
            jsonContent.relationShapeText = shapeNames.join(",");
          }
          else {// 形状
            const fileIds = [];
            const shapeIds = [];
            const shapeNames = [];
            for (let i = 0; i < data.length; i++) {
              const currFile = data[i];
              const children = currFile.children;
              for (let j = 0; j < children.length; j++) {
                const currShape = children[j];
                fileIds.push(currFile.id);
                shapeIds.push(currShape.shapeId);
                shapeNames.push(currShape.name);
              }
            }
            jsonContent.relationFileId = fileIds.join(",");
            jsonContent.relationShapeId = shapeIds.join(",");
            jsonContent.relationShapeText = shapeNames.join(",");
          }
          if (this.currPropSource == 'default') {// 固定属性，责任人、责任部门
            this.saveDefaultpropToDb(this.currPropertyId, JSON.stringify(jsonContent));
          } else {// 自定义属性
            this.saveCustomPropToDb(this.currPropertyId, JSON.stringify(jsonContent));
          }
          this.palRelationAddressVisible = false;
        },
        saveRepositoryNameVal(name) {// 模型名称保存
          const that = this;
          const data = {
            url:'jd',
            data:{
              cmd: 'com.actionsoft.apps.coe.pal_pl_repository_designer_updatetitle',
              uuid: that.id,
              title: name,
            }
          };
          // 查询数据
          awsuiAxios.post(data).then(function (ro) {
            if (ro.result == 'ok') {
              that.initData();
              // 父页面左侧树和右侧
              if (that.repositoryRefresh && that.id) {
                that.repositoryRefresh(that.id);
              }
            } else {
              that.$message.error(ro.msg);
            }
          }).catch(error=>{
            console.log(error);
          })
        }
      }
    }
</script>

<style scoped>
  .property-group {
    height: 25px;
    line-height: 25px;
    vertical-align: center;
    margin: 30px 30px 15px 20px;
    border-left: 3px solid #4E7FF9;
  }
  .property-item {
    margin-top: 15px;
  }
  .property-label {
    width: 11%;
    display: inline-block;
    text-align: right;
    padding-right: 12px;
    vertical-align: middle;
  }
  .property-value {
    display: inline-block;
    width: 85%;
  }
  #tableDialog  >>> .el-dialog__body {
    padding: 10px 20px;
    color: #606266;
    font-size: 14px;
    word-break: break-all;
    cursor: pointer;
  }
  #tableDialog  >>> .el-input__inner {
    border: none;
    padding: 0;
    text-overflow: ellipsis;
    cursor: pointer;
  }
  .table {
    width: 100%;
  }
  .table tr td{
    border-bottom: 1px solid #f2f2f2;
    padding:0 5px;
    white-space: normal;
  }
  .titleInput  >>> .el-input__inner {
    height: 25px;
    width: 100%;
    padding: 0;
    border: none;
    font-size: 18px;
    font-family: PingFangSC-Light;
  }
  .headInput >>> .el-input__inner {
    font-size: 14px;
    color: #909399;
    font-weight: bold;
    font-family: PingFangSC-Light;
  }
  .contentInput >>> .el-input__inner {
    font-size: 14px;
    color: #606266;
    font-family: PingFangSC-Light;
    background: transparent;
  }
</style>
