<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-row v-show="isExpend"  :gutter="20"  >
    <slot name="header"></slot>
    <template v-for="(item, index) in datalist">
      <el-col :key="index" 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
              :key="item.id"
              v-if="item.fieldSource=='dictDate' "
              v-model="moduleForm[item.fieldAttr]"
              :dictkey="item.sourceLabel"
              :dictvalue="item.sourceValue"
              :dict-type="item.sourceParams"
              :index="index"
              :paramval="moduleForm[item.parentField]  ? moduleForm[item.parentField] : '' "
              @selectChange="dictChange"
              :disabled="item.isReadOnly=='Y'"
              :ismult="item.multiple=='Y' "
              >
            </common-select>
            <ls-select
              :key="item.id"
              v-else
              v-model="moduleForm[item.fieldAttr]"
              @selectChange="lsSeleChange"
              :attr="item.fieldAttr"
              :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="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 || 'def' "
              :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>
  </div>
</template>

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

    },
    mounted(){

    },
    methods:{
      handleExpend(){
        this.isExpend = !this.isExpend;
      },
      dictChange(obj, index, dictVal){
        if(this.generateField&&this.datalist[index].multiple!='Y'){
          this.$emit('generate', obj[this.datalist[index].sourceValue], this.datalist[index],obj,this.datalist);
        }
        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);
        }
        for(let i=0; i<this.datalist.length; i++){
          let item = this.datalist[i];
          //在dataList中，通过依赖查询参数(parentField字段)，找到依赖当前字段的字段
          if(item.parentField && this.datalist[index].fieldAttr === item.parentField){
            if(this.datalist[index].multiple=='Y'){ //下拉多选
              let arr = [];
              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;
            }
            if(this.generateField){
              this.$emit('generate', this.moduleForm[item.fieldAttr], item);
            }
            break;
          }
        }
      },
      lsSeleChange(obj, index, dataVal){
        if(this.generateField && this.datalist[index].multiple !=='Y' ){
          this.$emit('generate', obj[this.datalist[index].sourceValue], this.datalist[index], obj,this.datalist);
        }
        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);
        }
        let item = {};
        for(let i=0; i<this.datalist.length; i++){//依赖查询参数
          item = this.datalist[i];
          if( item.parentField && item.parentField ==  this.datalist[index].fieldAttr){
            if(this.datalist[index].multiple=='Y'){
              let vals=[];
              for(let o=0; o<obj.length; o++){
                vals.push(obj[o][item.sourceValue] ? obj[o][item.sourceValue] : obj[o][item.fieldAttr]);
              }
              // this.moduleForm[item.fieldAttr]=vals.join(',');
              this.multipleProp[item.fieldAttr] = vals.join(',');
            }else{
              this.moduleForm[item.fieldAttr] = obj[item.sourceValue] ? obj[item.sourceValue] : obj[item.fieldAttr];
            }
          }
        }

      },
      fileClosse(fileObj, i){
        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 j=0; j< arr.length; j++){
              let item = arr[j];
              //根据文件id ，从附件数组中移除对应文件
              if(item.fileId == this.moduleForm[this.datalist[i].fieldAttr]){
                this.moduleForm[this.fileArrField].splice(j, 1);
                break;
              }
            }
          }
          this.moduleForm[this.datalist[i].fieldAttr] = '';
          this.moduleForm[this.fileObjField] = {};
        }
        if(this.generateField){
          this.$emit('generate', fileObj.fileId, this.datalist[i]);
        }
      },
      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;
              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) {
            this.$message.error( res.body.msg || res.msg);
          }.bind(this)
        })
      },
      handleClick(item){
        this.$emit('onClick', item);
      },

    },
    props:{
      formdata:{ //表单对象
        type: Object,
        default: () => {},
        required: true
      },
      toptitle: {//标题
        type: String,
        default: '',
        required: true
      },
      datalist:{ //模板字段数据
        type: Array,
        default: () => [],
        required: true
      },
      objTypeField:{ //模板数据对象中嵌套另外一个，模板数据对象，用一个 对象类型的 字段存储
        type: String,
        default: ''
      },
      fileArrField: { //文件数组 字段
        type: String,
        default: ''
      },
      fileObjField: {//文件对象字段
        type: String,
        default: 'attachFileInfo'
      },
      modelId: {
        type: String,
        default: '3110'
      },
      modelName: {
        type: String,
        default: 'CUSTOMER'
      },
      busId: {
        type: String,
        default: '',
        // required: true
      },
      showdown: {//展示下拉折叠
        type: Boolean,
        default: false
      },
      candelfile: {//可以删除上传文件
        type: Boolean,
        default: true
      },
      defExpend: { //默认展开
        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'];
        }
      },
      pickerOptions:{//日期可选项

      },

    },
    watch: {
      datalist: {
        handler(newVal){
          if(newVal.length){
            let obj = {};
            newVal.forEach((item, i)=>{
              if(item.fieldAttr != 'none'){
                obj[item.fieldAttr] = this.formdata[item.fieldAttr] ? this.formdata[item.fieldAttr] : '';
              }
              if(item.fieldType=='upload'){
                if(this.fileArrField){
                  obj[this.fileArrField] = this.formdata[this.fileArrField];
                }
                obj[item.fieldAttr] && this.getFileInfo(obj[item.fieldAttr], i);
              }
              if(item.multiple=='Y'){
                this.multipleProp[item.fieldAttr] = obj[item.fieldAttr];
                obj[item.fieldAttr] = obj[item.fieldAttr]?obj[item.fieldAttr].split(','):[];
              }
              // 依赖查询参数
              if(item.parentField){
                if(item.fieldType=='org'){ //组织架构
                  for(let j=0; j<newVal.length; j++){
                    if(this.formdata[item.fieldAttr] && newVal[j].fieldAttr == item.parentField){
                      let id = this.formdata[item.fieldAttr];
                      let n = this.formdata[newVal[j].fieldAttr];
                      newVal[j].users = [];
                      newVal[j].users.push({uid: id, name: n});
                      break;
                    }
                  }
                }
              }

            });
            this.moduleForm = Object.assign( {},this.moduleForm, obj);
          }
        },
        immediate: true
      },
      moduleForm:{
        handler(newVal, oldVal){
          if(this.objTypeField){
            let obj = Object.assign({}, this.formdata, this.moduleForm, this.multipleProp);
            obj[this.objTypeField] = Object.assign({}, obj[this.objTypeField], this.moduleForm, this.multipleProp);
            this.$emit('update:formdata', obj);
          }else{
            let obj = Object.assign({}, this.formdata, this.moduleForm, this.multipleProp);
            this.$emit('update:formdata', obj);
          }
        },
        immediate: true,
        deep: true
      },
    },
    data(){
      return{
        moduleForm: {},
        multipleProp: {}, //用来存多选属性
        isExpend: this.defExpend, //是否展开
      }
    },
  }
</script>

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