<template>
  <div>
    <el-dialog custom-class="customClass" :visible.sync="areaVisibleCopy" :title="modalTypeText[modalType]"
      @close="closeModal" :close-on-click-modal="false" :close-on-press-escape="false">

      <!-- 挂载和修改   -->
      <div class="right">
        <el-form :model="dataForm" :rules="rules" ref="dataForm" @keyup.enter.native="dataFormSubmitHandle()"
          :label-width="$i18n.locale === 'en-US' ? '120px' : '100px'">
          <!-- 基本信息 -->
          <div class="scrollBox" id="anchor1">

            <div class="baseInner">
              <el-form-item label="所属区市:" prop="unit">
                <el-select v-model="dataForm.area" placeholder="请选择">
                  <el-option v-for="item in areas" :key="item.data" :label="item.name"
                    :value="item.name"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="赋能领域:" prop="unit">
                <el-select v-model="dataForm.applicationArea" placeholder="请选择">
                  <el-option v-for="item in sceneAreas" :key="item.data" :label="item.dict_label"
                    :value="item.dict_label"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="场景名称:" prop="name">
                <el-input v-model="dataForm.name" placeholder="请输入名称" style="width:90%"></el-input>
              </el-form-item>

              <el-form-item label="场景描述:" prop="description">
                <el-input type="textarea" :rows="3" v-model="dataForm.description" placeholder="请输入描述"
                  style="width:90%">
                </el-input>
              </el-form-item>
              <el-form-item label="场景入口:">
                <el-input v-model="dataForm.sceneUrl" placeholder="请输入场景入口" style="width:90%"></el-input>
              </el-form-item>

              <el-form-item label="场景图片:">
                <el-upload ref="editUpload" class="upload-demo" :action="fileUploadUrl"
                  :on-success="eidtHandleAvatarSuccess" :before-upload="editBeforeAvatarUpload" :limit="1"
                  :file-list="[]" :on-remove="editUploadRemoveFile" :on-exceed="handleExceed" list-type="picture">
                  <div slot="tip" class="el-upload__tip">只能上传图片文件，格式为jpg/png</div>
                  <div class="button-new">
                    <div>点击上传</div>
                  </div>

                  <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                </el-upload>
              </el-form-item>
            </div>
          </div>

        </el-form>
      </div>
      <template slot="footer">
        <el-button @click="closeModal">{{ $t("cancel") }}</el-button>
        <el-button type="primary" @click="dataFormSubmitHandle()">提交</el-button>

      </template>
    </el-dialog>
  </div>
</template>

<script>
import debounce from 'lodash/debounce'
import qs from 'qs'
import Cookies from 'js-cookie'
import upload from '@/views/modules/components/upload'

// 模态框标题
export const modalTypeText = {
  add: '场景挂接',
  update: '场景修改'
}

