<template>
  <!-- 表单 -->
  <div class="card_employee">
    <el-form ref="ruleForm" :label-position="labelPosition" :model="ruleForm" :label-width="labelWidth">
      <el-row :gutter="10">
        <el-col :span="item.colWidth" v-for="(item, index) in formList" :key="index">
          <el-form-item class="card_independent" :label-width="item.labelWidth" :label="item.label" :prop="item.field"
            :rules="detail ? item.rules : {}" v-if="item.type === 'input'">
            <el-input :placeholder="item.placeholder" :disabled="item.disabled" :id="item.field"
              v-model="ruleForm[`${item.field}`]"></el-input>
            <div class="unit_card" v-if="item.unit">{{item.unit}}</div>
          </el-form-item>
          <el-form-item :label-width="item.labelWidth" :label="item.label" :prop="item.field"
            :rules="detail ? item.rules : {}" v-if="item.type === 'textarea'">
            <el-input :maxlength="item.maxLenght" type="textarea" :rows="item.rowsHeight" :disabled="item.disabled"
              :id="item.field" :placeholder="item.placeholder" v-model="ruleForm[`${item.field}`]" />
          </el-form-item>
          <el-form-item :label-width="item.labelWidth" :label="item.label" :prop="item.field"
            :rules="detail ? item.rules : {}" v-if="item.type === 'select'">
            <el-select :id="item.field" v-model="ruleForm[`${item.field}`]" :placeholder="item.placeholder"
              :disabled="item.disabled" :multiple="item.multiple" style="width: 100%"
              @change="(params) => changeSelect(params,item.field)">
              <el-option v-for="(element, i) in item.options" :label="element.label" :value="`${element.value}`"
                :key="i">
                <span style="float: left">{{ element.label }}</span>
                <span style="float: right; color: #409EFF; font-size: 13px" v-if="element.IsBind">已绑定</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label-width="item.labelWidth" :label="item.label" :prop="item.field"
            :rules="detail ? item.rules : {}" v-if="item.type === 'searchSelect'">
            <el-select :id="item.field" v-model="ruleForm[`${item.field}`]" filterable remote
              :remote-method="remoteMethod" :placeholder="item.placeholder" :disabled="item.disabled"
              style="width: 100%">
              <el-option v-for="(element, i) in item.options" :label="element.label" :value="`${element.value}`"
                :key="i" />
            </el-select>
          </el-form-item>
          <el-form-item :label="item.label" :prop="item.field" :rules="detail ? item.rules : {}"
            v-if="item.type === 'cascader'">
            <el-cascader v-model="ruleForm[`${item.field}`]" :disabled="item.disabled" :options="item.options">
            </el-cascader>
          </el-form-item>
          <el-form-item :label="item.label" :prop="item.field" :rules="detail ? item.rules : {}"
            v-if="item.type === 'radio'">
            <div style="display: flex;height: 40px;align-items: center;">
              <el-radio-group v-model="ruleForm[`${item.field}`]" :disabled="item.disabled" @input="radioInput">
                <el-radio v-for="(element, i) in item.options" :key="i"
                  :label="element.value">{{element.label}}</el-radio>
              </el-radio-group>
            </div>
          </el-form-item>
          <el-form-item :label="item.label" :prop="item.field" :rules="detail ? item.rules : {}"
            v-if="item.type === 'time'">
            <el-date-picker type="date" value-format="yyyy-MM-dd" v-model="ruleForm[`${item.field}`]"
              :placeholder="item.placeholder" :disabled="item.disabled">
            </el-date-picker>
          </el-form-item>
          <el-form-item :label="item.label" :prop="item.field" :rules="detail ? item.rules : {}"
            v-if="item.type === 'section'">
            <el-date-picker align="center" v-model="ruleForm[`${item.field}`]" :disabled="item.disabled"
              type="datetimerange" value-format="yyyy-MM-dd HH:mm:ss" range-separator="至" start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>
          <div v-if="item.type === 'divider'">
            <div v-if="item.label">{{item.label}}</div>
            <el-divider></el-divider>
          </div>
          <div style="height: 40px;display: flex;align-items: center;" v-if="item.type === 'search'">
            <el-button size="small" type="primary" :loading="curLoading" :disabled="item.disabled"
              @click="numberSearch">{{item.label}}</el-button>
          </div>
          <div style="height: 10px;width: 100%;" v-if="item.type === 'dividingSlot'"></div>
          <el-form-item class="card_descriptions" :label="item.label" :prop="item.field"
            :rules="detail ? item.rules : {}" v-if="item.type === 'descriptions'">
            <span class="descriptions_title">{{ruleForm[`${item.field}`] || ''}}
              <span class="descriptions_badge center_in" v-if="item.field == 'name'">商户</span>
              <span v-if="item.field == 'quantity'">瓶</span>
            </span>
          </el-form-item>
          <el-form-item class="card_descriptions" :label="item.label" :prop="item.field"
            :rules="detail ? item.rules : {}" v-if="item.type === 'prdfterence'">
            <span class="descriptions_title"
              :style="{color: filterColor(ruleForm,item.options,item.field)}">{{initDictvalueil(ruleForm[`${item.field}`],item.options)}}</span>
          </el-form-item>
          <!-- 单张图片上传 -->
          <el-form-item :class="item.crosswise ? '' : 'card_fuel_gas'" :label="item.label" :prop="item.field"
            :rules="detail ? item.rules : {}" v-if="item.type === 'singleUpload'">
            <el-upload class="avatar-uploader" action="#" :show-file-list="false" :disabled="item.disabled"
              :http-request="(params) => singleUpload(params,item.field)">
              <img v-if="ruleForm[`${item.field}`]" :src="$baseUrl + ruleForm[`${item.field}`]" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <!-- 可以上传多张 -->
          <div v-if="item.type === 'upload'">
            <div class="card_purple">
              <el-form-item ref="headimgUpload" :class="item.crosswise ? '' : 'card_fuel_gas'" class="margin-l-50"
                :label="item.label" :prop="item.field" :rules="detail ? item.rules : {}">
                <el-upload action="#" list-type="picture-card" :file-list="ruleForm.fileList" :disabled="item.disabled"
                  :http-request="UploadImage" v-if="operationType != 'logs'">
                  <i slot="default" class="el-icon-plus"></i>
                  <div slot="file" slot-scope="{file}">
                    <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
                    <span class="el-upload-list__item-actions">
                      <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                        <i class="el-icon-zoom-in"></i>
                      </span>
                      <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
                        <i class="el-icon-delete"></i>
                      </span>
                    </span>
                  </div>
                </el-upload>
                <div class="card_image" v-else>
                  <div v-for="(item,index) in ruleForm.fileList" :key="index">
                    <img class="avatar_image" :src="item.url" alt="" />
                    <!-- <el-image class="avatar_image" :src="item.url" :preview-src-list="[item.url]">
                      <div slot="placeholder" class="image-slot">
                        加载中<span class="dot">...</span>
                      </div>
                    </el-image> -->
                  </div>
                </div>
                <el-dialog :visible.sync="dialogVisible" append-to-body>
                  <img width="100%" :src="dialogImageUrl" alt="">
                </el-dialog>
              </el-form-item>
            </div>
          </div>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
  // import {
  //   getFileToken,
  // } from '@/api/user'
  export default {
    name: "forms",
    props: {
      // 表单tabel数据
      formNewList: {
        type: Array,
        default: () => [],
      },
      // 表单label宽度
      labelWidth: {
        type: String,
        default: () => '120px',
      },
      // 对齐方式
      labelPosition: {
        type: String,
        default: () => 'right',
      },
      // 绑定值
      ruleForm: {
        type: Object,
        default: () => {},
      },
      operationType: {
        type: String,
        default: () => '',
      },
    },
    watch: {
      formNewList: {
        immediate: true, // 立即触发监听函数
        handler() {
          this.formList = this.formNewList;
        },
      },
    },
    data() {
      return {
        detail: true,
        formList: [],
        imageUrl: '',
        file: null,
        dialogImageUrl: '',
        dialogVisible: false,
        disabled: false,
        fileList: [],
        curLoading: false,
      }
    },
    methods: {
      //下拉框下拉事件
      changeSelect(row, field) {
        this.$forceUpdate()
        this.$emit("changeSelect", row, field);
      },
      // 重置校验
      resetCheck() {
        this.$refs.ruleForm.resetFields();
      },
      // 单个图片上传
      singleUpload(file, value) {
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        this.file = file.file;
        let formData = new FormData();
        formData.append('file', this.file);
        getFileToken(formData).then(res => {
          if (res.code == 200) {
            this.ruleForm[`${value}`] = res.data
            this.$forceUpdate()
          }
          loading.close();
        }).catch(e => {
          loading.close();
          this.$message.error('上传失败');
        })
      },
      // 上传文件
      UploadImage(file) {
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        this.file = file.file;
        let formData = new FormData();
        formData.append('file', this.file);
        getFileToken(formData).then(res => {
          if (res.code == 200) {
            let arr1 = {
              uid: this.file.uid,
              url: '',
            }
            arr1.url = this.$baseUrl + res.data
            this.ruleForm.fileList.push(arr1)
          }
          loading.close();
        }).catch(e => {
          loading.close();
          this.$message.error('上传失败');
        })
      },
      // 手机号搜索
      numberSearch() {
        const flag = false
        this.$refs['ruleForm'].validateField('phone', valid => {
          if (!valid) {
            this.curLoading = true
            this.$emit('numberSearch', this.ruleForm.phone)
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      // 单选选择
      radioInput(label) {
        this.$emit('radioInput', label)
      },
      // tag颜色获取
      filterColor(value, list, type) {
        let color = ''
        list.forEach(item => {
          if (value[type] === item.value) {
            color = item.bgcolor
          }
        })
        return color
      },
      // 普通类型文字匹配
      initDictvalueil(value, list) {
        let name = ''
        list.forEach(item => {
          if (value == item.value) {
            name = item.label
          }
        })
        return name
      },
      handleScroll() {
        // console.log('触底了')
        this.$emit('handleScroll')
      },
      remoteMethod(val) {
        // console.log('远程搜索', val)
        this.$emit('remoteMethod', val)
      },
      // 删除
      handleRemove(file) {
        const filteredArr = this.ruleForm.fileList.filter(obj => obj.uid !== file.uid);
        this.ruleForm.fileList = filteredArr
        this.$forceUpdate()
      },
      // 查看
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },
      //子组件校验，传递到父组件
      validateForm() {
        let flag = null
        this.$refs['ruleForm'].validate(valid => {
          if (valid) {
            flag = true
          } else {
            flag = false
          }
        })
        return flag
      }
    }
  }
</script>

<style lang="scss" scoped>
  .card_employee {
    max-height: 600px;
    overflow-y: auto;
    overflow-x: hidden;
  }

  .margin-l-50 {
    margin-right: 50px;
  }

  .card_fuel_gas {
    display: flex;
    flex-direction: column;
  }

  .card_fuel_gas ::v-deep .el-form-item__label {
    width: 150px !important;
    text-align: left;
    // margin-bottom: 20px;
  }

  .card_descriptions {
    margin-bottom: 10px !important;
  }

  .card_descriptions ::v-deep .el-form-item__label {
    text-align: left;
  }

  .card_fuel_gas ::v-deep .el-form-item__content {
    margin-left: 0px !important;
  }

  .card_purple {
    display: flex;
  }

  .descriptions_title {
    position: relative;
  }

  .descriptions_badge {
    position: absolute;
    width: fit-content;
    width: -webkit-fit-content;
    width: -moz-fit-content;
    top: -10px;
    right: -35px;
    color: #169BD5;
    font-size: 12px;
    line-height: 14px;
    padding: 2px;
    border: 1px solid #169BD5;
  }

  .unit_card {
    width: 80px;
    padding-left: 10px;
    flex: none;
  }

  .card_independent ::v-deep .el-form-item__content {
    display: flex !important;
  }

  .card_image {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
  }

  .avatar_image {
    width: 140px;
    height: 140px;
    border-radius: 6px;
    margin: 0 8px 8px 0;
  }
</style>
