<template>
  <!-- 本地挂接 -->
  <el-dialog title="本地挂接" :close-on-click-modal="false" :modal-append-to-body="false" append-to-body :visible.sync="localHitchVisible" :before-close="handleCancel" @opened="opened">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="重复验证方式" prop="checkRepeatType">
        <el-select v-model="form.checkRepeatType" placeholder="请选择" style="width: 400px;">
          <el-option
            v-for="item in typeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="挂接字段" prop="hitchFiled">
        <el-select v-model="form.hitchFiled" placeholder="请选择" style="width: 400px;" @change="selectFiled">
          <el-option
            v-for="item in fieldOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="挂接详情" prop="fields">
        <div class="tag-wrapper">
          <el-tag v-for="item in hitchRemarkArray" :key="item" :closable="item !== '*'" @close="removeTag(item)">
            {{ item }}
          </el-tag>
        </div>
        <el-input v-model="form.fields" style="display: none;" type="hidden" />
      </el-form-item>
      <el-form-item label="匹配模式" prop="matchingMode">
        <el-select v-model="form.matchingMode" placeholder="请选择" style="width: 400px;" @change="changeMatchedType">
          <el-option
            v-for="item in matchedOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-if="!connectionType" label="上传附件" prop="file">
        <div class="upload-bgColor">
          <input class="upload-input" type="file" accept=".zip" style="width: 110px; height: 32px;" @change="handleFile">
          <el-button size="small" type="primary"><i class="iconfont icon-shangchuan" />点击上传</el-button>
        </div>
        <!-- <div class="file-list">
          <i class="iconfont icon-xiaowenjian" />
          {{ form.file && form.file.name }}
        </div> -->
        <div v-for="item in fileList" :key="item.name" class="file-list">
          <i class="iconfont icon-xiaowenjian" />
          {{ item.name }}
        </div>
        <el-input v-show="false" v-model="form.file" />
      </el-form-item>
      <el-form-item v-if="connectionType" label="挂接类型" prop="batchType">
        <el-select v-model="form.batchType" placeholder="请选择" style="width: 400px;">
          <el-option
            v-for="item in batchTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-if="connectionType" label="文件路径" prop="filePath">
        <el-input v-model="form.filePath" style="width: 400px;" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="text" @click="handleCancel">取消</el-button>
      <el-button type="primary" @click.native="handleComfired">确定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { crud } from '@crud/crud'
