<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogVisible"
    width="650px"
    :close-on-click-modal="false"
    append-to-body
  >
    <el-form
      :model="appModel"
      data-vv-scope="appForm"
      label-position="left"
      v-if="dialogVisible"
    >
      <ht-form-item label="应用名称">
        <ht-input
          v-model="appModel.name"
          validate="required"
          style="width: 100%"
          :maxlength="50"
          :showWordLimit="true"
        />
      </ht-form-item>
      <ht-form-item label="应用别名">
        <ht-input
          :disabled="!!appModel.id"
          v-model="appModel.alias"
          validate="required"
          style="width: 100%"
          :maxlength="50"
          :showWordLimit="true"
          v-pinyin="appModel.name"
        />
      </ht-form-item>
      <ht-form-item label="所属分类" class="is-required">
        <tree-select
          style="width: 456px"
          :appendToBody="true"
          v-model="appModel.menuId"
          :normalizer="normalizer"
          :multiple="false"
          :options="appTypes"
          noOptionsText=" "
          noChildrenText=" "
          z-index="9999"
          placeholder="请选择父节点"
          :clearable="false"
        />
      </ht-form-item>
      <ht-form-item label="应用Logo">
        <div class="icon-wrap">
          <div class="icon-main" :style="{background: appModel.iconColor}">
            <el-image class="image" :src="image" v-if="image"></el-image>
            <i
              v-else
              :class="appModel.icon"
              :style="{fontSize: '30px', color: 'white'}"
              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="Logo颜色">
        <el-input
          v-model="appModel.iconColor"
          style="width: 414px; vertical-align: middle"
          clearable
          placeholder=""
        />
        <el-color-picker
          class="layout_md"
          v-model="appModel.iconColor"
        ></el-color-picker>
        <div class="default-color--list">
          <div
            class="color-item"
            v-for="(item, index) in colorList"
            :key="index"
            @click="handleColor(item)"
            :style="{background: item}"
          ></div>
        </div>
      </ht-form-item>
      <ht-form-item label="排序">
        <ht-input
          class="input-text"
          v-model="appModel.sn"
          :min="0"
          :max="999"
          style="width: 100%"
          type="number"
          controls-position="right"
        />
      </ht-form-item>
      <ht-form-item label="应用说明">
        <el-upload
          style="display: inline-block"
          :action="uploadUrl"
          :on-success="handleUploadResult"
          :on-error="handleUploadResult"
          :headers="uploadHeaders"
          :on-exceed="onExceed"
          accept=".pdf,.png,.jpg"
          :before-upload="beforeUpload"
          :on-remove="onRemove"
          :limit="1"
          :file-list="fileList"
          ref="uploadRef"
        >
          <div style="display: flex">
            <el-button size="small" icon="icon-my-todo-upload">上传</el-button>
            <div style="color: #5f5f5f; margin-left: 8px">可上传图片或pdf</div>
          </div>
        </el-upload></ht-form-item
      >
      <ht-form-item label="应用描述">
        <ht-input
          v-model="appModel.desc"
          type="textarea"
          :rows="3"
          :maxlength="200"
          :showWordLimit="true"
          style="width: 100%"
        />
      </ht-form-item>
    </el-form>
    <div slot="footer">
      <el-button @click="beforeClose">取消</el-button>
      <ht-submit-button
        url="${portal}/portal/sysApp/v1/save"
        :model="appModel"
        scope-name="appForm"
        @after-response-value="afterSaveData"
        @before-save-data="beforeSaveData"
        :is-submit="isSubmit"
        >确定
      </ht-submit-button>
    </div>
  </el-dialog>
</template>

