<template>
  <div class="right-board">
    <el-tabs v-if="activeId" v-model="currentTab" class="center-tabs" :stretch="true">
      <el-tab-pane label="组件属性" name="field" />
      <!--      <el-tab-pane v-if="activeData?.event?.isEvent" label="事件设置" name="event" />-->
      <el-tab-pane v-if="isRelation && !activeData.__config__.relationTable && !activeData.__config__.isSubTable" label="关联设置" name="relation" />
    </el-tabs>
    <el-tabs v-else v-model="currentTab" class="center-tabs" :stretch="true">
      <el-tab-pane label="逻辑属性" name="logic" />
      <el-tab-pane label="表单属性" name="form" />
    </el-tabs>
    <div class="field-box">
      <el-scrollbar class="right-scrollbar">
        <!-- 组件属性 -->
        <el-form v-show="currentTab === 'field' && showField" size="small" label-width="90px" labelPosition="left">
          <template v-if="activeData.__config__">
            <el-form-item v-if="allComponents.find((item) => item.__config__.jnpfKey === activeData.__config__.jnpfKey)" label="控件属性">
              <el-select filterable :value="activeData.__config__.jnpfKey" placeholder="请选择控件属性" clearable @change="changeType($event, activeData.__config__.label)">
                <el-option v-for="item in allComponents" :key="item.__config__.jnpfKey" :value="item.__config__.jnpfKey" :label="item.__config__.label"> </el-option>
              </el-select>
            </el-form-item>
            <template v-if="$store.getters.hasTable">
              <template v-if="activeData.__config__.jnpfKey === 'table'">
                <!--                <el-form-item v-if="activeData.__vModel__!==undefined" label="控件字段">-->
                <!--                  <el-input v-model="activeData.__vModel__" placeholder="请输入控件字段（v-model）"-->
                <!--                    disabled />-->
                <!--                </el-form-item>-->
              </template>
              <template v-else-if="activeData.__config__.jnpfKey === 'serialNumber'">
                <el-form-item v-if="activeData.__vModel__ !== undefined">
                  <template slot="label">
                    <span>控件字段</span>
                    <el-tooltip style="cursor: pointer" effect="dark" :content="'流水号控件仅支持选择String类型字段'" placement="top">
                      <i class="el-icon-question" />
                    </el-tooltip>
                  </template>
                  <el-select v-model="activeData.__vModel__" placeholder="请选择控件字段（v-model）" clearable @change="fieldChange" filterable>
                    <!--                    <el-option-group v-for="group in formItemList" :key="group.id"-->
                    <!--                                     :label="group.tableName">-->

                    <el-option
                      v-for="item in formItemList"
                      :key="item.id"
                      :value="item.id"
                      :disabled="getDisabledStrSelect(item.id, item)"
                      :label="item.columnTitle ? item.columnTitle + ' ' + item.columnName : item.columnComment + ' ' + item.columnName"
                    >
                    </el-option>
                    <!--                    </el-option-group>-->
                  </el-select>
                </el-form-item>
              </template>
              <template v-else>
                <template v-if="!activeData.__config__.isSubTable">
                  <el-form-item v-if="activeData.__vModel__ !== undefined" label="控件字段">
                    <el-select v-model="activeData.__vModel__" placeholder="请选择控件字段" clearable @change="fieldChange" filterable :disabled="activeData.isText">
                      <!--                                      <el-option-group v-for="group in formItemList" :key="group.id"-->
                      <!--                                        :label="group.tableName">-->

                      <el-option
                        v-for="item in formItemList"
                        :key="item.id"
                        :value="item.id"
                        :disabled="getDisabledSelect(item.id)"
                        :label="item.columnTitle ? item.columnTitle + ' ' + item.columnName : item.columnComment + ' ' + item.columnName"
                      >
                      </el-option>
                      <!--                                      </el-option-group>-->
                    </el-select>
                  </el-form-item>
                </template>
                <template v-if="activeData.__config__.isSubTable">
                  <el-form-item v-if="activeData.__vModel__ !== undefined" label="控件字段">
                    <el-select v-model="activeData.__vModel__" placeholder="请选择控件字段" clearable @change="fieldChange" filterable :disabled="activeData.isText">
                      <el-option
                        v-for="item in getSubTalebFiled(activeData.__config__.relationTable)"
                        :key="item.id"
                        :value="item.id"
                        :disabled="getChildrenDisabledSelect(activeData.__config__.relationTable, item.id)"
                        :label="item.columnTitle ? item.columnTitle + ' ' + item.columnName : item.columnComment + ' ' + item.columnName"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </template>
            </template>
            <el-form-item label="布局方式">
              <el-switch v-model="activeData.__config__.typeSpan" active-text="自定义" inactive-text="全局"></el-switch>
            </el-form-item>
            <!--            <template v-else>-->
            <!--              <el-form-item v-if="activeData.__vModel__!==undefined" label="控件字段">-->
            <!--                <el-input v-model="activeData.__vModel__" placeholder="请输入控件字段（v-model）" disabled />-->
            <!--              </el-form-item>-->
            <!--            </template>-->
            <JNPFComInput v-if="activeData.__config__.jnpfKey === 'comInput'" :active-data="activeData" :dbLinkId="dbLinkId" :draw-list="drawList" />
            <JNPF-textarea v-if="activeData.__config__.jnpfKey === 'textarea'" :active-data="activeData" />
            <JNPFText v-if="activeData.__config__.jnpfKey === 'JNPFText'" :active-data="activeData" :dbLinkId="dbLinkId" :draw-list="drawList" />
            <JNPFNumInput v-if="activeData.__config__.jnpfKey === 'numInput'" :active-data="activeData" :dbLinkId="dbLinkId" :draw-list="drawList" />
            <JNPFAmount v-if="activeData.__config__.jnpfKey === 'JNPFAmount'" :active-data="activeData" />
            <JNPFPsdInput v-if="activeData.__config__.jnpfKey === 'PsdInput'" :active-data="activeData" />
            <JNPFRadio v-if="activeData.__config__.jnpfKey === 'radio'" :active-data="activeData" />
            <JNPFCheckbox v-if="activeData.__config__.jnpfKey === 'checkbox'" :active-data="activeData" />
            <JNPFSelect v-if="activeData.__config__.jnpfKey === 'select'" :draw-list="drawList" :active-data="activeData" />
            <JNPFCascader v-if="activeData.__config__.jnpfKey === 'cascader'" :draw-list="drawList" :active-data="activeData" />
            <JNPFTime v-if="activeData.__config__.jnpfKey === 'time'" :active-data="activeData" />
            <JNPFTimeRange v-if="activeData.__config__.jnpfKey === 'timeRange'" :active-data="activeData" />
            <JNPFDate v-if="activeData.__config__.jnpfKey === 'date'" :active-data="activeData" />
            <JNPFDateRange v-if="activeData.__config__.jnpfKey === 'dateRange'" :active-data="activeData" />
            <JNPFColorPicker v-if="activeData.__config__.jnpfKey === 'colorPicker'" :active-data="activeData" />
            <JNPFRate v-if="activeData.__config__.jnpfKey === 'rate'" :active-data="activeData" />
            <JNPFSwitch v-if="activeData.__config__.jnpfKey === 'switch'" :active-data="activeData" />
            <JNPFSlider v-if="activeData.__config__.jnpfKey === 'slider'" :active-data="activeData" />
            <JNPFDivider v-if="activeData.__config__.jnpfKey === 'divider'" :active-data="activeData" />
            <JNPFUploadFz v-if="activeData.__config__.jnpfKey === 'uploadFz'" :active-data="activeData" />
            <JNPFUploadImg v-if="activeData.__config__.jnpfKey === 'uploadImg'" :active-data="activeData" />
            <JNPFComRight v-if="isCommon" :active-data="activeData" />
            <JNPFAddress v-if="activeData.__config__.jnpfKey === 'address'" :active-data="activeData" />
            <TreeSelect v-if="activeData.__config__.jnpfKey === 'treeSelect'" :active-data="activeData" />
            <GroupTitle v-if="activeData.__config__.jnpfKey === 'groupTitle'" :active-data="activeData" />
            <RelationForm v-if="activeData.__config__.jnpfKey === 'relationForm'" :active-data="activeData" v-on="$listeners" />
            <RelationFormAttr v-if="activeData.__config__.jnpfKey === 'relationFormAttr'" :active-data="activeData" ref="relationFormAttr" />
            <RelationFlow v-if="activeData.__config__.jnpfKey === 'relationFlow'" :active-data="activeData" v-on="$listeners" />
            <RelationFlowAttr v-if="activeData.__config__.jnpfKey === 'relationFlowAttr'" :active-data="activeData" ref="relationFlowAttr" />
            <JNPFCalculate v-if="activeData.__config__.jnpfKey === 'calculate'" :active-data="activeData" ref="calculate" />
            <PopupSelect v-if="activeData.__config__.jnpfKey === 'popupSelect'" :active-data="activeData" />
            <serialNumber v-if="activeData.__config__.jnpfKey === 'serialNumber'" :active-data="activeData" :draw-list="drawList" :columnModelId="columnModelId" />
            <Tab v-if="activeData.__config__.jnpfKey === 'tab'" :active-data="activeData" />
            <Collapse v-if="activeData.__config__.jnpfKey === 'collapse'" :active-data="activeData" />
            <Table v-if="activeData.__config__.jnpfKey === 'table'" :dbtable-list="tableList" :active-data="activeData" :dbSourceId="dbSourceId" :columnModelId="columnModelId" />
            <PlaceholderCom v-if="activeData.__config__.jnpfKey === 'PlaceholderCom'" :active-data="activeData" />
            <template v-if="isSystem">
              <el-form-item label="控件标题">
                <el-input v-model="activeData.__config__.label" placeholder="请输入控件标题" />
              </el-form-item>
              <el-form-item label="控件栅格">
                <el-slider v-model="activeData.__config__.span" :max="24" :min="6" show-stops :step="2" show-tooltip />
              </el-form-item>
              <el-form-item label="标题宽度">
                <el-input-number v-model="activeData.__config__.labelWidth" placeholder="标题宽度" :min="0" :precision="0" controls-position="right" />
              </el-form-item>
              <el-form-item label="是否隐藏" v-if="activeData.__config__.jnpfKey !== 'billRule'">
                <el-switch v-model="activeData.__config__.noShow" @change="activeData.displayNone = activeData.__config__.noShow" />
              </el-form-item>
              <el-form-item label="选择模板" v-if="activeData.__config__.jnpfKey === 'billRule'">
                <BillRule v-model="activeData.__config__.rule" placeholder="选择模板" />
              </el-form-item>
            </template>
            <template v-if="activeData.__config__.jnpfKey === 'card'">
              <el-form-item label="控件栅格" label-width="76px">
                <el-slider v-model="activeData.__config__.span" :max="24" :min="6" show-stops :step="2" show-tooltip />
              </el-form-item>
              <el-form-item label="卡片标题" label-width="76px">
                <el-input v-model="activeData.header" placeholder="请输入卡片标题" />
              </el-form-item>
              <el-form-item label="显示阴影" label-width="76px">
                <el-radio-group v-model="activeData.shadow" size="small">
                  <el-radio-button label="always">一直显示</el-radio-button>
                  <el-radio-button label="hover">移入显示</el-radio-button>
                  <el-radio-button label="never">永不显示</el-radio-button>
                </el-radio-group>
              </el-form-item>
            </template>
            <!-- row 布局 -->
            <template v-if="activeData.__config__.jnpfKey === 'row'">
              <el-form-item v-if="activeData.__config__.componentName !== undefined" label="组件名">
                {{ activeData.__config__.componentName }}
              </el-form-item>
              <el-form-item label="控件栅格">
                <el-slider v-model="activeData.__config__.span" :max="24" :min="6" show-stops :step="2" show-tooltip />
              </el-form-item>
            </template>
            <el-form-item v-if="activeData.__config__.layout === 'rowFormItem' && activeData.gutter !== undefined" label="栅格间隔">
              <el-input-number v-model="activeData.gutter" :min="0" placeholder="栅格间隔" controls-position="right" />
            </el-form-item>
          </template>
          <!--          <template v-if="activeData.__logic__">-->
          <!--            <el-divider>逻辑</el-divider>-->
          <!--            <el-form-item label="选择组件">-->
          <!--              <el-select v-model="activeData.__logic__.op"  placeholder="请选择组件" clearable-->
          <!--              @change="logicOpChange">-->
          <!--                <el-option-->
          <!--                  v-for="item in getLogicList()"-->
          <!--                  :key="item.__vModel__" :value="item.__vModel__"-->
          <!--                  :label="item.__config__.label">-->
          <!--                </el-option>-->
          <!--              </el-select>-->
          <!--            </el-form-item>-->
          <!--            <el-form-item label="满足条件">-->
          <!--              <el-select v-model="activeData.__logic__.setType" placeholder="请选择条件" clearable>-->
          <!--                <el-option :value="1" label="选中"> </el-option>-->
          <!--                <el-option :value="2" label="未选中"> </el-option>-->
          <!--              </el-select>-->
          <!--            </el-form-item>-->
          <!--            <el-form-item label="选择选项">-->
          <!--              <el-select v-model="activeData.__logic__.deVal" placeholder="请选择选项" clearable>-->
          <!--                <el-option  v-for="item in logicOpList"-->
          <!--                  :key="item.id" :value="item.id"-->
          <!--                  :label="item.fullName">-->
          <!--                </el-option>-->
          <!--              </el-select>-->
          <!--            </el-form-item>-->
          <!--          </template>-->
        </el-form>
        <el-form v-show="currentTab === 'logic'" label-width="85px" size="small" labelPosition="left">
          <el-collapse accordion>
            <template v-for="(i, k) in logicData">
              <el-collapse-item>
                <template slot="title">
                  <div class="flex" style="justify-content: space-between; width: 100%">
                    <span class="el-button--medium" style="font-weight: bold">逻辑分组</span>
                    <el-button v-if="k !== 0" size="medium" @click="logicData.splice(k, 1)" type="text"><span style="margin-right: 5px" class="el-icon-delete"></span>删除</el-button>
                    <el-button v-else size="medium" style="font-weight: bold" @click.stop="addLogic" type="text"><span style="margin-right: 5px" class="el-icon-plus"></span>添加</el-button>
                  </div>
                </template>
                <div style="padding: 0 20px">
                  <el-form-item label="被控组件">
                    <el-select v-model="i.hostval" filterable clearable placeholder="请选择">
                      <el-option
                        v-for="(item, index) in drawList"
                        :label="item.__config__.label"
                        :value="item.__vModel__"
                        :key="item.__config__.formId"
                        :disabled="getLogicDisOption(item.__vModel__)"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="主控组件">
                    <el-select v-model="i.op" placeholder="请选择组件" clearable @change="logicOpChange($event, i)">
                      <el-option v-for="item in LogicList" :key="item.__config__.formId" :value="item.__vModel__" :label="item.__config__.label"> </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="满足条件">
                    <el-select v-model="i.setType" placeholder="请选择条件" clearable>
                      <el-option :value="1" label="选中"> </el-option>
                      <el-option :value="2" label="未选中"> </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item>
                    <template slot="label">
                      <span>选择选项</span>
                      <el-tooltip style="cursor: pointer" effect="dark" :content="'已开启多选，满足其一即可'" placement="top">
                        <i class="el-icon-question" />
                      </el-tooltip>
                    </template>
                    <el-select v-model="i.deVal" placeholder="请选择选项" clearable multiple>
                      <el-option v-for="item in i.logicOpList || []" :key="item.id" :value="item.id" :label="item.fullName"> </el-option>
                    </el-select>
                  </el-form-item>
                </div>
              </el-collapse-item>
              <!--            <el-card class="relation-card" :key="k" shadow="never">-->
              <!--              <div slot="header" class="clearfix"></div>-->
              <!--              <template> </template>-->
              <!--            </el-card>-->
            </template>
          </el-collapse>
        </el-form>
        <!-- 关联设置 -->
        <el-form v-loading="loading" v-show="currentTab === 'relation'" label-width="80px" size="small" labelPosition="left">
          <template v-if="activeData.relationData">
            <el-form-item label="关联表单">
              <el-select v-model="activeData.relationData.itemRelationTable" filterable placeholder="请选择" clearable @change="onRelationTableChange($event)">
                <el-option v-for="(item, index) in allTabelList" :label="item.fullName" :value="item.id" :key="item.id"></el-option>
              </el-select>
              <!--                  <el-cascader ref="relationcascader"-->
              <!--                    v-model="i.relationName" :options="relationData" :props="{ expandTrigger: 'hover', emitPath: false }"-->
              <!--                    filterable @change="onDbChange($event,k)" :show-all-levels="false">-->
              <!--                  </el-cascader>-->
            </el-form-item>
            <el-form-item label="显示字段">
              <!--                  @change="relationfieldChange($event,k)"-->
              <el-select v-model="activeData.relationData.showTitle" @change="showTitleChange" filterable multiple collapse-tags placeholder="请选择">
                <el-option v-for="(item, index) in columnList" :label="item.title" :value="{ value: item.propId, label: item.title }" :key="item.propId"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="是否多列">
              <el-switch v-model="activeData.relationData.isCheck" inactive-text="多行选择" active-text="多列选择" @change="isCheckChange()" />
            </el-form-item>
            <el-table v-if="activeData.relationData.itemRelationList.length" :data="activeData.relationData.itemRelationList" style="width: 100%" border>
              <el-table-column label="关联字段">
                <template slot-scope="scope">{{ scope.row.label }}</template>
              </el-table-column>
              <el-table-column label="关联控件">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.drawId" filterable clearable placeholder="请选择" ref="selectRef">
                    <el-option
                      v-for="(item, index) in relationDrawList"
                      :label="item.__config__.label"
                      :value="item.__vModel__"
                      :key="item.__vModel__"
                      :disabled="getRelationDisOption(item.__vModel__)"
                    ></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column align="center">
                <template #header>
                  保存格式
                  <el-tooltip class="item" effect="light" content="开启：保存数据为明文， 关闭：保存数据为关联字段的ID号" placement="top-start">
                    <el-button type="text">帮助</el-button>
                  </el-tooltip>
                </template>
                <template slot-scope="scope">
                  <el-switch v-model="scope.row.plaintext" :active-value="1" :inactive-value="0"> </el-switch>
                </template>
              </el-table-column>
            </el-table>
            <el-form-item label="关联字段设置" label-width="100px" style="margin-top: 18px">
              <el-select v-model="activeData.relationData.PrimaryId" filterable placeholder="请选择">
                <el-option v-for="(item, index) in relationColumnList" :label="item.columnTitle" :value="item.id" :key="item.id"></el-option>
              </el-select>
            </el-form-item>
            <p style="color: #ff0000; font-size: 12px">
              {{ '提示：必须是主键或全局唯一标识每一条记录(行)的一个字段，如身份证号，入库编码等' }}
            </p>
            <el-form-item label="列多选分隔符" label-width="100px" style="margin-top: 18px">
              <el-select v-model="activeData.relationData.associationSeparator" placeholder="请选择">
                <el-option label="分号符" value=";"></el-option>
                <el-option label="逗号符" value=","></el-option>
              </el-select>
            </el-form-item>
          </template>
        </el-form>
        <!-- 表单属性 -->
        <el-form v-show="currentTab === 'form'" size="small" label-width="100px" labelPosition="left">
          <el-form-item label="表单尺寸">
            <el-radio-group v-model="formConf.size">
              <el-radio-button label="medium">中等</el-radio-button>
              <el-radio-button label="small">较小</el-radio-button>
              <el-radio-button label="mini">迷你</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="标签对齐">
            <el-radio-group v-model="formConf.labelPosition">
              <el-radio-button label="left">左对齐</el-radio-button>
              <el-radio-button label="right">右对齐</el-radio-button>
              <el-radio-button label="top" :disabled="formConf.formStyle === 'word-form'">顶部对齐 </el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="标题宽度">
            <el-input-number v-model="formConf.labelWidth" :min="0" placeholder="标题宽度" controls-position="right" />
          </el-form-item>
          <el-form-item label="栅格布局">
            <el-slider v-model="formConf.span" :max="24" :min="6" show-stops :step="2" show-tooltip />
          </el-form-item>
          <el-form-item label="栅格间隔">
            <el-input-number v-model="formConf.gutter" :min="0" placeholder="栅格间隔" controls-position="right" />
          </el-form-item>
          <el-form-item label="弹窗类型" v-if="modelType != 3 && modelType != 6">
            <el-select v-model="formConf.popupType" placeholder="请选择">
              <el-option label="普通弹窗" value="general"></el-option>
              <!--              <el-option label="全屏弹窗" value="fullScreen"></el-option>-->
            </el-select>
          </el-form-item>
          <el-form-item label="表单样式" v-if="modelType != 3">
            <el-select v-model="formConf.formStyle" placeholder="请选择">
              <el-option label="默认风格" value=""></el-option>
              <el-option label="公文风格" value="word-form"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="表单宽度" v-if="formConf.popupType === 'general' && modelType != 3 && modelType != 6">
            <el-select v-model="formConf.generalWidth" placeholder="请选择">
              <el-option v-for="item in generalWidthOptions" :label="item" :value="item" :key="item" />
            </el-select>
          </el-form-item>
          <el-form-item label="表单宽度" v-if="formConf.popupType === 'fullScreen' || modelType == 3 || modelType == 6">
            <el-select v-model="formConf.fullScreenWidth" placeholder="请选择">
              <el-option v-for="item in fullScreenWidthOptions" :label="item" :value="item" :key="item" />
            </el-select>
          </el-form-item>
          <el-form-item label="取消按钮文本" v-if="modelType != 3 && modelType != 6">
            <el-input v-model="formConf.cancelButtonText" placeholder="默认为‘取 消’" />
          </el-form-item>
          <el-form-item label="确定按钮文本" v-if="modelType != 3 && modelType != 6">
            <el-input v-model="formConf.confirmButtonText" placeholder="默认为‘确 定’" />
          </el-form-item>
          <!--          <el-divider>数据删除检查配置</el-divider>-->
          <!--          <div style="margin-bottom: 10px">-->
          <!--            <el-checkbox v-model="formConf.deleteDataCheckReferenceRelation" :true-label="1" :false-label="0">删除数据时检查被引用关联</el-checkbox>-->
          <!--          </div>-->
          <!--          <el-form-item label="忽略被引用关联表单" label-width="138px">-->
          <!--            <el-select v-model="formConf.deleteDataIgnoringReferenceRelationIds" placeholder="选择关联表" multiple collapse-tags>-->
          <!--              <el-option v-for="item in formInterfacesList" :label="item.fullName" :value="item.id" :key="item.id" />-->
          <!--            </el-select>-->
          <!--          </el-form-item>-->
          <!--          <p style="color: #ff0000">注：该表单列被其它表单所引用关联，即其它表单组件“关联设置”关联该表单列；</p>-->
        </el-form>
        <el-form v-show="currentTab === 'event'" size="small" label-width="100px" labelPosition="left">
          <Event v-if="activeData?.event?.isEvent" :activeData="activeData" :formConf="formConf"></Event>
        </el-form>
      </el-scrollbar>
    </div>
  </div>
