<template>
    <el-container style="height: 100%">
        <el-main style="height: 100%;" ref="tableMain">
            <el-table :data="datas" :ref="crud.tableRef" stripe border height="100%"
                      style="width: 100%;" @cell-click="openDetails">
<!--                <el-table-column type="selection" width="40" align="center"></el-table-column>-->
                <el-table-column type="index" label="序号" align="center" width="60"></el-table-column>
                <el-table-column label="变更人" prop="updateDataUserName" align="center" width="200"></el-table-column>
                <el-table-column label="变更时间" prop="updateDataTime" align="center" width="300"></el-table-column>
                <el-table-column label="变更内容" prop="updateContentResult" show-overflow-tooltip align="center" min-width="300"></el-table-column>
            </el-table>
        </el-main>
    </el-container>
</template>

<script>
    export default {
        name: "update-record-list",
        props:{
            formId:{type:String,required:true},
            dataId:{type:String,required:true},
            logEvidence:{type:String,default:""},
            excludeField:{type:String,default:""}
        },
        data(){
            return {
                crud: new this.CrudUtil({
                    vue: this,
                    entityName: "plUpdateRecord",
                    url:this.api.plUpdateRecord.url,
                    searchUrl: this.api.plUpdateRecord.find,
                    searchForm: {"formId": this.formId, "dataId": this.dataId,order: 'CREATE_TIME desc',},
                    noClearSearchColumns: ["formId", "dataId"],
                    initNoSearch:true,
                    excludeFieldArr:[],
                }),
                datas:[],
            }
        },
        created() {
            this.excludeFieldArr = (this.excludeField || "").split(",");
            this.crud.search(this.dealData);
        },
        methods:{
            dealData(vm,result){
                let fieldIdToName = {};
                let evidenceArr = []; //变更记录
                this.spcpFormAxios.post(this.api.plFormField.find,{"formId":this.formId}).then(res => {
                    (res.data || []).forEach(value => {
                        fieldIdToName[value.id] = value.chfieldName;
                    });

                    this.datas = result || [];
                    let evidenceIndex = 0;
                    this.datas.forEach(item => {
                        let updateContent = JSON.parse(item.updateContent || "{}");
                        let updateContentResult = "";
                        // 解析字段变更描述
                        this.$set(item,'evidenceIndex',evidenceIndex);
                        Object.keys(updateContent).forEach(key => {
                            let change = updateContent[key] || {};
                            if(change["type"] == "upload"){ // 附件
                                // 新增和删除存在时提示变更
                                if((change["add"] || []).length > 0 || (change["delete"] || []).length > 0){
                                    let uploadResult = "";
                                    if((change["add"] || []).length > 0){
                                        uploadResult += ("“" + change["name"] + "”新增附件“" + change["add"].join("”,“") + "”");
                                    }
                                    if((change["delete"] || []).length > 0){
                                        if(!uploadResult){
                                            uploadResult += ("“" + change["name"] + "”");
                                        }else{
                                            uploadResult += ",";
                                        }
                                        uploadResult += ("删除附件“" + change["add"].join("”,“") + "”;");
                                    }else{
                                        uploadResult += ";";
                                    }
                                    updateContentResult += uploadResult;
                                }
                            }else{
                                let temKey = key;
                                if(updateContent[key + "_sequence"]){ // 有自增序列
                                    return;
                                }
                                if(key.indexOf("_sequence")){
                                    temKey = temKey.replace("_sequence","");
                                }
                                if(this.excludeFieldArr.indexOf(temKey) > -1){
                                    return;
                                }
                                updateContentResult += ("字段“" + (fieldIdToName[temKey] || "") + "”由“" + (change["old"] || "") + "”变更为“" + (change["new"] || "") + "”;");
                                if(this.logEvidence && key == this.logEvidence){ //记录当前id ,当前记录分组
                                    evidenceArr.push(item.id);
                                    evidenceIndex++;
                                    this.$set(item,'evidenceIndex',evidenceIndex);
                                }
                            }
                        })
                        if(!updateContentResult){
                            item["updateContentResult"] = "无内容变更";
                        }else{
                            if(item["updateType"] == "add"){
                                item["updateContentResult"] = "首次添加";
                            }else if(item["updateType"] == "delete"){
                                item["updateContentResult"] = "数据已删除";
                            }else{
                                item["updateContentResult"] = updateContentResult;
                            }
                        }
                    })
                    //对于配置了变更凭据的字段进行分组
                    let newDataArr = [];
                    if(evidenceArr.length > 0){
                        //根据 evidenceIndex 分组
                        let copyDatas = JSON.parse(JSON.stringify(this.datas));
                        copyDatas = this.getEvidenceIndex(copyDatas);
                        copyDatas.forEach(item =>{
                            let updateContentResultStr = "";
                            (item.data || []).forEach((data,index) =>{
                                if(data["updateContentResult"] != '无内容变更'){
                                    updateContentResultStr += data.updateContentResult +" ";
                                }
                            });
                            let obj = item.data[item.data.length -1];
                            this.$set(obj,'updateContentResult',updateContentResultStr);
                            newDataArr.push(obj);
                        });
                        this.datas = newDataArr;
                    }
                })
            },
            openDetails(row,column) {
                if(column["property"] == "updateContentResult"){
                    let arr = (row["updateContentResult"] || "").split(";");
                    let showHtml = arr.join(";<br/>")
                    this.$alert(showHtml, '变更内容', {
                        dangerouslyUseHTMLString: true,
                        confirmButtonText: '确定'
                    });
                }
            },

            // JS判断元素是否在数组内的实现代码
            contains(arr,obj) {
                let length = arr.length
                while(length--){
                    if(arr[length] === obj){
                        return true
                    }
                }
                return false
            },
            //排序
            compareSort(a,b){
                return Number(b["id"]) - Number(a["id"]);
            },

            /**
             *  根据 evidenceIndex 的分组
             * @param dataArr
             */
            getEvidenceIndex(dataArr){
                let map = {},
                    dest = [];
                dataArr.forEach(ai =>{
                    if(!map[ai.evidenceIndex]){
                        dest.push({
                            evidenceIndex: ai.evidenceIndex,
                            data: [ai]
                        });
                        map[ai.evidenceIndex] = ai;
                    }else{
                        dest.forEach(dj =>{
                            if(dj.evidenceIndex == ai.evidenceIndex){
                                dj.data.push(ai);
                            }
                        });
                    }
                });
                return dest;
            },
        }
    }
</script>

<style scoped>

</style>
