<template>
  <el-dialog
    fullscreen
    :visible.sync="dialogVisible"
    v-if="dialogVisible"
    @destroy-on-close="true"
    class="form-editor-dialog"
  >
    <el-container class="fullheight">
      <el-header class="header" style="height: 45px">
        <div class="navbar-default box-shadow flex">
          <el-page-header @back="beforeClose" content="详情页面">
          </el-page-header>
          <ht-submit-button
            url="${portal}/portal/sysApp/v1/save"
            :model="appModel"
            scope-name="appModelForm"
            @after-save-data="afterSaveData"
            @before-save-data="beforeSaveData"
            >{{ $t('eip.common.save') }}
          </ht-submit-button>
        </div>
      </el-header>
      <el-main>
        <el-tabs type="card" v-model="activeName">
          <el-tab-pane label="基础信息" name="base">
            <el-form
              v-form="{formItemAlign: labelPosition}"
              data-vv-scope="appModelForm"
            >
              <ht-form-item label="应用名称">
                <ht-input
                  v-model="appModel.name"
                  validate="required"
                  width="434px"
                  :maxlength="50"
                  :showWordLimit="true"
                />
              </ht-form-item>
              <ht-form-item label="图标">
                <div class="icon-wrap">
                  <div class="icon-main">
                    <el-image
                      class="image"
                      :src="image"
                      v-if="image"
                    ></el-image>
                    <i
                      v-else
                      :class="appModel.icon"
                      :style="{fontSize: '30px', color: appModel.iconColor}"
                      class="app-icon"
                    ></i>
                  </div>
                  <icon-dialog
                    class="icon-select_wrap"
                    @selected="selectIcon"
                  />
                  <el-upload
                    action="string"
                    :http-request="updateImage"
                    :show-file-list="false"
                    accept="image/gif,image/jpeg,image/png,image/jpg,image/bmp"
                  >
                    <el-button size="small">上传图标</el-button>
                  </el-upload>
                  <el-button
                    style="margin-left: 16px"
                    class="upload-bt"
                    size="small"
                    @click="handleClear"
                    >清空</el-button
                  >
                </div>
              </ht-form-item>
              <ht-form-item label="图标颜色">
                <el-input
                  v-model="appModel.iconColor"
                  style="width: 402px; vertical-align: middle"
                  clearable
                  placeholder=""
                />
                <el-color-picker
                  class="layout_md"
                  v-model="appModel.iconColor"
                ></el-color-picker>
              </ht-form-item>
              <ht-form-item label="跳转模式">
                <ht-select
                  v-model="appModel.type"
                  :options="typeOptions"
                  validate="required"
                  class="width-input"
                  @change="modeChange"
                  :style="{width: wrapWidth}"
                />
              </ht-form-item>
              <ht-form-item label="表单列表" v-if="appModel.type === 2">
                <eip-data-template-selector
                  class="select-list"
                  v-model="templateData"
                  placeholder="请选择表单列表"
                  :single="true"
                />
              </ht-form-item>
              <ht-form-item label="数据列表" v-if="appModel.type === 3">
                <eip-custom-view-selector
                  validate="required"
                  v-model="customQueryData"
                  :single="true"
                  class="select-list"
                />
              </ht-form-item>
              <ht-form-item label="图表" v-if="appModel.type === 4">
                <eip-chart-selector
                  validate="required"
                  :dataParam.sync="appModel.content"
                  :chartType="2"
                  class="select-list"
                ></eip-chart-selector>
              </ht-form-item>
              <ht-form-item label="网页跳转" v-if="appModel.type === 5">
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="系统内网页可填写相对路径"
                  placement="top"
                >
                  <i class="el-icon-info"></i>
                </el-tooltip>
                <ht-input
                  v-model="appModel.content"
                  :validate="{required: true}"
                  style="width: 90%"
                ></ht-input>
              </ht-form-item>
              <ht-form-item label="表单" v-if="appModel.type === 6">
                <eip-form-selector
                  validate="required"
                  v-model="formData"
                  :single="true"
                  class="select-list"
                />
              </ht-form-item>
              <ht-form-item label="模块" v-if="appModel.type === 7">
                <eip-module-selector
                  class="select-list"
                  validate="required"
                  v-model="moduleData"
                  :single="true"
                />
              </ht-form-item>
              <ht-form-item label="流程" v-if="appModel.type === 8">
                <eip-flow-selector
                  validate="required"
                  v-model="flowData"
                  :single="true"
                  class="select-list"
                >
                </eip-flow-selector>
              </ht-form-item>
              <ht-form-item label="datav大屏" v-if="appModel.type === 9">
                <ht-select
                  v-model="datavData.alias"
                  :options="datavList"
                  validate="required"
                  class="width-input select-list"
                  :props="{key: 'alias', value: 'name'}"
                  @change="datavChange"
                />
              </ht-form-item>
              <ht-form-item label="排序">
                <ht-input
                  class="input-text"
                  v-model="appModel.sn"
                  :min="0"
                  :max="999"
                  :width="wrapWidth"
                  type="number"
                />
              </ht-form-item>
              <ht-form-item label="描述">
                <ht-input
                  v-model="appModel.desc"
                  :width="wrapWidth"
                  type="textarea"
                  :rows="3"
                  :maxlength="200"
                  :showWordLimit="true"
                />
              </ht-form-item>
              <ht-form-item label="应用菜单">
                <tree-Select
                  style="width: 432px"
                  :appendToBody="true"
                  v-model="appModel.menuId"
                  :normalizer="normalizer"
                  :multiple="false"
                  :options="menus"
                  noOptionsText=" "
                  noChildrenText=" "
                  z-index="9999"
                  placeholder="请选择父节点"
                />
              </ht-form-item>
            </el-form>
          </el-tab-pane>
          <!-- <el-tab-pane label="应用说明" name="appDesc" v-if="appModel.id">
            <portal-app-param :appId="appModel.id"></portal-app-param>
          </el-tab-pane> -->
          <el-tab-pane
            label="菜单信息"
            name="menu"
            v-if="appModel.type === 1"
            :disabled="!appModel.id"
          >
            <sys-app-menu :id="selectId"></sys-app-menu>
          </el-tab-pane>
        </el-tabs>
      </el-main>
    </el-container>
  </el-dialog>