</template>

<script>
import { deepClone, isNumberStr } from '@/components/Generator/utils'
import { inputComponents, systemComponents, selectComponents } from '@/components/Generator/generator/config'
import { getDrawingList } from '@/components/Generator/utils/db'
import JNPFComInput from './RightComponents/ComInput'
import JNPFTextarea from './RightComponents/Textarea'
import JNPFText from './RightComponents/JNPFText'
import JNPFNumInput from './RightComponents/NumInput'
import JNPFAmount from './RightComponents/JNPFAmount'
import JNPFPsdInput from './RightComponents/PsdInput'
import JNPFRadio from './RightComponents/Radio'
import JNPFCheckbox from './RightComponents/Checkbox'
import JNPFSelect from './RightComponents/Select'
import JNPFCascader from './RightComponents/Cascader/index'
import JNPFTime from './RightComponents/Time'
import JNPFTimeRange from './RightComponents/TimeRange'
import JNPFDate from './RightComponents/Date'
import JNPFDateRange from './RightComponents/DateRange'
import JNPFColorPicker from './RightComponents/ColorPicker'
import JNPFRate from './RightComponents/Rate'
import JNPFSwitch from './RightComponents/Switch'
import JNPFSlider from './RightComponents/Slider'
import JNPFDivider from './RightComponents/Divider'
import JNPFUploadFz from './RightComponents/UploadFz'
import JNPFUploadImg from './RightComponents/UploadImg'
import JNPFComRight from './RightComponents/ComRight'
import JNPFAddress from './RightComponents/Address'
import TreeSelect from './RightComponents/TreeSelect'
import GroupTitle from './RightComponents/GroupTitle'
import RelationForm from './RightComponents/RelationForm'
import RelationFormAttr from './RightComponents/RelationFormAttr'
import RelationFlow from './RightComponents/RelationFlow'
import RelationFlowAttr from './RightComponents/RelationFlowAttr'
import JNPFCalculate from './RightComponents/Calculate'
import PopupSelect from './RightComponents/PopupSelect'
import Tab from './RightComponents/Tab'
import Collapse from './RightComponents/Collapse'
import serialNumber from './RightComponents/serialNumber'
import Table from './RightComponents/Table'
import PlaceholderCom from './RightComponents/PlaceholderCom'
import { cubeFieldList } from '@/api/workFlow/FlowEngine'
import { getAssociatedFormInterfaces, getConfigData } from '@/api/onlineDev/visualDev'
import { loopRelationList } from '@/utils'
import AmisSdk from '@/components/AmisSdk.vue'
import Event from '@/components/Generator/index/RightComponents/Event.vue'

