<template>
  <!-- 表单 -->
  <div class="card_employee" :style="{maxHeight:beyondHeight}">
    <el-form ref="ruleForm" @submit.native.prevent :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}`]" auto-complete="new-password"
              :show-password="['newPassword','password'].includes(item.field) ? true : false"></el-input>
            <div class="unit_card" v-if="item.unit">{{item.unit}}</div>
          </el-form-item>
          <!-- 开关 -->
          <el-form-item class="card_independent" :label-width="item.labelWidth" :label="item.label" :prop="item.field"
            :rules="detail ? item.rules : {}" v-if="item.type === 'switch'">
            <div class="forms_switch">
              <el-switch v-model="ruleForm[`${item.field}`]" active-color="#13ce66"
                inactive-color="#ff4949"></el-switch>
            </div>
          </el-form-item>
          <!-- 扫描 -->
          <el-form-item class="card_independent" :label-width="item.labelWidth" :label="item.label" :prop="item.field"
            :rules="detail ? item.rules : {}" v-if="item.type === 'scan'">
            <el-input :placeholder="item.placeholder" :disabled="item.disabled" :id="item.field" v-model="inputs"
              @keyup.enter.native="serialNumber(item.field)" @focus="focus(item.field)" @input="iceRaftInput">
              <el-button slot="append" icon="el-icon-circle-plus icon_circle_btn"
                @click="serialNumber(item.field)"></el-button>
            </el-input>
            <div class="card_IceList" v-if="formIceTracing">
              <div class="ser_card_ial" v-for="(serial,num) in inputsList" :key="num">
                <div style="display: flex;align-items: center;">
                  <div>{{num + 1}}</div>
                  <div class="title_serial">{{serial}}</div>
                </div>
                <span class="del_serial" @click="delSerial(serial,num)">删除</span>
              </div>
            </div>
          </el-form-item>
          <div v-if="formIceTracing && item.type === 'scan'"
            :style="{height:scanHeight(inputsList.length),width:'100%'}"></div>
          <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}`]" v-loadmore="handleScroll" filterable remote
              :remote-method="(query) => remoteMethod(query, item.field)" :placeholder="item.placeholder"
              :disabled="item.disabled" style="width: 100%" @change="(row) => changeOption(row, item.field)">
              <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 ref="organizerUnit" checkStrictly v-model="ruleForm[`${item.field}`]" :disabled="item.disabled"
              :options="item.options" :props="item.props" :show-all-levels="item.levels"
              @change="(query) => handleChange(query, item.field)">
            </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-remove-hidden 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 === 'nvarchar' || item.type === 'nvarcharil'">
            <span class="descriptions_title" v-if="item.type === 'nvarchar'">{{ruleForm[`${item.field}`]}}</span>
            <span class="descriptions_title" :style="{color: filterColor(ruleForm,item.options,item.field)}"
              v-else-if="item.type === 'nvarcharil'">{{initDictvalueil(ruleForm,item.options,item.field)}}</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 style="display: flex;" 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-col :span="20" :offset="4" v-if="iceBank && !formIceTracing">
          <div style="display: flex;flex-direction: column;">
            <div class="ser_card_ial margin_around" v-for="(serial,num) in inputsList" :key="num">
              <div style="display: flex;align-items: center;">
                <div>{{num + 1}}</div>
                <div class="title_serial">{{serial}}</div>
              </div>
              <span class="del_serial" @click="delSerial(serial,num)">删除</span>
            </div>
          </div>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
  import {
    getFileToken,
  } from '@/api/login'
  import {
    getIceRaftCode,
  } from '@/api/iceRaft'
  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: () => '',
      },
      // 冰排冰库
      iceBank: {
        type: Boolean,
        default: () => false,
      },
      // 冰排追溯
      iceTracing: {
        type: Boolean,
        default: () => false,
      },
      // 表单冰排
      formIceTracing: {
        type: Boolean,
        default: () => false,
      },
      // 超出隐藏
      beyondHeight: {
        type: String,
        default: () => '530px',
      },
    },
    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,

        inputs: "",
        timearr: [0, 0],
        isScanningGun: false,
        inputsList: [],
        typeField: '',
      }
    },
    methods: {
      //下拉框下拉事件
      changeSelect(row, field) {
        this.$forceUpdate()
        this.$emit("changeSelect", row, field);
      },
      // 搜索选择
      changeOption(row, field) {
        this.$emit("changeOption", row, field);
      },
      // 重置校验
      resetCheck() {
        const that = this
        if (that.iceTracing) {
          that.inputs = ''
          that.inputsList = []
          checkType(that.ruleForm.code)

          function checkType(value) {
            if (typeof value === 'string') {
              that.ruleForm.code = ''
            } else if (Array.isArray(value)) {
              that.ruleForm.code = []
            } else {
              that.ruleForm.code = []
            }
          }
        }
        that.$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: res.data,
            }
            this.ruleForm.fileList.push(arr1)
          }
          loading.close();
        }).catch(e => {
          console.log(e, 23)
          loading.close();
          this.$message.error('上传失败');
        })
      },
      // 手机号搜索
      numberSearch() {
        let 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, type) {
        let name = ''
        if (list) {
          list.forEach(item => {
            if (value[type] === item.value) {
              name = item.label
            }
          })
        }
        return name
      },
      handleScroll() {
        // console.log('触底了')
        this.$emit('handleScroll')
      },
      remoteMethod(val, type) {
        // console.log('远程搜索', val, type)
        this.$emit('remoteMethod', val, type)
      },
      // 删除
      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;
      },
      // 添加编号
      serialNumber(field) {
        if (this.inputs) {
          getIceRaftCode(this.inputs).then(res => {
            if (res.code == 200) {
              this.inputsList.push(this.inputs)
              this.inputsList = this.uniqueArray(this.inputsList)
              this.inputs = ''
              this.ruleForm[`${field}`] = this.inputsList
            }
          })
        }
      },
      // 回车添加
      keydownBarcode(field) {
        if (this.inputs) {
          this.inputsList.push(this.inputs)
          this.inputsList = this.uniqueArray(this.inputsList)
          this.inputs = ''
          this.ruleForm[`${field}`] = this.inputsList
        }
      },
      // 输入
      iceRaftInput(value) {
        let arr = []
        arr.push(value)
        this.ruleForm.code = arr
      },
      // 去重
      uniqueArray(arr) {
        return [...new Set(arr)];
      },
      // 删除编号
      delSerial(value, index) {
        this.inputsList.splice(index, 1)
        this.ruleForm[`${this.typeField}`] = this.inputsList
        // this.ruleForm['code'].splice(index, 1);
      },
      focus(field) {
        this.typeField = field
      },
      // 级联选择器关闭
      handleChange(value, type) {
        if (this.$refs.organizerUnit) {
          this.$refs.organizerUnit[0].dropDownVisible = false
        }
      },
      scanHeight(num) {
        let arr = '0px'
        if (num < 4) {
          arr = num * 45 + 'px'
        } else {
          arr = 3 * 45 + 'px'
        }
        return arr
      },
      //子组件校验，传递到父组件
      validateForm() {
        let flag = null
        this.$refs['ruleForm'].validate(valid => {
          if (valid) {
            flag = true
          } else {
            flag = false
          }
        })
        return flag
      }
    }
  }
