<template>
<div v-if="datalist.length"  class="tempalte-contain" >
  <div class="top-title">
    <span>{{toptitle}}</span>
    <div v-if="showdown" class="col-btn" >
      <span  @click="handleExpend" class="button"
        :class="isExpend ? 'el-icon-arrow-up' : 'el-icon-arrow-down' ">
          <span v-if="isExpend">收起列表</span>
          <span v-else>展开列表</span>
      </span>
    </div>
  </div>
  <el-collapse-transition>
    <el-row v-show="isExpend"  :gutter="20"  >
      <slot name="header"><!-- 具名头部插槽 --></slot>
      <template v-for="(item, index) in datalist">
        <el-col  v-if="item.isShow === 'Y' "  :span="item.span">
          <el-form-item  :label="item.fieldName" :prop="item.fieldAttr"
            :class="{'lh16': item.fieldName.length > 6}"
            :rules="[{ required: item.isRequired === 'Y',
                message: item.fieldType=='input' || item.fieldType === 'textarea' ? '请输入' : '请选择',
                trigger: item.fieldType=='input' || item.fieldType === 'textarea' ? 'blur' : 'change' },
                { pattern: new RegExp(item.regular ? item.regular : ''), message: '输入类型有误!', trigger: 'blur' }
              ]"
          >
            <template v-if="item.fieldType === 'input'"  >
            <div @click="handleClick(item)">
              <el-input v-model="moduleForm[item.fieldAttr]"
                 @blur="valChange(moduleForm[item.fieldAttr], item)"
                 :disabled="item.isReadOnly === 'Y'"
                 :maxlength="item.fieldLength ? item.fieldLength : '' "
                 show-word-limit
                 v-inputFilter:trim
                 :key="item.id"
                 placeholder="请输入" >
              </el-input>
            </div>
            </template>
            <template v-else-if="item.fieldType === 'select' ">
              <common-select
                v-if="item.fieldSource === 'dictDate' "
                v-model="moduleForm[item.fieldAttr]"
                @selectChange="dictChange"
                :key="item.id"
                :ref="'comSelectRef'+index"
                :dictkey="item.sourceLabel"
                :dictvalue="item.sourceValue"
                :dict-type="item.sourceParams"
                :index="index"
                :paramval="moduleForm[item.parentField]  ? moduleForm[item.parentField] : '' "
                :disabled="item.isReadOnly === 'Y'"
                :ismult="item.multiple === 'Y' "
                >
              </common-select>
              <ls-select
                v-else
                v-model="moduleForm[item.fieldAttr]"
                @selectChange="lsSeleChange"
                :key="item.id"
                :ref="'lsSelectRef'+index"
                :params="item.sourceParams"
                :index="index"
                :selectlist="item.dataList ? item.dataList : [] "
                :parentobj="item.parentObj ? item.parentObj : {} "
                :objkey="item.sourceLabel"
                :objvalue="item.sourceValue"
                :disabled="item.isReadOnly === 'Y'"
                :ismult="item.multiple === 'Y' "
                >
              </ls-select>
            </template>
            <template v-else-if="item.fieldType === 'textarea'" >
              <el-input
                :key="item.id"
                v-model="moduleForm[item.fieldAttr]"
                @blur="valChange(moduleForm[item.fieldAttr], item)"
                :disabled="item.isReadOnly === 'Y'"
                type="textarea"
                :maxlength=" item.fieldLength ? item.fieldLength : '' "
                show-word-limit
                :autosize="{minRows: 1, maxRows: 2}"
                placeholder="请输入" >
              </el-input>
            </template>
            <template v-else-if="item.fieldType === 'date' " >
              <el-date-picker
                :key="item.id"
                v-model="moduleForm[item.fieldAttr]"
                @change="valChange(moduleForm[item.fieldAttr], item)"
                :disabled="item.isReadOnly === 'Y' "
                :picker-options="item.pickerOptions ? item.pickerOptions : '' "
                clearable
                type="date"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                placeholder="选择日期" >
              </el-date-picker>
            </template>
           <template v-else-if="item.fieldType === 'upload'"  >
              <el-input v-model="moduleForm[item.fieldAttr]"
                placeholder="校验占位" style="display: none;"  />
              <ls-upload
                :key="item.id"
                :fileList="item.fileList ? item.fileList : []"
                :ismult="false"
                @upload="fileClosse"
                :showuploadbtn="moduleForm[item.fieldAttr] ? false : true"
                :index="index"
                :showTips="true"
                :showdeletebtn="candelfile"
                :busId="busId"
                :fileTypeList="fileTypeList"
              >
              </ls-upload>
            </template>
            <template v-else-if="item.fieldType === 'org' " >
              <el-input v-model="moduleForm[item.fieldAttr]"
                placeholder="校验占位" style="display: none;"  />
              <aws-org
                :editable="item.isReadOnly === 'Y' ? false : true"
                :key="item.id"
                :users="item.users ? item.users : [] "
                :index="index"
                :ismuti="false"
                @submit="orgClose"
                >
              </aws-org>
            </template>
            <template v-else-if="item.fieldType === 'dialog'" >
            <div @click="handleClick(item)">
              <el-input v-model="moduleForm[item.fieldAttr]"
                 readonly
                 :key="item.id"
                 :disabled="item.isReadOnly === 'Y'"
                 placeholder="无数据" >
                 <i :class=" item.icon ? item.icon : 'el-icon-search' "
                   slot="suffix" >
                 </i>
              </el-input>
            </div>
            </template>
            <template v-else>

            </template>
          </el-form-item>
        </el-col>
      </template>
      <slot><!-- 默认插槽内容 --></slot>
    </el-row>
  </el-collapse-transition>