<script>
import uc from '@/api/uc.js'
import portal from '@/api/portal'
import utils from '@/hotent-ui-util'
import {mapState} from 'vuex'
const IconDialog = () => import('@/components/dialog/IconDialog.vue')
const TreeSelect = () => import('@riophae/vue-treeselect')
import _ from 'lodash'
export default {
  name: 'AppInfoDialog',
  components: {
    IconDialog,
    TreeSelect,
  },
  data() {
    return {
      dialogVisible: false,
      appModel: {
        id: '',
        name: '',
        alias: '',
        icon: '',
        iconColor: '#1339E0',
        type: '',
        content: '',
        sn: 1,
        createTime: '',
        updateTime: '',
        createBy: '',
        updateBy: '',
        isPublish: '',
        desc: '',
        menuAlias: '',
        menuName: '',
        contentAlias: '',
      },
      image: '',
      wrapWidth: '434px',
      title: '添加应用信息',
      colorList: [
        '#409EFF',
        '#07C160',
        '#4053FF',
        '#F6B85A',
        '#FF8A46',
        '#8550E1',
      ],
      action: 'add',
      menus: [],
      isSubmit: true,
      fullscreenLoading: false,
      fileList: [],
    }
  },
  computed: mapState({
    appTypes: (state) => {
      let stateAppTypes = _.cloneDeep(state.menu.appTypes)
      utils.nestForEach(stateAppTypes, 'children', (item) => {
        if (!item.children || item.children.length === 0) {
          delete item.children
        }
      })

      return stateAppTypes || []
    },
    uploadUrl: function () {
      return `${context.portal}/system/file/v1/upload`
    },
    uploadHeaders: function (mapState) {
      return {Authorization: 'Bearer ' + mapState.login.currentUser.token}
    },
  }),
  mounted() {
    this.loadMenus()
  },
  methods: {
    open(data) {
      if (data) {
        this.action = 'edit'
        this.title = '编辑应用信息'
        portal.getSysApp(data.id).then((data) => {
          data.icon = data.icon || ''
          this.appModel = data
          this.image = ''
          if (this.appModel.icon && this.appModel.icon.indexOf('icon') < 0) {
            this.image = this.appModel.icon
          }
          if (this.appModel.fileInfo) {
            this.fileList = [JSON.parse(this.appModel.fileInfo)].map((item) => {
              return {
                name: item.fileName,
              }
            })
          }
        })
        this.dialogVisible = true
      } else {
        this.action = 'add'
        this.title = '添加应用信息'
        this.appModel.icon = 'icon-application1'
        this.appModel.iconColor = '#409EFF'
        this.appModel.type = 1
        this.appModel.sn = 1
        this.image = ''
        this.dialogVisible = true
      }
    },
    getRandomColor() {
      return '#' + Math.floor(Math.random() * 16777215).toString(16)
    },
    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()
        })
    },
    handleClear() {
      this.appModel.icon = ''
      this.image = ''
    },
    selectIcon(icon) {
      this.image = ''
      this.appModel.icon = icon
    },
    beforeClose() {
      this.dialogVisible = false
      Object.assign(this.$data, this.$options.data())
    },
    afterSaveData(data) {
      this.$emit('refresh')
      if (this.action === 'add') {
        this.$emit('after-add', data)
      }
      this.beforeClose()
    },
    beforeSaveData() {
      this.isSubmit = true
      if (!this.appModel.menuId) {
        this.$message.error('分类菜单为必填')
        this.isSubmit = false
        return
      }
      if (this.image) {
        this.appModel.icon = this.image
      }
    },
    handleColor(color) {
      this.appModel.iconColor = color
    },
    normalizer(node) {
      return {
        id: node.id,
        label: node.name,
        children: node.children,
        isDefaultExpanded: false,
      }
    },
    loadMenus() {
      this.$store.dispatch('menu/getAppTypes')
    },
    handleUploadResult(data) {
      if (data.success) {
        this.appModel.fileInfo = JSON.stringify(data)
      } else {
        this.$message.error('上传失败')
      }
      this.fullscreenLoading = false
    },
    onExceed(files) {
      this.$refs.uploadRef.clearFiles()
      this.$nextTick(() => {
        this.$refs.uploadRef.handleStart(files[0])
        this.$refs.uploadRef.submit()
      })
    },
    beforeUpload(file) {
      this.fullscreenLoading = true
    },
    onRemove(file) {
      this.appModel.fileInfo = null
    },
  },
}
</script>

<style lang="scss" scoped>
.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: 5px;
    text-align: center;
  }
}
.icon-select_wrap {
  margin: 0 16px;
  flex: 0 0 87px;
  height: 34px;
}
.layout_md {
  vertical-align: middle;
  /deep/.el-color-picker__trigger {
    border-color: #dcdfe6;
  }
}
::v-deep {
  .el-dialog__footer {
    text-align: right;
  }
}

::v-deep .el-upload-list__item {
  max-width: 456px;
}

.default-color--list {
  display: flex;
  margin-top: 10px;
  .color-item {
    margin-right: 8px;
    height: 24px;
    width: 24px;
    border-radius: 4px;
    cursor: pointer;
  }
}
</style>