export default {
  components: {
    upload
  },
  watch: {

    dataForm: {
      handler (newVal) {
        this.dataForm = newVal
      },
      deep: true,
      immediate: true
    },
    areaVisible: {
      handler (newVal) {
        this.getSceneArea()
        this.getArea()
        this.areaVisibleCopy = newVal
        if (this.modalType == 'add' && newVal) {
          this.getDetail(this.dataForm)
        }
      },
      immediate: true
    }
  },
  props: {
    modalType: {
      type: String,
      default: 'add'
    },
    areaVisible: {
      type: Boolean,
      default: false
    }
  },

  data () {
    return {
      areas: [], // 所属区市
      sceneAreas: [],
      fileUploadUrl: window.SITE_CONFIG.apiURL + '/upload',
      dataForm: {
        district: 1, // 0市级，1基层
        area: '', // 所属区市
        infrastructureCount: null,
        dataSourceCount: null,
        componentCount: null,
        name: '',
        applicationArea: '', // 赋能领域
        description: '',
        sceneUrl: '',
        fuseAttrList: [
          {
            attrType: '构建步骤',
            attrValue: [{ question: '', answer: [{ answer: '' }, { answer: '' }] }]
          },
          {
            attrType: '基础设施',
            attrValue: [{ name: '', type: '', dept: '' }]
          },
          {
            attrType: '组件服务',
            attrValue: [{ name: '', type: '', dept: '' }]
          },
          {
            attrType: '数据资源',
            attrValue: [{ name: '', type: '', dept: '' }]
          },
          {
            attrType: '场景痛点',
            attrValue: [{ description: '' }]
          },
          {
            attrType: '解决方案',
            attrValue: [{ description: '' }]
          },
          {
            attrType: '服务图片',
            attrValue: ''
          }
        ]

      },
      rules: {
        name: [
          {
            required: true,
            message: '请输入名称',
            trigger: 'change'
          }
        ],
        description: [
          {
            required: true,
            message: '请输入描述',
            trigger: 'change'
          }
        ]
      },

      areaVisibleCopy: this.areaVisible,
      displayInfo: {
        name: '名称',
        description: '描述'
      },
      modalTypeText: modalTypeText,

      abilityListObj: {},
      imgData: [],
      // 限定图片
      handleExceed () {
        this.$message({ type: 'error', message: '最多支持一张图片上传' })
      },
      imageUrl: ''
    }
  },

  methods: {
    // 获取所属区市
    getArea () {
      const params = {
        pid: '250000'
      }
      this.$http
        .get('/sys/region/list/', {
          params
        })
        .then((res) => {
          this.areas = res.data.data
        })
    },
    // 获取赋能场景
    getSceneArea () {
      const params = {
        topCategoryName: '应用资源'
      }
      this.$http
        .get('/category/getAllFilterCriteriaByTopCategory/', {
          params
        })
        .then((res) => {
          this.sceneAreas = res.data.data[0].typeList
        })
    },

    clearForm () {
      this.$refs.dataForm && this.$refs.dataForm.resetFields()
    },
    closeModal () {
      this.$emit('closeModal')
    },

    // 表单提交
    dataFormSubmitHandle: debounce(
      function () {
        this.$refs.dataForm.validate((valid) => {
          if (!valid) {
            this.$message.error('请检查表单是否填写完整')
            return false
          }
          const methodsObj = {
            add: 'post',
            update: 'put'
          }

          // if (this.imageUrl == '') {
          //   this.$message.error('请上传图片！')
          //   return
          // }
          this.dataForm.fuseAttrList.find(v => v.attrType == '服务图片').attrValue = this.imageUrl || ''
          const _obj = Object.assign({}, this.dataForm, {
            type: '赋能场景'
          })

          this.dataForm.fuseAttrList.forEach(item => {
            if (item.attrType !== '服务图片') {
              item.attrValue = JSON.stringify(item.attrValue)
            }
          })
          this.$http
            [methodsObj[this.modalType]]('/fuse', _obj)
            .then(({ data: res }) => {
              if (res.code !== 0) {
                return this.$message.error(res.msg)
              }
              this.$message({
                message: this.$t('prompt.success'),
                type: 'success',
                duration: 500,
                onClose: () => {
                  this.$refs.dataForm && this.$refs.dataForm.resetFields()
                  this.$emit('refreshDataList')
                  this.$emit('closeModal')
                }
              })
            })
            .catch((err) => {
              this.$message.error(err)
            })
        })
      },
      1000,
      { leading: true, trailing: false }
    ),
    // 详情
    getDetail (data) {
      this.dataForm = data
        const _imgObj = data.fuseAttrList.find(v => v.attrType == '服务图片') || {}
        this.imageUrl = _imgObj.attrValue

    },
    handleAvatarSuccess (res, file) {
      if (res.code !== 0) {
        return this.$message.error(res.msg)
      }
      this.imageUrl = res.data
    },
    beforeAvatarUpload (file) {
      const isImage =
        file.type === 'image/jpeg' ||
        file.type === 'image/jpg' ||
        file.type === 'image/png'
      if (!isImage) {
        this.$message.error('上传图片只能是 jpg/png 格式!')
      }
      return isImage
    },
    addUploadRemoveFile (file, fileList) {
      this.$refs.addUpload.clearFiles()
      this.imageUrl = ''
    },
    editBeforeAvatarUpload (file) {
      const isImage =
        file.type === 'image/jpeg' ||
        file.type === 'image/jpg' ||
        file.type === 'image/png'

      if (!isImage) {
        this.$message.error('上传图片只能是 jpg/png 格式!')
      }
      return isImage
    },
    editUploadRemoveFile (file, fileList) {
      this.$refs.editUpload.clearFiles()
      this.imageUrl = ''
    },
    eidtHandleAvatarSuccess (res, file) {
      if (res.code !== 0) {
        return this.$message.error(res.msg)
      }
      this.imageUrl = res.data
    }
  },
  mounted () {
  },
  beforeDestroy () {
    this.clearForm()
  }
}
</script>

