<!--文本域组件-->
<template>
    <div class="main-div-comp" >
            <div class="main-div-comp-div"
                    v-for="(item,index) in textFieldArr" :key="index"  >
                    <!--<el-form-item   label-width="110px" :prop="item.fieldId"-->
                                    <!--:rules="textFieldRules[item.fieldId]">-->
                    <!--<span slot="label">-->
                        <!--&lt;!&ndash;<span v-if="requiredStars[item.fieldId] == '1'" style="color: red; margin-right: 5px;">*</span>&ndash;&gt;-->
                        <!--{{item.hideShowName == '是' ? '':item.showName}}</span>-->
                        <div  v-if="item.controlType == 'commonText'" :style="item.controlCss+';width:'+item.occupyWidth+';text-align:'+item.viewAlign" >
                            {{item.showName}}
                        </div>

                        <!--控件文本-->
                        <div  v-if="item.controlType != 'commonText'">
                             <el-input
                                     v-if="(item.controlType == 'input' || (item.controlType == 'textarea' && item.editor != 'true')  ||  item.controlType == 'password') && !showText"
                                     v-model="contentForm[item.fieldId]"
                                     :placeholder="item.placeholder"
                                     :disabled="item.editable != 'true'"
                                     :style=" item.controlCss || ( 'width:'+(item.controlWidth || '200px')+';height:'+item.controlHeight)"
                                     :type="item.controlType"
                                     v-on="$on[item.fieldId]"
                                     :show-password="item.controlType == 'password'"
                                     :auto-complete="'new-password'"
                                     :size="tableviewsData.size">
                        </el-input>
                            <!--富文本编辑器-->
                        <pl-ueditor v-if="item.controlType == 'textarea' && item.editor == 'true' && !showText"
                                    :content = "contentForm[item.fieldId]"
                                    v-on="$on[item.fieldId]"
                                    :config = "{height: (Number(item.editorRows) || 3) * 28}"
                        >
                        </pl-ueditor>
                        <div
                                v-if="(item.controlType == 'input' || (item.controlType == 'textarea' && item.editor != 'true')  ||  item.controlType == 'password') && showText"
                                :style="!contentForm[item.fieldId] ? 'height: 36px; ' :''">
                            {{contentForm[item.fieldId]}}
                        </div>
                            <!--select 选择框-->
                            <div v-if="item.controlType == 'select'">
                                <pl-data-select  v-if="item.selectType == 'remote'"
                                                 v-model="contentForm[item.fieldId]"
                                                 typeId = ''
                                                 v-on="$on[item[item.fieldId]]"
                                                 :multiple="item.muliti == 'true'"
                                                 :reqUrl="item.reqUrl"
                                                 :show-text="showText"
                                                 :placeholder="item.placeholder"
                                                 :disabled="item.editable != 'true'"
                                                 :size="tableviewsData.size"
                                                 :style=" item.controlCss || ( 'width:'+(item.controlWidth || '100%')+';height:'+item.controlHeight)"
                                >
                                </pl-data-select>
                                <pl-data-select
                                        v-if="item.selectType == 'sysData'"
                                        v-model="contentForm[item.fieldId]"
                                        :typeId="item.dataDic"
                                        v-on="$on[item[item.fieldId]]"
                                        :show-text="showText"
                                        :multiple="item.muliti == 'true'"
                                        :placeholder="item.placeholder"
                                        :disabled="item.editable != 'true'"
                                        :size="tableviewsData.size"
                                        :style=" item.controlCss || ( 'width:'+(item.controlWidth || '100%')+';height:'+item.controlHeight)">
                                </pl-data-select>

                                <el-select
                                        v-if="item.selectType == 'select' && !showText"
                                        v-model="contentForm[item.fieldId]"
                                        v-on="$on[item[item.fieldId]]"
                                        :style=" item.controlCss || ( 'width:'+(item.controlWidth || '100%')+';height:'+item.controlHeight)"
                                        :disabled="item.editable != 'true'"
                                        :multiple="item.muliti == 'true'"
                                        :size="tableviewsData.size">
                                    <el-option  v-for="(option,index) in  item.optionSetting || []"
                                                :key="index"
                                                :label="option.label"
                                                :value="option.label"/>
                                </el-select>

                                <div v-if="item.selectType == 'select' && showText">
                                    {{contentForm[item.fieldId]}}
                                </div>
                                <!--select预览-->
                            </div>

                                <!--单选框-->
                            <div v-if="item.controlType == 'radio'">
                                <pl-data-radio-box  v-model="contentForm[item.fieldId]"
                                                    v-if="item.radioType == 'sysData'"
                                                    :typeId = "item.dataDic || ''"
                                                    :width="item.controlWidth||'120px'"
                                                    :show-text="showText"
                                                    v-on="$on[item.fieldId]"
                                                    :height="item.controlHeight"
                                                    :disabled="item.editable != 'true'"
                                                    :control-css="item.controlCss">
                                </pl-data-radio-box>

                                <el-radio-group v-if="item.radioType == 'radio' && !showText"
                                                v-model="contentForm[item.fieldId]"
                                                v-on="$on[item.fieldId]"
                                                :style=" item.controlCss || ( 'width:'+(item.controlWidth || '100%')+';height:'+item.controlHeight)"
                                                :disabled="item.editable != 'true'"
                                                :size="tableviewsData.size">
                                    <el-radio-button v-for="(option,index) in (item.optionSetting|| [])" :key="index" :label="option.label">
                                        {{option.label}}
                                    </el-radio-button>
                                </el-radio-group>

                                <div v-if="item.radioType == 'radio' && showText">
                                    {{contentForm[item.fieldId]}}
                                </div>
                            </div>

                                <!--复选框-->
                            <div v-if="item.controlType == 'checkbox'">
                                <pl-data-checkbox
                                        v-if="item.checkboxType == 'sysData'"
                                        v-model="contentForm[item.fieldId]"
                                        :type-id="item.dataDic || ''"
                                        :width="item.controlWidth||'100%'"
                                        :show-text="showText"
                                        v-on="$on[item.fieldId]"
                                        :height="item.controlHeight"
                                        :disabled="item.editable != 'true'"
                                        :control-css="item.controlCss">
                                </pl-data-checkbox>

                                <el-checkbox-group v-if="item.checkboxType == 'checkbox' && !showText"
                                                   v-model="contentForm[item.fieldId]"
                                                   v-on="$on[item.fieldId]"
                                                   :size="tableviewsData.size"
                                                   :style=" item.controlCss || ( 'width:'+(item.controlWidth || '100%')+',height:'+item.controlHeight)"
                                                   :disabled="item.editable != 'true'">
                                    <el-checkbox v-for="(option,index) in (item.optionSetting || [])" :key="index" :label="option.label">
                                        {{option.label}}
                                    </el-checkbox>
                                </el-checkbox-group>
                                <div v-if="item.checkboxType == 'checkbox' && showText">
                                    {{contentForm[item.fieldId]}}
                                </div>
                            </div>

                                <!--time 时间框-->
                            <div v-if="item.controlType == 'time'">
                                <pl-date-picker
                                        v-model= "contentForm[item.fieldId]"
                                        :style=" item.controlCss || ( 'width:'+(item.controlWidth || '200px')+';height:'+item.controlHeight)"
                                        :type="formatterDateType(item.displayFormatter)"
                                        :value-format="item.displayFormatter || 'yyyy-MM-dd'"
                                        :format="item.displayFormatter || 'yyyy-MM-dd'"
                                        :editable="item.editable == 'true'"
                                        :min-date="item.startDate"
                                        :max-date="item.endDate"
                                        :placeholder="item.placeholder || '请输入日期'"
                                        v-on="$on[item.fieldId]"
                                        :size="tableviewsData.size">
                                </pl-date-picker>
                            </div>

                                <!--图片-->
                            <div v-if="item.controlType == 'pictureSet'">
                                <pl-image
                                        :style="item.controlCss || ( 'width:'+(item.controlWidth || '200px'))"
                                        :fkid = "item.fieldId"
                                        :title = "item.title"
                                        v-on="$on[item.fieldId]"
                                        :is-disabled="showText"
                                        :pl-file-type="item.picType || ''"
                                        :imgHeight = "Number(item.controlHeight)"
                                        :imgWidth = "Number(item.controlWidth) || 80"
                                        :maxSize = "Number(item.picSize)"
                                        :unit = "item.picSizeType"
                                        :size="tableviewsData.size"
                                ></pl-image>
                            </div>

                                <!--追加意见-->
                            <div v-if="item.controlType == 'addComments'">
                                <pl-additional-comment
                                        v-on="$on[item.fieldId]"
                                        v-model="contentForm[item.fieldId]"
                                        :width="item.controlWidth"
                                        :isWatch='showText'
                                        :panelHeight="Number((item.controlHeight || '').indexOf('px') > -1?
                            (item.controlHeight || '').substring(0,(item.controlHeight || '').indexOf('px'))
                             : ((item.controlHeight || '').indexOf('%')> -1 ?
                             (item.controlHeight || '').substring(0,(item.controlHeight || '').indexOf('%')):'0') )">
                                </pl-additional-comment>
                            </div>
                                <!--联系方-->
                            <div v-if="item.controlType == 'contactParty'">
                                <pl-org-select
                                        v-on="$on[item.fieldId]"
                                        v-model="contactObj"
                                        :prop = "item.fieldId"
                                        :checkType = "item.muliti === '是' ? 'checkbox' : 'radio'"
                                        :contactType="item.contactType"
                                        :backfillField = "item.callbackField"
                                        :showName = "item.showName">
                                </pl-org-select>
                            </div>
                        </div>
            </div>
    </div>