</template>

<script>
import uc from '@/api/uc.js'
import portal from '../../api/portal'
const treeSelect = () => import('@riophae/vue-treeselect')
const IconDialog = () => import('@/components/dialog/IconDialog.vue')
const EipDataTemplateSelector = () =>
  import('@/components/selector/EipDataTemplateSelector.vue')
const EipCustomViewSelector = () =>
  import('@/components/selector/EipCustomViewSelector.vue')
const EipChartSelector = () =>
  import('@/components/selector/EipChartSelector.vue')
const EipFormSelector = () =>
  import('@/components/selector/EipFormSelector.vue')
const EipModuleSelector = () =>
  import('@/components/selector/EipModuleSelector.vue')
const EipFlowSelector = () =>
  import('@/components/selector/EipFlowSelector.vue')
const PortalAppParam = () => import('@/views/portal/PortalAppParamManager.vue')
const SysAppMenu = () => import('@/components/portal/SysAppMenu.vue')

export default {
  name: 'app-dialog',
  components: {
    IconDialog,
    EipDataTemplateSelector,
    EipCustomViewSelector,
    EipChartSelector,
    EipFormSelector,
    EipModuleSelector,
    EipFlowSelector,
    PortalAppParam,
    SysAppMenu,
    treeSelect,
  },
  data() {
    return {
      labelPosition: 'left',
      wrapWidth: '434px',
      dialogVisible: false,
      appModel: {
        name: '',
        icon: '',
        iconType: 1,
        iconColor: '#1339E0',
        type: '',
        content: '',
        menuId: '',
      },
      activeName: 'base',
      image: '',
      typeOptions: [
        {key: 1, value: '常规应用'},
        {key: 2, value: '表单列表'},
        {key: 3, value: '数据列表'},
        {key: 4, value: '图表'},
        {key: 5, value: '网页跳转'},
        {key: 6, value: '表单'},
        {key: 7, value: '流程模块'},
        {key: 8, value: '流程'},
        {key: 9, value: 'datav大屏'},
      ],
      templateData: {},
      customQueryData: {},
      formData: {},
      moduleData: {},
      flowData: {},
      datavData: {id: '', alias: '', name: ''},
      datavList: [],
      datavMap: {},
      selectId: '',
      menu: {},
      menus: [],
    }
  },
  methods: {
    handleClear() {
      this.appModel.icon = ''
      this.image = ''
    },
    open(id, menuName) {
      this.activeName = 'base'
      this.loadMenus()
      this.dialogVisible = true
      this.selectId = id
      portal.getSysApp(id).then((data) => {
        data.icon = data.icon || ''
        if (!menuName) {
          data.menuId = null
        }
        this.appModel = data
        this.image = ''
        if (this.appModel.icon && this.appModel.icon.indexOf('icon') < 0) {
          this.image = this.appModel.icon
        }
        if (this.appModel.type === 2) {
          this.templateData = JSON.parse(this.appModel.content)
        } else if (this.appModel.type === 3) {
          this.customQueryData = JSON.parse(this.appModel.content)
        } else if (this.appModel.type === 6) {
          this.formData = JSON.parse(this.appModel.content)
        } else if (this.appModel.type === 8) {
          this.flowData = JSON.parse(this.appModel.content)
        } else if (this.appModel.type === 7) {
          this.moduleData = JSON.parse(this.appModel.content)
        } else if (this.appModel.type === 9) {
          this.datavData = JSON.parse(this.appModel.content)
          this.getDatavList()
        }
      })
    },
    add() {
      this.dialogVisible = false
      this.loadMenus()
      this.$nextTick(() => {
        this.dialogVisible = true
      })
      this.activeName = 'base'
      this.image = ''
      this.appModel = {
        name: '',
        icon: '',
        iconType: 1,
        iconColor: this.getRandomColor(),
        type: '',
        content: '',
      }
    },
    getRandomColor() {
      var colorValue = '0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F'
      var color = '#'
      var colorArray = colorValue.split(',')
      for (var i = 0; i < 6; i++) {
        color += colorArray[Math.floor(Math.random() * 16)]
      }
      return color
    },
    beforeClose() {
      this.dialogVisible = false
      //关闭弹窗重置data数据
      Object.assign(this.$data, this.$options.data())
    },
    afterSaveData() {
      this.dialogVisible = false
      //关闭弹窗重置data数据
      Object.assign(this.$data, this.$options.data())
      this.$emit('refresh')
    },
    beforeSaveData() {
      if (this.appModel.type === 2) {
        let data = {
          id: this.templateData.id,
          alias: this.templateData.alias,
          name: this.templateData.name,
        }
        this.appModel.content = JSON.stringify(data)
      } else if (this.appModel.type === 9) {
        this.appModel.content = JSON.stringify(this.datavData)
      } else if (this.appModel.type === 3) {
        let data = {
          id: this.customQueryData.id,
          alias: this.customQueryData.alias,
          sqlAlias: this.customQueryData.sqlAlias,
          name: this.customQueryData.name,
        }
        this.appModel.content = JSON.stringify(data)
      } else if (this.appModel.type === 6) {
        let data = {
          id: this.formData.id,
          name: this.formData.name,
          key: this.formData.formKey,
        }
        this.appModel.content = JSON.stringify(data)
      } else if (this.appModel.type === 7) {
        let data = {
          id: this.moduleData.id,
          name: this.moduleData.name,
        }
        this.appModel.content = JSON.stringify(data)
      } else if (this.appModel.type === 8) {
        let data = {
          id: this.flowData.id,
          name: this.flowData.name,
          key: this.flowData.defKey,
        }
        this.appModel.content = JSON.stringify(data)
      } else if (this.appModel.type === 9) {
        this.datavData = JSON.parse(this.appModel.content)
        this.getDatavList()
      }
      if (this.image) {
        this.appModel.icon = this.image
      }
    },
    selectIcon(icon) {
      this.image = ''
      this.appModel.icon = icon
    },
    updateImage(param) {
      const formData = new FormData()
      formData.append('files', param.file)
      uc.fileUpload(formData)
        .then((response) => {
          this.$store
            .dispatch('menu/downloadImg', response.fileId)
            .then((res) => {
              if (res !== '') {
                this.image = res
                param.onSuccess()
              }
            })
            .catch(() => {
              param.onError()
            })
        })
        .catch(() => {
          param.onError()
        })
    },
    modeChange() {
      this.$set(this.appModel, 'content', '')
      this.formData = {}
      this.templateData = {}
      this.customQueryData = {}
      this.moduleData = {}
      this.flowData = {}
      this.datavData = {id: '', alias: '', name: ''}
      if (this.appModel.type === 9) {
        this.getDatavList()
      }
    },
    datavChange(val) {
      this.$set(this.datavData, 'id', this.datavMap[val].id)
      this.$set(this.datavData, 'name', this.datavMap[val].name)
    },
    getDatavList() {
      let query = []
      query.push({
        property: 'type_',
        value: 'datav',
        group: 'type',
        operation: 'EQUAL',
        relation: 'AND',
      })
      query.push({
        property: 'enable',
        operation: 'EQUAL',
        value: 1,
        relation: 'AND',
        group: 'type',
      })
      query.push({
        property: 'LAYOUT_TYPE',
        value: 1,
        group: 'type',
        operation: 'NOT_EQUAL',
        relation: 'AND',
      })
      let param = {
        pageBean: {page: 1, pageSize: -1, total: 0},
        querys: query,
        sorter: [{direction: 'DESC', property: 'CREATE_TIME_'}],
      }
      let _this = this
      portal
        .getLayoutManagerPage(param)
        .then((data) => {
          _this.datavList = []
          _this.datavMap = {}
          if (data.rows && data.rows.length > 0) {
            _this.datavList = data.rows
            data.rows.forEach((item) => {
              _this.datavMap[item.alias] = item
            })
          }
        })
        .finally(() => {})
    },
    normalizer(node) {
      return {
        id: node.id,
        label: node.name,
        children: node.children,
        isDefaultExpanded: false,
      }
    },
    loadMenus() {
      portal.getCurrentMenuByAlias('app_menu').then((data) => {
        if (data.state) {
          this.menus = data.value
          this.removeEmptyChildren(this.menus)
        }
      })
    },
    removeEmptyChildren(menus) {
      menus.forEach((m) => {
        if (m.children) {
          if (m.children.length < 1) {
            delete m.children
          } else {
            this.removeEmptyChildren(m.children)
          }
        }
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.navbar-default {
  height: 100%;
  background-image: none;
  background: #fff;
  border-radius: 0px;
  box-shadow: 0px 2px 5px rgba(86, 96, 117, 0.15);
  border-bottom: 1px solid #ededed;
  justify-content: space-between;
  padding: 0 20px;
}
.navbar-default span {
  color: #666;
  font-size: 14px;
  line-height: 48px;
  font-weight: bold;
  margin-left: 20px;
}
.header {
  padding: 0;
  background: #fff;
  z-index: 7;
}

.form-editor-dialog {
  .el-form-item--small.el-form-item {
    margin-bottom: 32px;
  }
  .input-text {
    text-align: left;
    /deep/.el-input--small .el-input__inner {
      text-align: left;
    }
  }
}

.icon-wrap {
  display: flex;
  align-items: center;
  margin-top: -5px;
  .icon-main {
    width: 40px;
    height: 40px;
    background: rgb(244, 244, 244);
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 2px;
    text-align: center;
  }
}
.icon-select_wrap {
  margin: 0 16px;
  flex: 0 0 87px;
  height: 34px;
}

.select-list {
  width: 90%;
  /deep/.el-input-group {
    width: 90%;
  }
}

.layout_md {
  vertical-align: middle;
  /deep/.el-color-picker__trigger {
    border-color: #dcdfe6;
  }
}
</style>