</div>
</template>

<script>
  import lsSelect from './ls-select.vue'
  export default{
    name: 'template-form',
    components: {
      lsSelect,
    },
    created () {

    },
    mounted () {

    },
    methods:{
      setFormData () {
        let obj = {};
        let _this = this;
        this.datalist.forEach( (item, index) => {
          //给对象添加属性
          obj[item.fieldAttr] = this.formdata[item.fieldAttr] ? this.formdata[item.fieldAttr] : '';
          //下拉多选，需要格式化数据
          if (item.multiple === 'Y') {
            this.multipleProp[item.fieldAttr] = obj[item.fieldAttr];
            obj[item.fieldAttr] = obj[item.fieldAttr] ? obj[item.fieldAttr].split(',') : [];
          }
          //文件类型字段
          if (item.fieldType === 'upload') {
            if (this.fileArrField) {
              obj[this.fileArrField] = this.formdata[this.fileArrField];
            }
            obj[item.fieldAttr] && this.getFileInfo(obj[item.fieldAttr], index);
          }
          //字段有 依赖查询参数  属性
          if (item.parentField && _this.formdata[item.fieldAttr]) {
             for (let j = 0; j < _this.datalist.length; j++) {
              console.log("j=",j);
               if (item.parentField === _this.datalist[j].fieldAttr) {
                 //组织架构类型的
                 if( item.fieldType === 'org') {
                   //组合数据 user = {uid, name}
                   let id = _this.formdata[item.fieldAttr];
                   let n = _this.formdata[_this.datalist[j].fieldAttr];
                   _this.datalist[j].users = [];
                   _this.datalist[j].users.push({uid: id, name: n});
                 } else if(item.fieldType === 'select') {
                    //接口类型的下拉框，页面级联
                    if (item.isShow === 'Y' && item.fieldSource === 'interface' && item.sourceParams) {
                      let param = {};
                      param[_this.datalist[j].fieldAttr] = _this.formdata[_this.datalist[j].fieldAttr];
                      item.parentObj = param;
                    }
                 }
                 break;
               }
             }
          }

        });
        //添加 多个响应式 property
        this.moduleForm = Object.assign( {}, this.moduleForm, obj );
      },
      clearFormData () {
        Object.keys(this.moduleForm).forEach(key => this.moduleForm[key] = '');
      },
      handleExpend () {
        this.isExpend = !this.isExpend;
      },
      dictChange (obj, index, dictVal) {
        //下拉多选
        if (this.datalist[index].multiple === 'Y') {
          this.multipleProp[this.datalist[index].fieldAttr] = dictVal.join(',');
           //通过自定义事件，向外传送数据
           this.generateField &&
          this.$emit('generate', dictVal.join(','), this.datalist[index], obj, this.datalist);
        } else {
          this.generateField &&
          this.$emit('generate', obj[this.datalist[index].sourceValue], this.datalist[index], obj, this.datalist);
        }
        for(let i = 0; i < this.datalist.length; i++){
          let item = this.datalist[i];
           item = this.datalist[i];
          //在dataList中，通过依赖查询参数(parentField字段)，找到依赖当前字段 的字段
          if (item.parentField && item.parentField === this.datalist[index].fieldAttr ) {
            if (this.datalist[index].multiple === 'Y' ) { //下拉多选
              let arr = [];
              //obj 下拉框多选的数据项
              obj.forEach(item2 => {
                arr.push(item2[item.sourceValue]);
              })
              this.multipleProp[item.fieldAttr] = arr.join(',');
            } else {
              this.moduleForm[item.fieldAttr] = obj[item.sourceValue] ? obj[item.sourceValue] : obj.vaule;
            }
            this.generateField &&
            this.$emit('generate', this.moduleForm[item.fieldAttr], item);
            break;
          }
        }
      },
      lsSeleChange (obj, index, dataVal) {
        //下拉多选
        if (this.datalist[index].multiple === 'Y') {
          this.multipleProp[this.datalist[index].fieldAttr] = dataVal.join(',');
          //通过自定义事件，向外传送数据
          this.generateField &&
          this.$emit('generate', dataVal.join(','), this.datalist[index], obj, this.datalist);
        } else {
          this.generateField &&
          this.$emit('generate', obj[this.datalist[index].sourceValue], this.datalist[index], obj, this.datalist);
        }
        for (let i = 0; i < this.datalist.length; i++) {//依赖查询参数
          let item = this.datalist[i];
          if (item.parentField && item.parentField === this.datalist[index].fieldAttr) {
            if (this.datalist[index].multiple === 'Y') {
              let arr = [];
              //obj 下拉框多选的数据项
              obj.forEach( item2 => {
                arr.push(item2[item.sourceValue]);
              })
              this.multipleProp[item.fieldAttr] = arr.join(',');
            } else {
              this.moduleForm[item.fieldAttr] = obj[item.sourceValue] ? obj[item.sourceValue] : obj[item.fieldAttr];
            }
            //页面展示的接口级联
            if (item.sourceParams && item.isShow === 'Y') {
              let param = {};
              param[this.datalist[i].fieldAttr] = this.formdata[this.datalist[i].fieldAttr];
              item.parentObj = param;
            }
          }
        }
      },
      fileClosse (fileObj, index) {
        if (fileObj && fileObj.fileId) {
          this.moduleForm[this.datalist[i].fieldAttr] = fileObj.fileId;
          fileObj.modelName = this.modelName
          fileObj.modelId = this.modelId
          if (this.fileArrField) { //文件数组
            if (this.moduleForm[this.fileArrField]) {
              this.moduleForm[this.fileArrField].push(fileObj);
            } else {
              this.moduleForm[this.fileArrField] = [];
              this.moduleForm[this.fileArrField].push(fileObj);
            }
          } else {
            this.moduleForm[this.fileObjField] = fileObj;
          }
        } else {
          if (this.fileArrField) {
            let arr = this.moduleForm[this.fileArrField];
            for (let i = 0; i < arr.length; i++) {
              let item = arr[i];
              //根据文件id ，从附件数组中移除对应文件
              if (item.fileId === this.moduleForm[this.datalist[index].fieldAttr]) {
                this.moduleForm[this.fileArrField].splice(i, 1);
                break;
              }
            }
          }
          this.moduleForm[this.datalist[i].fieldAttr] = '';
          this.moduleForm[this.fileObjField] = {};
        }
        this.generateField && 
        this.$emit('generate', fileObj.fileId, this.datalist[index]);
      },
      orgClose (arr, index) {
        let item = {};
        for (let i = 0; i < this.datalist.length; i++) {
          item = this.datalist[i];
          //在dataList中，通过依赖查询参数(parentField字段)，找到当前组织人员的 id 字段
          if (item.fieldType === 'org' && this.datalist[index].fieldAttr === item.parentField) {
            //给 dataList 数据中的 当前 i 索引 的 项 ，设置 users 属性
            //给 字段 赋值
            this.datalist[index].users = arr;
            this.moduleForm[this.datalist[index].fieldAttr] = arr.length ? arr[0].name : '';
            this.moduleForm[item.fieldAttr] = arr.length ? arr[0].uid : '';
            break;
          }
        }
      },
      valChange (val, obj) {
        if (this.generateField) {
          this.$emit('generate', val, obj);
        }
      },
      getFileInfo (fileId, i) {
        this.$ajax.post({
          domain: 'crmCmUrl',
          url: 'attachFiles.getByFileIdInfo',
          data: { fileId  },
          requestType: 'body',
          showLoad: false,
          success: function (res) {
            if (res.errorCode === 200) {
              let data = res.data;
              if(data && data.fileId){
                let obj = {
                  fileId: data.fileId,
                  fileName: data.fileName,
                  fileSize: data.fileSize
                };
                let fileList = [obj];
                this.$set(this.datalist[i], 'fileList', fileList);
              }
            }
          }.bind(this),
          error: function (res) {
            console.log(res.body.msg || res.msg);
          }.bind(this)
        })
      },
      handleClick (item) {
        this.$emit('onClick', item);
      },

    },
    props:{
      //表单对象
      //(表单对象属性有 obj 类型的，建议使用多个 form 表单)
      formdata:{
        type: Object,
        default: () => {},
        required: true
      },
      toptitle: {//标题
        type: String,
        default: '',
        required: true
      },
      datalist:{ //模板字段数据
        type: Array,
        default: () => [],
        required: true
      },
      fileArrField: { //文件数组 字段
        type: String,
        default: ''
      },
      fileObjField: {//文件对象字段
        type: String,
        default: 'attachFileInfo'
      },
      modelId: {
        type: String,
        default: '3110'
      },
      modelName: {
        type: String,
        default: 'CUSTOMER'
      },
      busId: {
        type: String,
        default: '',
      },
      showdown: {//展示下拉折叠
        type: Boolean,
        default: false
      },
      candelfile: {//可以删除上传文件
        type: Boolean,
        default: true
      },
      expendRow: { //展开行
        type: Boolean,
        default: true
      },
      generateField: { //向外生成字段
        type: Boolean,
        default: false
      },
      fileTypeList: { //文件类型数组
        type: Array,
        default (){
          return ['rar', 'zip', 'doc', 'docx','pdf', 'xlsx',
          'pptx','ppt', 'xls','jpg', 'jpeg', 'png', 'gif', 'msg'];
        }
      },

    },
    watch: {
      moduleForm: {
        handler(newVal, oldVal){
          //更新formdata 时，用 multipleProp 覆盖 moduleForm 中的同名属性
          //再用 moduleForm 覆盖 formdata 中的同名属性
          let obj = Object.assign(this.formdata, this.moduleForm, this.multipleProp);
          this.$emit('update:formdata', obj);
        },
        deep: true
      },
    },
    data() {
      return{
        moduleForm: {},
        multipleProp: {}, //用来存多选属性
        isExpend: this.expendRow, //是否展开
      }
    },
  }
</script>

<style lang="scss">
</style>