import { FetchInitCategoryInputFieldByPid } from '@/api/system/category/category'
import { batchMountUpload } from '@/utils/upload'
import { mapGetters } from 'vuex'
export default {
  name: 'LocalHitch',
  components: { },
  mixins: [crud()],
  props: {
    currentCategory: {
      type: Object,
      default: function() {
        return {}
      }
    }
  },
  data() {
    return {
      localHitchVisible: false,
      hitchRemarkArray: [],
      connectionType: 0,
      form: {
        checkRepeatType: null,
        hitchFiled: null,
        matchingMode: 1,
        fields: null,
        file: null,
        batchType: null,
        filePath: null
      },
      fileList: [],
      typeOptions: [
        {
          value: 1,
          label: '跳过'
        },
        {
          value: 2,
          label: '覆盖'
        },
        {
          value: 3,
          label: '追加'
        }
      ],
      matchedOptions: [
        {
          value: 1,
          label: '全量匹配'
        },
        {
          value: 2,
          label: '前缀模糊匹配'
        },
        {
          value: 3,
          label: '后缀模糊匹配'
        }
      ],
      batchTypeOptions: [
        {
          value: 1,
          label: '服务端挂接'
        },
        {
          value: 2,
          label: 'FTP挂接'
        },
        {
          value: 3,
          label: 'SFTP挂接'
        }
      ],
      fieldOptions: [],
      rules: {
        checkRepeatType: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        hitchFiled: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        fields: [
          { required: true, message: '请选择上面挂接字段生成挂接详情', trigger: 'blur' }
        ],
        matchingMode: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        batchType: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        filePath: [
          { required: true, message: '请选择', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters([
      'baseApi'
    ]),
    collectLevel() {
      if (this.currentCategory.arrangeType === 1) {
        return 3
      } else if (this.currentCategory.arrangeType === 2) {
        return 2
      } else if (this.currentCategory.arrangeType === 3) {
        return 1
      }
      return null
    }
  },
  created() {
  },
  mounted() {
  },
  methods: {
    opened() {
      this.getFieldCommon()
    },
    handleFile(event) {
      const files = event.target.files
      for (let i = 0; i < files.length; i++) {
        this.fileList = []
        this.fileList.push(files[i])
      }
    },
    handleComfired() {
      if (this.fileList.length === 0) {
        this.$message({ message: '请先选择相关文件！', offset: 8 })
        return false
      }

      if (this.hitchRemarkArray.length === 1 && this.hitchRemarkArray[0] === '*') {
        this.form.fields = ''
      } else {
        this.form.fields = this.hitchRemarkArray.join('')
      }

      this.$refs['form'].validate((valid) => {
        if (valid) {
          let newhitchRemark = this.hitchRemarkArray.map(item => item.replace(/^\$|\$$|\*$/g, ''))
          newhitchRemark = newhitchRemark.filter(item => item !== '')
          const params = {
            'categoryId': this.currentCategory.id,
            'mountType': 1, // 挂接方式  1.本地挂接 2.远程挂接 3.上传目录 （目前只有1）
            'checkRepeatType': this.form.checkRepeatType,
            'matchingMode': this.form.matchingMode,
            'fields': newhitchRemark
          }
          console.log(params)
          batchMountUpload(this.baseApi + '/api/collect/batchMount',
            this.fileList,
            params
          ).then(res => {
            if (res.data.code === 200) {
              this.$message({ message: '操作成功', type: 'success', offset: 8 })
            } else {
              this.$message({ message: '上传附件失败', type: 'error', offset: 8 })
            }
            this.handleCancel()
            this.crud.refresh()
          })
        } else {
          return false
        }
      })
    },
    getFieldCommon() {
      const params = {
        'categoryId': this.currentCategory.id,
        'categoryLevel': this.collectLevel
      }
      FetchInitCategoryInputFieldByPid(params).then(data => {
        this.fieldOptions = data.map((item, index) => {
          const json = {}
          json.id = item.id
          json.label = item.fieldCnName
          json.value = item.fieldName
          return json
        })
      })
    },
    selectFiled(val) {
      if (val) {
        if (this.hitchRemarkArray && this.hitchRemarkArray.includes('$' + val + '$')) {
          this.$message({ message: '请注意当前选择的挂接字段，在挂接详情内已存在！', offset: 8 })
        } else {
          const lastItemIndex = this.hitchRemarkArray.length - 1
          const index = this.hitchRemarkArray.indexOf('*')
          if (index !== -1) {
            if (index === lastItemIndex) {
              if (this.form.matchingMode === 2) {
                this.hitchRemarkArray.unshift('$' + val + '$')
              } else if (this.form.matchingMode === 3) {
                this.hitchRemarkArray.push('$' + val + '$')
              } else {
                this.hitchRemarkArray.splice(index > 0 ? index : 0, 0, '$' + val + '$')
              }
            } else {
              this.hitchRemarkArray.push('$' + val + '$')
            }
          } else {
            this.hitchRemarkArray.push('$' + val + '$')
          }
        }
      }
    },
    changeMatchedType(val) {
      const symbol = '*'
      const index = this.hitchRemarkArray.indexOf(symbol)
      if (index !== -1) {
        this.hitchRemarkArray.splice(index, 1)
      }
      if (val === 2) {
        this.hitchRemarkArray.push(symbol)
      } else if (val === 3) {
        this.hitchRemarkArray.unshift(symbol)
      }
    },
    removeTag(tag) {
      const index = this.hitchRemarkArray.indexOf(tag)
      if (index !== -1) {
        this.hitchRemarkArray.splice(index, 1)
      }
    },
    handleCancel() {
      this.$refs.form.resetFields()
      this.hitchRemarkArray = []
      this.fileList = []
      this.localHitchVisible = false
    }
  }
}
</script>

<style lang='scss' scoped>
::v-deep .el-dialog{
  width: 585px !important;
  .el-dialog__body{
    padding: 30px 0 !important;
  }
}
.dialog-footer{
  margin-top: 0;
}

.file-list{
  width: 400px;
  font-size: 12px;
  color: #A6ADB6;
}
.tag-wrapper{
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
  width: 400px;
  min-height: 32px;
  padding: 0 10px;
  border-radius: 3px;
  border: 1px solid #e6e8ed;
  .el-tag{
    margin-right: 6px;
  }
}
</style>