const commonRightList = ['comSelect', 'depSelect', 'posSelect', 'userSelect', 'dicSelect', 'editor']
const systemList = ['createUser', 'createUserId', 'modifyUserId', 'createTime', 'modifyUser', 'modifyTime', 'currOrganize', 'currDept', 'currPosition', 'billRule']
const relationComponents = ['comInput', 'numInput', 'switch', 'radio', 'checkbox', 'select', 'cascader', 'time', 'date']
export default {
  components: {
    Event,
    AmisSdk,
    JNPFComInput,
    JNPFTextarea,
    JNPFText,
    JNPFNumInput,
    JNPFAmount,
    JNPFPsdInput,
    JNPFRadio,
    JNPFCheckbox,
    JNPFSelect,
    JNPFCascader,
    JNPFTime,
    JNPFTimeRange,
    JNPFDate,
    JNPFDateRange,
    JNPFColorPicker,
    JNPFRate,
    JNPFSwitch,
    JNPFSlider,
    JNPFDivider,
    JNPFUploadFz,
    JNPFUploadImg,
    JNPFComRight,
    JNPFAddress,
    TreeSelect,
    GroupTitle,
    RelationForm,
    RelationFormAttr,
    RelationFlow,
    RelationFlowAttr,
    JNPFCalculate,
    PopupSelect,
    Tab,
    Collapse,
    serialNumber,
    Table,
    PlaceholderCom
  },
  props: ['showField', 'activeData', 'formConf', 'drawList', 'modelType', 'relationData', 'logicData', 'cubeList', 'dbLinkId', 'tableList', 'dbSourceId', 'activeId', 'allTabelList', 'columnModelId'],
  data() {
    return {
      allComponents: [...inputComponents, ...selectComponents.filter((v) => v.__config__.jnpfKey === 'serialNumber'), ...systemComponents],
      keyTypeList: [
        { name: '单行输入', keyType: 'comInput' },
        { name: '下拉选择', keyType: 'select' }
      ],
      currentTab: 'field',
      currentNode: null,
      dialogVisible: false,
      iconsVisible: false,
      currentIconModel: null,
      justifyOptions: [
        {
          label: 'start',
          value: 'start'
        },
        {
          label: 'end',
          value: 'end'
        },
        {
          label: 'center',
          value: 'center'
        },
        {
          label: 'space-around',
          value: 'space-around'
        },
        {
          label: 'space-between',
          value: 'space-between'
        }
      ],
      generalWidthOptions: ['600px', '800px', '1000px', '40%', '50%', '60%', '70%', '80%'],
      fullScreenWidthOptions: ['800px', '1000px', '1200px', '1400px', '50%', '60%', '70%', '80%', '90%', '100%'],
      layoutTreeProps: {
        label(data, node) {
          const config = data.__config__
          return data.componentName || `${config.label}: ${data.__vModel__}`
        }
      },
      logicOpList: [],
      columnList: [],
      relationColumnList: [],
      loading: false,
      LogicList: [],
      relationDrawList: [],
      formInterfacesList: []
    }
  },
  computed: {
    activeTag() {
      return this.activeData.__config__.tag
    },
    formItemList() {
      return this.$store.state.generator.formItemList
    },
    subTable() {
      return this.$store.state.generator.subTable || []
    },
    isCommon() {
      return commonRightList.indexOf(this.activeData.__config__.jnpfKey) > -1
    },
    isSystem() {
      return systemList.indexOf(this.activeData.__config__.jnpfKey) > -1
    },
    isRelation() {
      return relationComponents.indexOf(this.activeData.__config__.jnpfKey) > -1
    },
    filteredArray() {
      return this.activeData.relationData.itemRelationList.filter((item) => item.drawId)
    }
  },
  watch: {
    formConf: {
      handler(val) {
        // saveFormConf(val)
        if (val.formStyle === 'word-form' && val.labelPosition === 'top') {
          val.labelPosition = 'left'
        }
      },
      deep: true
    },
    activeData(val) {
      if (relationComponents.indexOf(this.activeData.__config__.jnpfKey) > -1 && !val.__config__.relationTable && !val.relationData) {
        this.setOldTabelRelation()
      }
      if (val.relationData && val.relationData.itemRelationTable) {
        this.getRelationConfig(val.relationData.itemRelationTable)
      }
      if (val.__config__.jnpfKey === 'relationFormAttr') {
        this.$nextTick(() => {
          this.$refs.relationFormAttr && this.$refs.relationFormAttr.getOptions()
        })
      }
      if (val.__config__.jnpfKey === 'relationFlowAttr') {
        this.$nextTick(() => {
          this.$refs.relationFlowAttr && this.$refs.relationFlowAttr.getOptions()
        })
      }
      if (val.__config__.jnpfKey !== 'calculate') {
        this.$nextTick(() => {
          this.$refs.calculate && this.$refs.calculate.reloadExpressionTemp()
        })
      }
      this.getLogicList()
      this.getDrawListAllList()
    },
    activeId: {
      handler(val) {
        if (val) {
          this.currentTab = 'field'
        } else {
          this.currentTab = 'form'
          this.getLogicList()
        }
      },
      deep: true
    }
  },
  created() {
    if (this.activeData.relationData && this.activeData.relationData.itemRelationTable) {
      this.getRelationConfig(this.activeData.relationData.itemRelationTable)
    }
    if (relationComponents.indexOf(this.activeData.__config__.jnpfKey) > -1 && !this.activeData.__config__.relationTable && !this.activeData.relationData) {
      this.setOldTabelRelation()
    }
    this.getLogicList()
    this.getDrawListAllList()
    this.getAssociatedFormInterfacesList()
  },
  methods: {
    // 获取被引用关联表单接口
    getAssociatedFormInterfacesList() {
      getAssociatedFormInterfaces(this.$route.query.id).then((res) => {
        this.formInterfacesList = res.data.data
      })
    },
    getDrawListAllList() {
      let drawListAll = deepClone(this.drawList)
      this.relationDrawList = loopRelationList(drawListAll)
    },
    // 兼容老版本表单 添加关联设置基本信息
    setOldTabelRelation() {
      this.$set(this.activeData, 'relationData', {})
      this.$set(this.activeData.relationData, 'itemRelationTable', '')
      this.$set(this.activeData.relationData, 'RelationTableCubeId', '')
      this.$set(this.activeData.relationData, 'showTitle', [])
      this.$set(this.activeData.relationData, 'isCheck', false)
      this.$set(this.activeData.relationData, 'itemRelationList', [])
      this.$set(this.activeData.relationData, 'PrimaryId', '')
      this.$set(this.activeData.relationData, 'associationSeparator', ';')
    },
    //获取符合添加逻辑的list
    getLogicList() {
      this.LogicList = this.drawList
        .map((i) => {
          if (i.__config__.jnpfKey === 'select' && i.__vModel__) {
            return i
          }
        })
        .filter((l) => l !== undefined)
    },
    logicOpChange(e, item) {
      this.drawList.forEach((i, k) => {
        if (i.__vModel__ === e) {
          item.logicOpList = i.__slot__.options
        }
      })
    },
    showTitleChange() {
      const relationData = g.toHash(this.activeData.relationData.showTitle, 'value')
      const itemRelationList = g.toHash(this.activeData.relationData.itemRelationList, 'columnId')
      const showTitle = Object.values(relationData)
      this.activeData.relationData.itemRelationList = showTitle.map((o) => {
        const find = itemRelationList[o.value] || {}
        return {
          columnId: o.value,
          label: o.label,
          drawId: find?.drawId || '',
          plaintext: find.plaintext === undefined ? 0 : find.plaintext === 0 ? 0 : find.plaintext
        }
      })
    },
    isCheckChange() {
      this.showTitleChange()
    },
    //关联字段新增
    relationfieldChange(v, k) {
      let changeData = deepClone(v)
      let keyData = changeData.map((i) => {
        return i.value
      })
      if (this.relationData[k].relationList && this.relationData[k].relationList.length) {
        this.relationData[k].relationList.forEach((item, i) => {
          //比较差异 获取列表中多余的关联字段删除
          if (!keyData.includes(item.fieldId)) {
            delete this.relationData[k].relationList[i]
          }
        })
        let addData = this.relationData[k].relationList.map((i) => {
          return i.fieldId
        })
        //比较差异 获取列表中没有的关联字段添加
        let columns = keyData.filter((cur) => !addData.includes(cur))
        if (columns && columns.length) {
          for (let i in columns) {
            this.relationData[k].relationList.push({ fieldId: columns[i], drawId: null })
          }
        }
      } else {
        this.relationData[k].relationList = v.map((item) => {
          return {
            fieldId: item.value,
            drawId: null
          }
        })
      }
      this.relationData[k].relationList = this.relationData[k].relationList.filter(Boolean)
    },
    getrelationName(id) {
      let str = this.cubeList
        .map((item) => item.children)
        .flat()
        .find((item) => item.value === id)
      if (!str) return
      return str.label
    },
    addRelation() {
      this.relationData.push({ relationName: '', fieldName: [], fieldList: [], tablesList: [], relationList: [] })
    },
    addLogic() {
      this.logicData.push({ hostval: '', op: '', setType: '', deVal: [], logicOpList: [] })
    },
    getLogicDisOption(id) {
      let res = false
      this.logicData.forEach((i, k) => {
        if (i.hostval && i.hostval === id) {
          res = true
        }
      })
      return res
    },
    getRelationDisField(id) {
      let list = this.relationData.map((i) => {
        return i.relationName
      })
      let res = false
      list.forEach((i, k) => {
        if (i && i === id) {
          res = true
        }
      })
      return res
    },
    getRelationDisOption(id) {
      let res = false
      this.activeData.relationData.itemRelationList.forEach((i, k) => {
        if (this.activeData.relationData.isCheck) {
          if (id !== this.activeData.__vModel__) res = true
        } else {
          if (i.drawId && i.drawId === id) {
            res = true
          }
        }
      })
      return res
    },
    // 选择完关联表单后 要获取关联表单的显示字段
    onRelationTableChange(val) {
      this.loading = true
      this.$set(this.activeData.relationData, 'RelationTableCubeId', '')
      this.$set(this.activeData.relationData, 'showTitle', [])
      this.$set(this.activeData.relationData, 'isCheck', false)
      this.$set(this.activeData.relationData, 'itemRelationList', [])
      this.$set(this.activeData.relationData, 'PrimaryId', '')
      this.$set(this.activeData.relationData, 'associationSeparator', ';')
      if (val) {
        this.getRelationConfig(val)
      } else {
        this.loading = false
      }
      //   getConfigData(val).then((res)=>{
      //   let dbLinkid = res.data.data.dbLinkId
      //   cubeFieldList({cubeDataId: dbLinkid}).then((res)=>{
      //     this.columnList = res.data.data.reverse()
      //   })
      // })
    },
    getRelationConfig(val) {
      getConfigData(val).then((res) => {
        let data = res.data.data
        this.activeData.relationData.RelationTableCubeId = data.dbLinkId
        let columnData = JSON.parse(data.columnData)
        this.onDbChange(data.dbLinkId)
        this.columnList = columnData.columnList
        this.loading = false
      })
    },
    onDbChange(val, k) {
      //获取数据集
      cubeFieldList({ cubeDataId: val }).then((res) => {
        this.relationColumnList = res.data.data.reverse()
        // this.relationData[k].fieldList = res.data.data.reverse()
        // this.relationData[k].relationList = []
        // this.relationData[k].fieldName = []
      })
    },
    changeType(val, t) {
      const oldActiveData = g.Copy(this.activeData)
      let newData = this.allComponents.find((o) => o.__config__.jnpfKey === val)
      this.$emit('changeType', { oldActiveData, newData })
    },
    addReg() {
      this.activeData.__config__.regList.push({
        pattern: '',
        message: ''
      })
    },
    setDefaultValue(val) {
      if (Array.isArray(val)) {
        return val.join(',')
      }
      // if (['string', 'number'].indexOf(typeof val) > -1) {
      //   return val
      // }
      if (typeof val === 'boolean') {
        return `${val}`
      }
      return val
    },
    onDefaultValueInput(str) {
      if (Array.isArray(this.activeData.__config__.defaultValue)) {
        // 数组
        this.$set(
          this.activeData.__config__,
          'defaultValue',
          str.split(',').map((val) => (isNumberStr(val) ? +val : val))
        )
      } else if (['true', 'false'].indexOf(str) > -1) {
        // 布尔
        this.$set(this.activeData.__config__, 'defaultValue', JSON.parse(str))
      } else {
        // 字符串和数字
        this.$set(this.activeData.__config__, 'defaultValue', isNumberStr(str) ? +str : str)
      }
    },
    getSubTalebFiled(key) {
      let list = this.drawList.find((o) => o.__config__.tableName && o.__config__.tableName === key)
      if (list) {
        return list.mainTableFields
      }
    },
    fieldChange1(val) {
      if (!val) return
      let options = this.getSubTalebFiled(this.activeData.__config__.relationTable)
      let item = options.filter((o) => o.field == val)[0]
      if (!item || !item.fieldName) return
      this.activeData.__config__.label = item.fieldName
    },
    //选中过的置灰
    getDisabledSelect(val) {
      let res = false
      this.drawList.forEach((i, k) => {
        if (i.__vModel__ && i.__vModel__ === val) {
          res = true
        }
      })
      return res
    },
    //子表 选中过的置灰
    getChildrenDisabledSelect(key, val) {
      let res = false
      let list = this.drawList.find((o) => o.__config__.tableName && o.__config__.tableName === key)
      if (list && list.__config__.children && list.__config__.children.length) {
        list.__config__.children.forEach((i, k) => {
          if (i.__vModel__ && i.__vModel__ === val) {
            res = true
          }
        })
      }

      return res
    },
    //选中过的置灰 字段为字符
    getDisabledStrSelect(val, item) {
      let res = false
      this.drawList.forEach((i, k) => {
        if ((i.__vModel__ && i.__vModel__ === val) || item.viewDataType !== 'STRING') {
          res = true
        }
      })
      return res
    },
    //判断有没有选中
    fieldChange(val) {
      console.log(val)
      this.$forceUpdate()
      if (!val) return
      const drawingList = getDrawingList() || []
      let boo = false
      const loop = (list) => {
        for (let i = 0; i < list.length; i++) {
          const e = list[i]
          const config = e.__config__
          if (e.__vModel__ === val) {
            boo = true
            break
          }
          if (config && config.jnpfKey != 'table' && config.children && Array.isArray(config.children)) {
            loop(config.children)
          }
        }
      }
      loop(drawingList)
      if (boo) {
        this.$message.warning(`字段【${val}】已存在,请重新选!`)
        this.activeData.__vModel__ = ''
        return
      }
      // let item = this.formItemList.filter(o => o.id === val)[0]
      let item

      if (this.activeData.__config__.isSubTable) {
        let childrenTable = this.getSubTalebFiled(this.activeData.__config__.relationTable)
        childrenTable.filter((o) => {
          if (o.id === val) {
            item = o
          }
        })
      } else {
        this.formItemList.filter((o) => {
          // if(o.children && o.children.length){
          //   o.children.forEach((i,k)=>{
          if (o.id === val) {
            item = o
          }
          //   })
          // }
        })
      }
      if (!item || !item.columnTitle) return
      this.activeData.__config__.label = item.columnTitle
      this.activeData.__config__.viewDataType = item.viewDataType
      this.activeData.__vModelName__ = item.columnName
      this.activeData.__config__.isRequiredType = item.isRequiredType
      // 如果关联字段为主子表关联主键 需要禁用
      let list = this.drawList.find((o) => o.__config__.tableName && o.__config__.tableName === this.activeData.__config__.relationTable)
      if (list && list.relationConf.foreignModel === this.activeData.__vModel__) {
        this.activeData.disabled = true
      }
      this.$nextTick(() => {
        this.$forceUpdate()
      })
    },
    spanChange(val) {
      this.formConf.span = val
    }
  }
}
</script>

