<template>
  <div>
    <el-dialog
      id="editMod"
      :close-on-click-modal="false"
      :visible.sync="show"
      :before-close="handleClose"
      :title="title"
      :width="width"
      @close="close"
    >
      <div v-loading="loadingHand">
        <el-form
          ref="form"
          :model="form"
          label-position="right"
          :rules="rules"
          :label-width="labelWidth"
          label-suffix="："
        >

          <template v-if="mode==='edit' || mode==='add'">
            <el-col v-for="(item,index) in modeOptions" v-show="item.type!=='hidden'" :key="index" :span="item.width ? 0.24*item.width:24">
              <el-form-item :prop="item.prop || item.key" :label="item.label" :rules="item.rules" :label-width="item.labelWidth ? item.labelWidth :labelWidth">
                <el-select v-if="item.type=='select'" v-model.trim="form[item.key]" :placeholder="getPlaceholderMsg(item)" filterable>
                  <el-option
                    v-for="select in item.selectList"
                    :key="select[item.selectKey? item.selectKey:'id']"
                    :label="select[item.selectLabel ? item.selectLabel:'label']"
                    :value="select[item.selectValue ? item.selectValue:'value']"
                  />
                </el-select>
                <dictSelect v-else-if="item.type == 'dictSelect'" v-model.trim="form[item.key]" :code="item.dictCode" :label-key="item.selectLabel || 'myname'" :value-key="item.selectValue || 'mycode'" />
                <el-radio-group v-else-if="item.type=='radio'" v-model.trim="form[item.key]">
                  <el-radio
                    v-for="select in item.selectList"
                    :key="select[item.selectValue? item.selectValue:'value']"
                    :label="select[item.selectLabel ? item.selectLabel:'value']"
                  >{{ select[item.selectValue ? item.selectValue:'label'] }}</el-radio>
                </el-radio-group>
                <el-checkbox-group v-else-if="item.type=='checkbox'" v-model.trim="form[item.key]">
                  <el-checkbox
                    v-for="select in item.selectList"
                    :key="select[item.selectValue? item.selectValue:'value']"
                    :label="select[item.selectLabel ? item.selectLabel:'value']"
                    :disabled="!!item.disabled"
                  >
                    {{ select[item.selectValue ? item.selectValue:'label'] }}
                  </el-checkbox>
                </el-checkbox-group>
                <el-date-picker
                  v-else-if="item.type=='date'"
                  v-model.trim="form[item.key]"
                  type="date"
                  :placeholder="getPlaceholderMsg(item)"
                  :value-format="item.formatDate?item.formatDate:'yyyy-MM-dd'"
                />
                <el-upload
                  v-else-if="item.type=='image'"
                  ref="upload"
                  multiple
                  :on-success="handleExceed"
                  :http-request="(file)=>uploadFile(file,form[item.key])"
                  :before-upload="beforeUpload"
                  :show-file-list="false"
                >
                  <div slot="trigger" @click.stop="()=>{}">
                    <div
                      v-for="(image,imageIndx) in form[item.key]"
                      :key="(image && image.url) ? image.url : image"
                      style="display: inline-block;vertical-align: top;position: relative;"
                    >
                      <el-image
                        style="width: 100px; height: 100px"
                        :src="(image && image.url) ? image.url : image"
                        :preview-src-list="[(image && image.url) ? image.url : image]"
                      />
                      <div class="icon">
                        <i class="el-icon-error" @click="deleteImg(imageIndx,form[item.key])" />
                      </div>
                    </div>
                    <div class="photo" @click="addImage">
                      <i class="el-icon-plus" />
                    </div>
                  </div>
                </el-upload>
                <span v-else-if="item.type=='hidden'" />
                <slot v-else-if="item.type=='slot'" :row="form" :name="item.slotName" />
                <el-input
                  v-else-if="item.type=='textarea'"
                  v-model.trim="form[item.key]"
                  :placeholder="getPlaceholderMsg(item)"
                  :rows="item.rows || 4"
                  resize="none"
                  type="textarea"
                  :maxlength="item.maxlength || 100"
                  show-word-limit
                />
                <el-input
                  v-else
                  v-model.trim="form[item.key]"
                  :placeholder="getPlaceholderMsg(item)"
                />
              </el-form-item>
            </el-col>
          </template>
          <template v-else-if="mode==='see'">
            <el-col v-for="(item,index) in modeOptions" :key="index" :span="item.width ? 0.24*item.width:24">
              <el-form-item :prop="item.prop || item.key" :label="item.label" :rules="item.rules" :label-width="item.labelWidth ? item.labelWidth : labelWidth">
                <template v-if="item.type=='select'">
                  {{ getSelectData(form[item.key],item.selectList,item.selectKey? item.selectKey:'id',item.selectLabel ? item.selectLabel:'label') }}
                </template>
                <template v-else-if="item.type=='radio' || item.type=='checkbox'">
                  {{ getSelectData(form[item.key],item.selectList,item.selectLabel ? item.selectLabel:'value',item.selectKey? item.selectKey:'label') }}
                </template>
                <template v-else-if="item.type=='date'">
                  {{ form[item.key] }}
                </template>
                <template v-else-if="item.type=='image'">
                  <div
                    v-for="(image) in form[item.key]"
                    :key="(image && image.url) ? image.url : image"
                    style="display: inline-block;vertical-align: top;position: relative;"
                  >
                    <el-image
                      style="width: 100px; height: 100px"
                      :src="(image && image.url) ? image.url : image"
                      :preview-src-list="[(image && image.url) ? image.url : image]"
                    />
                  </div>
                </template>
                <slot v-else-if="item.type=='slot'" :row="form" :name="item.slotName" />
                <template v-else>
                  {{ form[item.key] }}
                </template>
              </el-form-item>
            </el-col>
          </template>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="close">取消</el-button>
        <el-button
          :loading="loadingHand"
          type="primary"
          @click="submit"
        >确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { upload } from '@/api/equipment/model'