</script>

<style lang="scss" scoped>
  ::v-deep .el-cascader {
    width: 100% !important;
  }

  .card_purple ::v-deep .el-upload-list__item {
    width: 120px !important;
    height: 120px !important;
  }

  .card_purple ::v-deep .el-upload--picture-card {
    width: 120px !important;
    height: 120px !important;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .card_independent ::v-deep .icon_circle_btn {
    font-size: 20px;
  }

  .card_employee {
    // max-height: 530px;
    overflow-y: auto;
    overflow-x: hidden;
  }

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

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

  ::v-deep .el-form-item__label {
    height: 40px !important;
    display: flex !important;
    align-items: center !important;
    justify-content: flex-end !important;
    line-height: unset !important;
  }

  .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_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: auto;
    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;
  }

  .ser_card_ial {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .margin_around {
    margin: 5px 0px;
  }

  .title_serial {
    margin-left: 10px;
  }

  .del_serial {
    cursor: pointer;
    color: #F56C6C;
  }

  .card_IceList {
    display: flex;
    flex-direction: column;
    position: absolute;
    top: 60px;
    left: 0;
    right: 5px;
    padding: 0px 10px;
    max-height: 125px;
    overflow-y: auto;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    border-radius: 4px;
  }

  .forms_switch {
    height: 40px;
  }
</style>