</template>

<script>
    import {Replace} from "sasp-base";
    import PlUeditor from "./plUeditor";
    import PlAdditionalComment from "./plAdditionalComment";
    import PlOrgSelect from "./plOrgSelect";
    import PlDataRadioBox
        from "../../views/popup/tableViewsDialog/tableviewRenderComp/plDataRadioBox";
    import PlDataCheckbox
        from "../../views/popup/tableViewsDialog/tableviewRenderComp/plDataCheckbox";
    export default {
        name: "plTextField",
        components: {PlDataCheckbox, PlDataRadioBox, PlOrgSelect, PlAdditionalComment, PlUeditor},
        props:{
            formId:{type:String,default:''},
            textFieldArr:{type:Array,default:function () {return []}},
            contentForm:{type:Object,required:true},
            tableviewsData:{type:Object,default:{}},
            showText:{required: false, default: false, type: Boolean}, // 查看状态
            formOperate:{type:String,default:"add"}
        },
        data(){
            return {
                contactObj :{},
                loginUser:{},
                userDept:{},
                requiredStars:{}, //必填控件前面加*
                textFieldRules: {}, //校验
                $on:{}, //表单视图事件
                viewsEventMap: {}, // 表单视图事件设置参数

            }
        },
        mounted(){

        },
        computed:{
            argumens(){
                // const sopt = {
                //     'hideFields': this.hideFields,
                //     'hideTrsByField': this.hideTrsByField,
                //     'showTrsByField': this.showTrsByField
                // };
                return [
                    this.contentForm, //行数据
                    formEvent.CTX,
                    this,
                    formEvent.axios,
                    // sopt,
                    // this.eventListener
                ];
            },

            formalParams(){
                return [
                    'formData',//行数据
                    'CTX',
                    'vm',
                    'axios',
                    // 'sopt',
                    // 'eventListener'
                ];
            },
        },

        created(){
            this.loadLoginUser();
            this.loadViewsEvent();
            this.initDeafultVal();   //初始化验证
        },
        watch:{
            textFieldArr: {
                handler: function(newVal, oldVal){
                    this.initDeafultVal();
                },
                deep: true
            }

        },
        methods:{
            //查询当前用户信息
            loadLoginUser(){
                this.loginUser = this.CACHE_GLOBAL.getLoginUser() || {};
                this.userDept = this.CACHE_GLOBAL.getLoginDept() || {};
            },

            async loadViewsEvent(){
                let vm = this;
                vm.viewsEventMap = {};
                if(vm.formId){
                    let dataRes =  await vm.axios.post(vm.api.plEventSet.find,{formId:vm.formId,tviewId:vm.tableviewsData.id,sourceType:'basic'});
                    (dataRes.data || []).forEach(item =>{
                        if(!vm.viewsEventMap[item.field]){
                            vm.$set(vm.viewsEventMap, item.field, {});
                        }
                        vm.$set(vm.viewsEventMap[item.field], item.eventType, new Function(...vm.formalParams, item.eventContent));
                    });
                }
            },

           initDeafultVal(){
                (this.textFieldArr || []).forEach(item =>{
                    let fieldId = item.fieldId;
                    if(this.formOperate == 'add'){ //新增or预览
                        switch (item.controlType){
                            case 'input':
                            case 'textarea':
                            case 'password':
                                let defaultValue = item.defaultVal; //缺省值
                                let defaultValText = item.defaultValText; //手动输入默认值
                                if(!defaultValText && defaultValue){
                                    if(defaultValue.indexOf('LOGINUSER') > -1 ||  defaultValue.indexOf('LOGINDEPT') > -1){
                                        this.$set(this.contentForm,item.fieldId,Replace.def(this.loginUser,defaultValue));
                                    }
                                    else if(defaultValue.indexOf('SYSTIME.time') > -1){
                                        this.$set(this.contentForm,item.fieldId,this.viewDateFormat(new Date(),'yyyy-MM-dd HH:mm:ss'));
                                    }else{
                                        this.$set(this.contentForm,item.fieldId,'');
                                    }
                                }else if(defaultValText){
                                    //替换长文本
                                    this.$set(this.contentForm,item.fieldId,Replace.text(null,defaultValText));
                                }else{
                                    this.$set(this.contentForm,item.fieldId,'');
                                }
                                break;
                            case  'select':
                                this.$set(this.contentForm,item.fieldId,item.spdefaultVal);
                                break;
                            case  'radio':
                                //默认单选框选中
                                this.$set(this.contentForm,item.fieldId,item.spdefaultVal);
                                break;
                            case 'checkbox':
                                if(typeof  item.spdefaultVal == 'string'){
                                    this.contentForm[item.fieldId] = [];
                                }else {
                                    this.contentForm[item.fieldId] = item.spdefaultVal || [];
                                }
                                break;
                            case 'time':
                                let startTime = ""; //开始时间
                                let endTime = "";  //结束时间
                                let startTimeArr = []; //开始时间数组
                                let endTimeArr = []; //结束时间数组
                                //计算结束时间(取最小日期 系统时间、比较字段,自定义时间)
                                (item.maxDate||[]).forEach(date =>{ //表单视图中比较字段排除
                                    if(date === '自定义时间'){
                                        endTime = item.diyTimeMax; //自定义最大时间
                                    }
                                    if(date === '系统时间'){
                                        endTime = this.viewDateFormat(new Date(),item.displayFormatter || 'yyyy-MM-dd');
                                    }
                                    if(endTime){
                                        endTimeArr.push(endTime);//最大时间
                                    }
                                });
                                //计算开始时间(取最大日期 系统时间、比较字段,自定义时间)
                                (item.minDate || []).forEach(date =>{
                                    if(date === '自定义时间'){
                                        startTime = item.diyTimeMin; //自定义最大时间
                                    }
                                    if(date === '系统时间'){
                                        startTime = this.viewDateFormat(new Date(),item.displayFormatter || 'yyyy-MM-dd');
                                    }
                                    if(startTime){
                                        startTimeArr.push(startTime);//最大时间
                                    }
                                });
                                //获取最大时间数组中最的最小值
                                let endDate =  this.getMinDateInMaxDateArr(endTimeArr);
                                let startDate = this.getMaxDateInMinDateArr(startTimeArr);
                                if(item.defaultValueType == '系统时间'){
                                    this.contentForm[item.fieldId] = this.viewDateFormat(new Date(),item.displayFormatter || 'yyyy-MM-dd');
                                }else if(item.diyDefaultVal){
                                    this.contentForm[item.fieldId] = item.diyDefaultVal;
                                }
                                this.$set(item,'endDate',endDate);
                                this.$set(item,'startDate',startDate);
                                break;
                            case 'contactParty': //联系方
                                break;
                            case 'pictureSet': //图片
                                break;
                            case 'addComments': //追加意见
                                break;
                            default:
                        }
                    }else{ //修改或查看
                        switch (item.controlType){
                            case 'radio':
                                break;
                            case "select":
                                if(item.multiple){
                                    if(this.contentForm[fieldId]){
                                        if(typeof this.contentForm[fieldId] == 'string'){
                                            this.$set(this.contentForm,fieldId,this.contentForm[fieldId].split(","));
                                        }
                                    }else{
                                        this.$set(this.contentForm,fieldId,[]);
                                    }
                                }
                                break;
                            case "checkbox":
                                if(this.contentForm[fieldId]){
                                    if(typeof this.contentForm[fieldId] == 'string'){
                                        this.$set(this.contentForm,fieldId,this.contentForm[fieldId].split(","));
                                    }
                                }else{
                                    this.$set(this.contentForm,fieldId,[]);
                                }
                                break;
                            default:
                                break;
                        }
                    }
                    //绑定验证
                    if(this.formOperate != 'view'){ //查看状态下不需要添加验证
                        this.buidRules(item); //绑定验证
                        this.bindViewsEvent(item.fieldId); //绑定验证
                    }
                });
            },

            /**
             * 文本域组件验证
             */
            buidRules(obj){
                let vm = this;
                let validFunArr = []; // 多个验证数组
                if(obj.isRequired == "1" && obj.editable != "false"){
                    vm.requiredStars[obj.fieldId] = '1';   //非空验证前加星星
                    validFunArr.push({required: true, message: '必填'});
                }
                if(obj.validRuleArr){
                    // console.log("obj...."+obj.showName,obj.validRuleArr);
                    let validFunChArr = obj.validRuleArr || [];
                    let otherParam = {min:obj.minNumValue,max:obj.maxNumValue,regExp:obj["diyValidVal"]};
                    if(validFunChArr.length > 0){
                        const validOrFn = vm.platValidator.mulOrValidator.bind(null,validFunChArr,otherParam);
                        validFunArr.push({validator:validOrFn,trigger: 'blur'});
                    }
                }
                vm.$set(vm.textFieldRules, obj.fieldId, validFunArr);
            },

            /**
             * 绑定表单视图事件
             */
            bindViewsEvent(field){
                if(this.viewsEventMap && this.viewsEventMap[field]){
                    const evtKeys = Object.keys(this.viewsEventMap[field]);
                    let evt = null;
                    evtKeys.forEach(evtKey => {
                        evt = this.viewsEventMap[field][evtKey];
                        if(!this.$on[field]){
                            this.$set(this.$on,field,{});
                        }
                        this.$set(this.$on[field],evtKey,evt.bind(this,...this.argumens));
                    });
                }
            },

            /**
             * 格式化日期type
             **/
            formatterDateType(displayFormatter){
                let type = "date";
                if(displayFormatter === 'yyyy-MM-dd'){
                    type = 'date';
                }else if(displayFormatter === 'yyyy-MM-dd HH:mm:ss'){
                    type = 'datetime';
                }else if(displayFormatter === 'yyyy'){
                    type = 'year';
                }else if(displayFormatter === 'yyyy-MM'){
                    type = 'month';
                }else{
                    type = 'datetime';
                }
                return type;
            },

            /**
             * 时间格式化方法（查看表单视图时用到）
             * @param d
             * @param fmt
             * @return {string|void}
             */
            viewDateFormat(d, fmt) {
                if (d) {
                    let date = new Date(d);
                    let o = {
                        "M+": date.getMonth() + 1,                 //月份
                        "d+": date.getDate(),                    //日
                        "H+": date.getHours(),                   //小时
                        "m+": date.getMinutes(),                 //分
                        "s+": date.getSeconds(),                 //秒
                        "q+": Math.floor((date.getMonth() + 3) / 3), //季度
                        "S": date.getMilliseconds()             //毫秒
                    };
                    if (/(y+)/.test(fmt)){
                        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
                    }
                    for (let k in o){
                        if (new RegExp("(" + k + ")").test(fmt)){
                            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
                        }
                    }
                } else {
                    fmt = '';
                }
                return fmt;
            },

            /**
             * 获取日期数组中的最小值
             * */

            getMinDateInMaxDateArr(maxTimeArr){
                let maxTime = '';
                if(maxTimeArr && maxTimeArr.length > 0){
                    maxTime =     maxTimeArr.reduce(function (a,b) {
                        return   new Date(a).getTime() <= new Date(b).getTime() ? a:b;

                    });
                }
                return maxTime;
            },

            getMaxDateInMinDateArr(minTimeArr){
                let minTime = '';
                if(minTimeArr && minTimeArr.length > 0){
                    minTime =     minTimeArr.reduce(function (a,b) {
                        return   new Date(a).getTime() >= new Date(b).getTime() ? a:b;
                    });
                }
                return minTime;
            },

        }
    }
</script>

<style scoped>
    .main-div-comp{
        min-height: 100px;
        position: relative;
    }
    .main-div-comp-div{
        float: left;
    }
</style>
