<!-- 搜索表单 -->
<template>
    <div class="ces-search">
      <el-form :size="size" :inline="inline" :label-position="labelPosition" :label-width="labelWidth" ref="ruleForm" :rules="formRule" :model="itemData">
        <el-form-item v-for="item in formItem" :label="item.label" :key="item.label" :prop="item.prop" :label-width="item.labelWidth||labelWidth">
          <!-- 输入框 -->
          <el-input
            v-if="item.type==='input'"
                      :type="item.mold||'text'"
            v-model="itemData[item.prop]"
            :size="size || item.size"
            :style="{width:(item.width?item.width+'px':'300px')}"
            @change="item.change && item.change(itemData[item.prop])"
            :placeholder="`请输入${item.label}`"
            :disabled="item.isDisabled && item.isDisabled(itemData[item.prop])"
                      @blur="item.mold==='number'?BlurText($event):''"
          >
                      <template v-if="item.slot" :slot="item.slot.direction||'append'">{{item.slot.value}}</template>
                  </el-input>
                  <!-- 文本域 -->
                  <el-input
                    v-if="item.type==='textarea'"
                    type="textarea"
                    :rows="4"
                    :size="size || item.size"
                    :style="{width:item.width+'px'}"
                    :disabled="item.isDisabled && item.isDisabled(itemData[item.prop])"
                    @change="item.change && item.change(itemData[item.prop])"
                    v-model="itemData[item.prop]"
                  ></el-input>
          <!-- 下拉框 -->
          <el-select
            v-if="item.type==='select'"
            v-model="itemData[item.prop]"
            filterable
            :size="size || item.size"
            :style="{width:(item.width?item.width+'px':'300px')}"
            :multiple="item.multiple"
            :placeholder="`请选择${item.placeholder||item.label}`"
            @change="item.change && item.change(itemData[item.prop])"
            @visible-change="item.focus && item.focus($event,itemData[item.prop])"
            :disabled="item.isDisabled && item.isDisabled(itemData[item.prop])"
          >
            <el-option v-for="op in item.options" :label="op.label" :value="op.value" :key="op.value"></el-option>
          </el-select>
          <!-- 级联省市区 -->
          <el-cascader
            v-if="item.type==='cascader'"
            :style="{width:(item.width?item.width+'px':'300px')}"
            :placeholder="item.placeholder || `请选择${item.label}` "
            :options="options"
            v-model="itemData[item.prop]"
            @focus="item.focus && item.focus(itemData[item.prop])"
            filterable
            clearable
            :show-all-levels="item.showAll && item.showAll(itemData[item.prop])"
            :props="{ expandTrigger: 'hover',checkStrictly: item.checkStrictly && item.checkStrictly(itemData[item.prop]) }"
            @change="item.change && item.change(itemData[item.prop])"
          ></el-cascader>
          <!-- 单选 -->
          <el-radio-group
            v-if="item.type==='radio'"
            v-model="itemData[item.prop]"
            :style="{width:item.width+'px'}"
            @change="item.change && item.change(itemData[item.prop])"
            :size="size || item.size"
            :disabled="item.isDisabled && item.isDisabled(itemData[item.prop])"
          >
            <el-radio v-for="ra in item.radios" :label="ra.value" :key="ra.value">{{ra.label}}</el-radio>
          </el-radio-group>
          <!-- 单选按钮 -->
          <el-radio-group
            v-if="item.type==='radioButton'"
            v-model="itemData[item.prop]"
            :style="{width:item.width+'px'}"
            @change="item.change && item.change(itemData[item.prop])"
            :size="size || item.size"
            :disabled="item.isDisabled && item.isDisabled(itemData[item.prop])"
          >
            <el-radio-button v-for="ra in item.radios" :label="ra.value" :key="ra.value">{{ra.label}}</el-radio-button>
          </el-radio-group>
          <!-- 复选框 -->
          <!-- <el-checkbox-group
            v-if="item.type==='checkbox'"
            v-model="itemData[item.prop]"
            :style="{width:item.width+'px'}"
            @change="item.change && item.change(itemData[item.prop])"
            :size="size || item.size"
            :disabled="item.isDisabled && item.isDisabled(itemData[item.prop])"
          >
            <el-checkbox v-for="ch in item.checkboxs" :label="ch.value" :key="ch.value">{{ch.label}}</el-checkbox>
          </el-checkbox-group> -->
  
          <el-checkbox-group v-model="itemData[item.prop]" v-if="item.type==='checkbox'">
            <el-checkbox v-for="ch in item.checkboxs" :label="ch.label" :key="ch.value" :name="item.prop"></el-checkbox>
          </el-checkbox-group>
          <!-- 树形组件 -->
          <el-tree
            v-if="item.type==='tree'"
            :data="item.treeArr"
            show-checkbox
            :node-key="treeKey"
            :default-expanded-keys="treeExpandArr"
            :default-checked-keys="treeCheckArr"
            :props="defaultProps"
            @check-change="handleCheckChange"
            @check="getChecked"
          >
          </el-tree>
          <!-- 日期 -->
          <el-date-picker
            v-if="item.type==='date'"
            v-model="itemData[item.prop]"
            :style="{width:item.width+'px'}"
                      format="yyyy-MM-dd"
                      value-format="yyyy-MM-dd"
            :placeholder="`请选择${item.placeholder||''}`"
            @change="item.change && item.change(itemData[item.prop])"
            :size="size || item.size"
            :disabled="item.isDisabled && item.isDisabled(itemData[item.prop])"
          ></el-date-picker>
          <!-- 开始-结束日期 -->
          <el-date-picker
            v-if="item.type==='daterange'"
            type="daterange"
                      format="yyyy-MM-dd"
                      value-format="yyyy-MM-dd"
            v-model="itemData[item.prop]"
            :style="{width:item.width+'px'}"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="item.change && item.change(itemData[item.prop])"
            :size="size || item.size"
            :disabled="item.isDisabled && item.isDisabled(itemData[item.prop])"
          ></el-date-picker>
          <!-- 时间 -->
          <el-time-select
            v-if="item.type==='time'"
            v-model="itemData[item.prop]"
            format="HH:mm:ss"
            value-format="HH:mm:ss"
                      :picker-options="item.options||{
                            start: '00:00',
                            step: '00:30',
                            end: '23:30'
                          }"
            :style="{width:item.width+'px'}"
            @change="item.change && item.change(itemData[item.prop])"
            :size="size || item.size"
                      :placeholder="`请选择${item.placeholder||''}`"
            :disabled="item.isDisabled && item.isDisabled(itemData[item.prop])"
          ></el-time-select>
          <!-- 日期时间 -->
          <el-date-picker
            v-if="item.type==='dateTime'"
            :type="item.timeType||'datetime'"
            :style="{width:item.width+'px'}"
            v-model="itemData[item.prop]"
            @change="item.change && item.change(itemData[item.prop])"
            :size="size || item.size"
                      :placeholder="`请选择${item.placeholder||''}`"
            :disabled="item.isDisabled && item.isDisabled(itemData[item.prop])"
          ></el-date-picker>
          <!-- 滑块 -->
          <!-- <el-slider v-if="item.type==='Slider'" v-model="itemData[item.prop]"></el-slider> -->
          <!-- 开关 -->
          <el-switch
            v-if="item.type==='switch'"
            v-model="itemData[item.prop]"
            :size="size || item.size"
                      :active-value="item.values&&item.values[0]"
                      :inactive-value="item.values&&item.values[1]"
            @change="item.change && item.change(itemData[item.prop])"
            :style="{width:item.width+'px'}"
            :disabled="item.isDisabled && item.isDisabled(itemData[item.prop])"
          ></el-switch>
          <!-- 图片上传 -->
          <section v-if="item.type==='upload'" :style="{width:item.width+'px'}">
            <el-upload
              v-loading="loading"
              class="avatar-uploader"
              :action="upload_url+'/common/upload'"
              :show-file-list="false"
              :on-success="item.success"
              :on-error="handleAvatarError"
              :on-progress="handleAvatarProgress"
              :before-upload="beforeAvatarUpload"
              name="file"
            >
              <img v-if="itemData[item.prop]" :src="itemData[item.prop]|formatImg" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </section>
          <!-- 文件上传 -->
          <section v-if="item.type==='uploadfill'" :style="{width:item.width+'px'}">
            <el-upload
              v-loading="loading"
              class="avatar-uploader"
              :action="file_url+'common//uploadNotRename'"
              :show-file-list="false"
              :on-success="item.success"
              :on-error="handleAvatarError"
              :on-progress="handleAvatarProgress"
              name="file"
            >
              <img v-if="itemData[item.prop]" :src="itemData[item.prop]|formatImg" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </section>
          <!-- 多图片上传 -->
          <section v-if="item.type==='uploadList'" :style="{width:item.width+'px'}">
            <el-upload
                          ref="pictureCard"
              v-loading="loading"
              :action="upload_url+'/common/upload'"
              list-type="picture-card"
              :multiple="true"
              :limit="item.limit||9"
              :fileList="fileList"
              :on-success="handleAvatarSuccess"
              :on-error="handleAvatarError"
              :on-progress="handleAvatarProgress"
              :before-upload="beforeAvatarUpload"
              :on-remove="handleRemove"
              :on-exceed="handleExceed"
                          :on-preview="handlePictureCardPreview"
                          :headers="{'Authorization':$cookie.get('token')}"
                          name="file"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible"  title="预览" width="600px">
              <img width="100%" :src="dialogImageUrl" alt />
            </el-dialog>
          </section>
                  <!-- 富文本 -->
                  <r-tinymce
                    v-if="item.type==='tinymce'"
                    v-model="itemData[item.prop]"
                    :height="300"
                    :width="600"
                  ></r-tinymce>
  
        </el-form-item>
        <el-form-item :style="btnRight?`float:right`:''">
          <el-button
            v-for="(btnl,btni) in btnList" :key="btni"
              :type="btnl.type"
              :size="btnl.size || size"
              :icon="btnl.icon"
                          :disabled="btnl.disabled"
              :style="{display:btnl.visible}"
              @click="getHandle(btnl.handle,btnl.deed)"
            >{{btnl.label}}</el-button>
        </el-form-item>
  
      </el-form>
    </div>
  </template>
  <script>
  import { regionData, CodeToText } from "element-china-area-data";
  export default {
    name: "FormItem",
    props: {

      labelPosition:{
        type: String,
        default: "none"
      },
      isState:{
        type: Boolean,
        default: true,
      },
      btnRight:{
        type: Boolean,
        default: false,
      },
      isHandle: {
        type: Boolean,
        default: true,
      },
      inline: {
        type: Boolean,
        default: false,
      },
      labelWidth: {
        type: String,
        default: "100px",
      },
      // 搜索框型号：mini,medium,small
      size: {
        type: String,
        default: "medium",
      },
      btnList: {
        type: Array,
        default: () => [],
      },
      formItem: {
        type: Array,
        default: () => [],
      },
      itemData: {
        type: Object,
        default: () => {},
      },
          formRule: {
        type: Object,
        default: () => {},
      },
          fileList: {
            type: Array,
            default: () => [],
          },
      treeArr: {
            type: Array,
            default: () => [],
          },
      treeExpandArr: {
            type: Array,
            default: () => [],
          },
      treeCheckArr: {
            type: Array,
            default: () => [],
          },
      treeKey:{
        type: String,
        default: "id"
      },
      defaultProps: {
        children: 'children',
        label: 'label'
      },
    },
    data() {
      return {
        // treeExpandArr:[],
        // treeCheckArr:[],
        options:regionData,
        loading: false,
        imageUrl: "",
        upload_url: process.env.NODE_ENV,
        imgurl: process.env.VUE_APP_IMG,
              dialogVisible: false,
              dialogImageUrl:'',
        isMouse:false,
        isLoading:false,
        good:[],
        file_url:''
      };
    },
    created(){
      this.file_url=process.env.VUE_APP_IMG
    },
  
    methods: {
      getChecked(checkedNodes,checkedKeys){
        this.$parent.$emit('treeKeyArr',checkedKeys.checkedKeys);
      },
      handleCheckChange(data, checked) {
        if (data.parent_id==0 && checked) {
          data.chk=1
        }else if (data.parent_id==0 && !checked) {
          data.chk=0
        }else if (data.parent_id !==0) {
          data.chk=checked?1:0
        }
      },
      getHandle(func,deed){
        if (deed=='reset') {
          this.$refs.ruleForm.resetFields();
        }else{
          func.call(func)
        }
  
  
      },
      mouseenter(icon){
        if (icon==='el-icon-refresh') {
          this.isMouse=true;
        }
      },
      mouseleave(icon){
        if (icon==='el-icon-refresh') {
          this.isMouse=false;
        }
      },
  
          BlurText(e) {
              let boolean = new RegExp("^[1-9][0-9]*$").test(e.target.value)
              if(!boolean) {
                  this.$message.warning('请输入正整数')
                  e.target.value = ' '
              }
          },
      handleAvatarSuccess(res, file) {
        this.loading = false;
        this.imageUrl = URL.createObjectURL(file.raw);
        this.$message({
          message: "上传成功",
          type: "success",
        });
        this.$emit("imgs", {
          type: "text",
          url: `${res.data}`,
        });
      },
          handleUpload() {
            this.$refs['excel-upload-input'][0].click()
          },
          handleClick(e){
              const files = e.target.files
              const rawFile = files[0] // only use files[0]
              if (!rawFile) return
              //this.upload(rawFile)
              this.$emit("uploadEX", rawFile);
          },
          upload(rawFile) {
            this.$refs['excel-upload-input'][0].value = null // fix can't select the same excel
            const before = this.beforeUpload(rawFile)
            if (before) {
              let formData = new FormData();
              formData.append('file',rawFile);
              this.$http.upload('/file/upload',formData).then(res=>{
                      if(res.code == 200){
                          this.$message({
                            type: "success",
                            message:  "上传成功",
                          });
                      }
              })
            }
          },
          beforeUpload(file) {
            const isLt1M = file.size / 1024 / 1024 < 1
            if (isLt1M) {
              return true
            }
            this.$message({
              message: '小于1兆',
              type: 'warning'
            })
            return false
          },
      handleAvatarError() {
        this.loading = false;
        this.$message.error("上传失败");
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === "image/jpeg" || "image/png";
        const isLt5M = file.size / 1024 / 1024 < 5;
        if (!isJPG) {
          this.$message.error("上传格式只能是图片格式!");
        }
        if (!isLt5M) {
          this.$message.error("上传头像图片大小不能超过 5MB!");
        }
        return isJPG && isLt5M;
      },
      handleAvatarProgress(res, file) {
        this.loading = true;
      },
      handleRemove(file, fileList) {
        let list = fileList.map((item) => {
          console.log(item)
          if(item.response){
              return item.response.data
          }else{
              if(item.url.indexOf('http')!=-1){
                  return item.url.split(process.env.VUE_APP_IMG)[1]
              }else{
                  return item.url
              }
          }
              });
        this.$emit("imgs", {
          type: "pictureCard",
          url: list,
        });
      },
      handleExceed() {
        this.$message({
          message: `最多上传${this.$refs.pictureCard[0].limit||9}张图片`,
          type: "warning",
        });
      },
          handlePictureCardPreview(file){
              this.dialogImageUrl = file.url;
              this.dialogVisible = true;
          }
    },
  };
  </script>
  <style scoped lang="scss">
  @keyframes circles{
    0%{transform:rotateZ(0deg);}
    100%{transform:rotateZ(360deg);}
  }
  .good{
    animation-name:circles;
    animation-duration:3s;
    animation-iteration-count:1;
  }
  .avatar-uploader,
  .el-upload {
    border: 1px dashed #ccc;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 150px;
    height: 150px;
    display: block;
  }
  
  .avatar-uploader:hover,
  .el-upload:hover {
    border-color: #409eff;
  }
  
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 150px;
    height: 150px;
    line-height: 150px;
    text-align: center;
  }
  
  .avatar {
    width: 150px;
    height: 150px;
    display: block;
  }
  
  .excel-upload-input{
    display: none;
    z-index: -9999;
  }
  </style>
  