<style lang="scss" scoped>
.fixed {
  position: sticky;
  z-index: 10012;
  top: 0;
  left: 50%;
  margin-left: -9.56rem;
}

.button-new {
  height: 90px;
  width: 128px;
  border: 1px dashed rgba(198, 198, 198, 0.5);
  border-radius: 2px;
  background: #e9eff8;
  color: #666666;
  font-size: 14px;
  margin-right: 8px;
}

.button-new div {
  background: url('~@/assets/img/uploadAdd.png') no-repeat;
  color: #666666;
  background-position: center;
  text-align: center;
  height: 90px;
  padding-top: 41px;
  background-position-y: 22px;
}

.right {
  width: 770px;
  margin-left: 100px;
  margin-top: 24px;

  .info-inner {

    margin-left: 10px;

    margin-right: 10px;
  }

  .info-title {
    font-size: 14px;
    font-weight: bold;
  }

  .baseInfo {

    border-radius: 2px;

  }

  .baseTitle {
    padding-left: 20px;
    color: #212121;
    font-size: 16px;
    margin-bottom: 10px;
    margin-top: 32px;
    background: url("~@/assets/img/biaoti.png") no-repeat;
    background-position-y: 2px;

  }

  .baseInner {
    background: rgba(244, 245, 248, 0.8);
    padding: 24px 120px;
  }

  .baseInner1 {
    background: rgba(244, 245, 248, 0.8);
    padding: 24px 24px;
  }
}

::v-deep .el-dialog__header {
  background: #0058e1;
  // height: 50px;
}

::v-deep .el-dialog__title {
  line-height: 18px;
  font-size: 18px;
  color: #fff;
}

::v-deep .el-upload {
  display: inline-flex;
}

::v-deep .el-dialog__body {
  padding: 0px;
  height: 580px;
  overflow: auto;

}

.icon-input ::v-deep .el-input__inner {
  cursor: pointer;
}

.detial-form ::v-deep {
  .el-form-item {
    margin-bottom: 0px;
    line-height: 32px;
  }

  .el-form-item__label {
    line-height: 32px;
  }

  .el-form-item__content {
    line-height: 32px;
  }
}

::v-deep .el-checkbox-button__inner {
  width: 130px;
  margin: 0 10px 5px;
  border-left: unset !important;
  border-radius: unset !important;
  border: 1px solid #dcdfe6 !important;
}
</style>

<style lang="scss" scoped>
.mod-sys__menu {

  .menu-list,
  .icon-list {

    .el-input__inner,
    .el-input__suffix {
      cursor: pointer;
    }
  }

  &-icon-popover {
    width: 458px;
    overflow: hidden;
  }

  &-icon-inner {
    width: 478px;
    max-height: 258px;
    overflow-x: hidden;
    overflow-y: auto;
  }

  &-icon-list {
    width: 458px;
    padding: 0;
    margin: -8px 0 0 -8px;

    >.el-button {
      padding: 8px;
      margin: 8px 0 0 8px;

      >span {
        display: inline-block;
        vertical-align: middle;
        width: 18px;
        height: 18px;
        font-size: 18px;
      }
    }
  }
}

.previewImg {
  position: fixed;
  z-index: 9999;
}

.name {
  text-align: right;
  vertical-align: middle;
  font-size: 14px;
  color: #606266;
  line-height: 40px;
  padding: 0 12px 0 0;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  line-height: 32px;
  width: 120px;
}

.text {
  margin-left: 132px;
  font-size: 14px;
  color: #606266;
  line-height: 32px;
}

.title {
  text-align: center;
  font-weight: 600;
  font-size: 18px;
  margin-bottom: 10px;
}

.first-title {
  text-align: center;
  font-weight: 600;
  font-size: 18px;
  margin-bottom: 10px;
}

.avatar {
  height: 100px;
  width: 100px;
  display: block;
}
</style>