<style lang="scss" scoped>
.right-board {
  width: 340px;
  position: absolute;
  right: 0;
  top: 0;
  padding-top: 3px;
  height: 100%;
  background: #fff;
  border-radius: 4px;
  .field-box {
    position: relative;
    height: calc(100% - 42px);
    box-sizing: border-box;
    overflow: hidden;
  }
  .el-scrollbar {
    height: 100%;
  }
}

.select-item {
  display: flex;
  border: 1px dashed #fff;
  box-sizing: border-box;
  & .close-btn {
    cursor: pointer;
    color: #f56c6c;
  }
  & .el-input + .el-input {
    margin-left: 4px;
  }
}
.select-item + .select-item {
  margin-top: 4px;
}
.select-item.sortable-chosen {
  border: 1px dashed #409eff;
}
.select-line-icon {
  line-height: 32px;
  font-size: 22px;
  padding: 0 4px;
  color: #777;
}
.option-drag {
  cursor: move;
}
.time-range {
  .el-date-editor {
    width: 227px;
  }
  ::v-deep .el-icon-time {
    display: none;
  }
}
.document-link {
  position: absolute;
  display: block;
  width: 26px;
  height: 26px;
  top: 0;
  left: 0;
  cursor: pointer;
  background: #409eff;
  z-index: 1;
  border-radius: 0 0 6px 0;
  text-align: center;
  line-height: 26px;
  color: #fff;
  font-size: 18px;
}
.node-label {
  font-size: 14px;
}
.node-icon {
  color: #bebfc3;
}
.right-scrollbar {
  .el-form {
    >>> .el-date-editor,
    >>> .el-cascader,
    >>> .el-select {
      width: 100%;
    }
  }
}
.relation-card {
  margin-bottom: 10px;
  ::v-deep .el-card__header {
    padding: 10px 20px;
  }
}
:deep(.el-collapse-item__arrow) {
  position: absolute;
}
</style>