export default {
  model: {
    prop: 'show',
    event: 'change'
  },
  props: {
    show: { // 弹窗显示
      type: Boolean,
      default: false
    },
    title: { // 弹窗标题
      type: String,
      default: ''
    },
    width: { // 弹窗宽度
      type: String,
      default: '700px'
    },
    mode: { // 表单模式 see查看 edit编辑
      type: String,
      default: 'see'
    },
    data: { // 表单数据
      type: Object,
      default: () => ({})
    },
    options: { // 表单配置列表
      type: Array,
      default: () => []
    },
    labelWidth: { // 表单字段宽度
      type: String,
      default: '160px'
    },
    rules: { // 总表单校验规则
      type: Object,
      default: () => ({})
    },
    loading: { // 表单加载效果
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      list: [],
      form: {},
      loadingHand: false,
      debounceTime: null
    }
  },
  computed: {
    modeOptions() {
      return this.options.filter(opt => !opt.mode || opt.mode.includes(this.mode))
    }
  },
  watch: {
    loading(value) {
      this.loadingHand = value
      this.$nextTick(() => {
        const dom = document.querySelector('#editMod').querySelector('.el-dialog__body')
        const height = dom.clientHeight
        const width = dom.clientWidth
        this.$nextTick(() => {
          const markDom = document.querySelector('#editMod').querySelector('.el-loading-mask')
          if (width > 0 && markDom) {
            markDom.style.width = width - 30 + 'px'
            markDom.style.height = height - 30 + 'px'
          }
        }, 300)
      })
    },
    show(value) {
      if (value) {
        this.$emit('open')
        this.form = { ...this.data }
        console.log(`editMode:show`, this.form)
        this.$emit('dataChange', this.form)
      } else {
        this.init()
      }
    },
    data(value) {
      const form = {}
      this.modeOptions.forEach(item => {
        if (value[item.key] !== undefined) {
          if (value[item.key] === null && (item.type === 'checkbox' || item.type === 'image')) {
            form[item.key] = []
          } else {
            form[item.key] = value[item.key]
          }
        } else {
          if (item.type === 'checkbox' || item.type === 'image') {
            form[item.key] = []
          } else {
            form[item.key] = ''
          }
        }
      })
      this.form = form
      this.$emit('dataChange', this.form)
    }
  },
  created() {
  },
  mounted() {
  },
  methods: {

    deepClone(obj, hash = new WeakMap()) {
      if (obj == null || typeof obj !== 'object') return obj

      if (obj instanceof Date) return new Date(obj)

      if (obj instanceof RegExp) return new RegExp(obj)

      if (hash.has(obj)) return hash.get(obj)

      const t = new obj.constructor()
      hash.set(obj, t)

      for (const key in obj) {
        if (obj.hasOwnProperty(key)) {
          t[key] = this.deepClone(obj[key], hash)
        }
      }

      return t
    },
    getSelectData(key, array, selectKey, selectLabel) {
      if (!Array.isArray(array)) {
        return key
      }
      if (Array.isArray(key)) {
        const arr = []
        key.forEach(item => {
          arr.push(this.getSelectData(item, array, selectKey, selectLabel))
        })
        return arr.length === 0 ? '-' : arr.join(',')
      }
      const result = array.find(item => item[selectKey] == key)
      return result ? result[selectLabel] : key
    },
    addImage() {
      this.$nextTick(() => {
        this.$refs['upload'][0].$children[0].$refs.input.click()
      })
    },
    deleteImg(index, list) {
      list.splice(index, 1)
    },
    async uploadFile(file, list) {
      this.uploadLoading = true
      const formData = new FormData()
      formData.append('file', file.file)
      const bucket = 'fsmodel'
      formData.append('bucket', bucket)
      const content = await upload(formData)
      this.uploadLoading = false
      list.push(
        {
          name: 'image',
          url: content.data
        }
      )
      this.$message({ type: 'success', offset: 60, message: '上传成功' })
    },
    handleExceed(response, file, fileList) {
      this.$refs.batchAddForm?.validateField('file')
    },
    getPlaceholderMsg(data) {
      if (data.type == 'input') {
        return '请输入' + data.label
      }
      if (data.type == 'select' || data.type == 'checkbox' || data.type == 'date') {
        return '请选择' + data.label
      }
    },
    init() {
      this.$refs.form.resetFields()
    },
    submit() {
      if (this.mode === 'see') {
        this.$emit('submit', this.form, this.data)
      } else {
        console.log('FORM', this.form, this.data)
        this.$refs.form.validate((valid) => {
          if (valid) {
            const form = this.deepClone(this.form)
            if (this.debounceTime) {
              clearTimeout(this.debounceTime)
            }
            this.debounceTime = setTimeout(() => {
              this.$emit('submit', form, this.data)
            }, 300)
          }
        })
      }
    },
    close() {
      this.init()
      this.$emit('close', this.form)
    },
    clearValidate() {
      this.$refs.form.clearValidate()
    }
  }
}
</script>
<style lang="scss" scoped>
.photo{
  width: 33.33px;
  height: 33.33px;
  align-content: center;
  border: 1px dashed #dfe3e9;
  color: #dfe3e9;
  display: inline-block;
vertical-align: top;
position: relative;
zoom: 3;
padding-top:7px;
}
.icon{
  position: absolute;
  right: 0px;
  top: 0;
  width: 30px;
  height: 30px;
  color: red;
  font-size: 17px;
}
</style>
