<template>
    <div id="replaceRule">
        <!--替换规则-->
        <div>
            <div class="opt-category-title"><p style="padding-left: 5px;"><b>替换规则</b></p></div>
            <div>
                <awsui-row v-for="(item, n) in ruleData" class="row">
                    <awsui-col :span="2">
                        <div style="text-align: center;line-height: 30px;height: 30px;">
                            <span>将</span>
                        </div>
                    </awsui-col>
                    <awsui-col :span="8">
                        <awsui-input style="font-size: 0px" v-model="item.propertyName" placeholder="请选择属性" readonly @click.native="openAttrTree(n)"></awsui-input>
                        <awsui-input type="hidden" v-model="item.propertyKey" placeholder="请选择属性"></awsui-input>
                    </awsui-col>
                    <awsui-col :span="4">
                        <div style="text-align: center;">
                            <span>的值更新为</span>
                        </div>
                    </awsui-col>
                    <awsui-col :span="10">
                        <div style="padding-right: 25px;">
                            <!--单选类型-->
                            <awsui-select v-if="item.propertyType == 'select'" clearable v-model="item.propertyValue" :options="item.selectTypeOpts"></awsui-select>
                            <!--多选类型-->
                            <awsui-select v-else-if="item.propertyType == 'select_m'" multiple clearable v-model="item.propertyValue" :options="item.selectTypeOpts"></awsui-select>
                            <!--是否类型-->
                            <awsui-select v-else-if="item.propertyType == 'boolean'" v-model="item.propertyValue" :options="item.selectTypeOpts"></awsui-select>
                            <!--数字类型-->
                            <awsui-input-number v-else-if="item.propertyType == 'number'" v-model="item.propertyValue"></awsui-input-number>
                            <!--关联PAL类型-->
                            <awsui-input v-else-if="item.propertyType == 'relation'" v-model="item.propertyShowValue" placeholder="请选择" readonly @click.native="openPalRelationAddress(n)"></awsui-input>
                            <!--关联BPM组织架构类型-->
                            <awsui-input v-else-if="item.propertyType == 'awsorg'" v-model="item.propertyShowValue" placeholder="请选择" readonly @click.native="openBpmOrgAddress(n)"></awsui-input>
                            <!--文本、多行文本、其他类型-->
                            <awsui-input v-else v-model="item.propertyValue" placeholder="请输入"></awsui-input>
                        </div>
                        <i class="awsui-iconfont operate-icon-display" style="float: right;position: relative; top: -22px;padding-right: 5px;" @click="removeRowRule(n)">&#xe626;</i>
                    </awsui-col>
                </awsui-row>
            </div>
            <div>
                <div style="display: inline-block;border-top:1px solid #c2c2c2;position: relative;bottom: -3px;width:100%;"></div>
                <div class="cursor-pointer" style="display: inline-block;background-color:white;position: relative;bottom: 10px;left: 40px;" @click="addRule"><u>+添加规则</u></div>
            </div>
        </div>
        <!--筛选结果-->
        <div>
            <div class="opt-category-title" style="margin-top: 10px;"><p style="padding-left: 5px;"><b>筛选结果（<span>{{resultCount}}</span>）</b></p></div>
            <div v-if="conditionData.type == 'file'">
                <el-table
                        :data="fileTableData"
                        @selection-change="handleSelectionChange"
                        style="width: 100%">
                    <el-table-column
                            type="selection"
                            align="center"
                            min-width="5%">
                    </el-table-column>
                    <el-table-column
                            prop="name"
                            label="文件名称"
                            min-width="35%">
                    </el-table-column>
                    <el-table-column
                            prop="namePath"
                            label="路径"
                            min-width="25%">
                    </el-table-column>
                    <el-table-column
                            prop="updateDate"
                            align="center"
                            min-width="20%"
                            label="最后修改">
                        <template slot-scope="scope">
                            <div style="text-align: center;">
                                <p>{{scope.row.updateDate}}</p>
                                <p>({{scope.row.updateUser}})</p>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div v-if="conditionData.type == 'shape'">
                <el-table
                        :data="shapeTableData"
                        @selection-change="handleSelectionChange"
                        style="width: 100%">
                    <el-table-column
                            type="selection"
                            align="center"
                            min-width="5%">
                    </el-table-column>
                    <el-table-column
                            prop="name"
                            label="文件名称"
                            min-width="25%">
                    </el-table-column>
                    <el-table-column
                            prop="shapeName"
                            label="形状名称"
                            min-width="10%">
                    </el-table-column>
                    <el-table-column
                            prop="namePath"
                            label="路径"
                            min-width="30%">
                    </el-table-column>
                    <el-table-column
                            prop="updateDate"
                            align="center"
                            min-width="20%"
                            label="最后修改">
                        <template slot-scope="scope">
                            <div style="text-align: center;">
                                <p>{{scope.row.updateDate}}</p>
                                <p>({{scope.row.updateUser}})</p>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </div>
        <BPMOrgAddress
                ref="palAwsOrgAddress"
                :visible.sync="bpmOrgAddress.visible"
                :addressType="bpmOrgAddress.addressType"
                v-on:cancel="bpmOrgAddress.visible = false"
                v-on:getResult="saveBpmOrgAddressResult"
                :title="bpmOrgAddress.title"
                :multiple="bpmOrgAddress.multiple"
        />
        <pal-relation-address
                ref="palRelationAddress"
                :visible.sync="palRelationAddress.visible"
                v-on:cancel="palRelationAddress.visible = false"
                v-on:getResult="saveRelationResult"
                :title="palRelationAddress.title"
                :selectFileId="palRelationAddress.selectFileId"
                :selectShapeId="palRelationAddress.selectShapeId"
                :relationType="palRelationAddress.relationType"
                :categorys="palRelationAddress.category"
                :methods="palRelationAddress.method"
                :wsId="palRelationAddress.wsId"
                :teamId="palRelationAddress.teamId"
                :multiple = palRelationAddress.multiple
        />
        <pal-attribute-tree
                ref="palAttributeTree"
                :visible.sync="attributeDlg.visible"
                :methodId="attributeDlg.methodId"
                :type="attributeDlg.type"
                v-on:cancel="attributeDlg.visible = false"
                v-on:getResult="saveAttrTreeResult"
        />
    </div>
</template>

<script>
    import awsuiAxios from "../../awsuiAxios";
    import BPMOrgAddress from  "./components/BPMOrgAddress";// pal平台组织架构地址簿，调用平台部门人员角色
    import PalRelationAddress from  "./components/PalRelationAddress";
    import PalAttributeTree from './components/PalAttributeTree/index';
    export default {
        name: "replace-rule",
        components: {BPMOrgAddress, PalRelationAddress, PalAttributeTree},
        props: {
            conditionData: {// 上一步的结果
                type: Object,
                default: function () {
                    return {}
                }
            }
        },
        data() {
            return {
                resultCount: 0,
                wsId: wsId,
                teamId: teamId,
                attributeDlg: {
                    visible: false,
                    methodId: '',
                    type: '',
                    currRow: 0
                },
                bpmOrgAddress: {
                    visible: false,
                    addressType: 'user',
                    title: '',
                    multiple: false,
                    currRow: 0
                },
                palRelationAddress: {
                    visible: false,
                    selectFileId: '',
                    selectShapeId: '',
                    relationType: '',
                    category: '',
                    method: '',
                    wsId: wsId,
                    teamId: teamId,
                    multiple: false,
                    currRow: 0
                },
                palId: palId,// 判断是否设计器内部的批量替换，不为空则是设计器内部调用
                ruleData: [
                    {
                        "propertyName": "",
                        "propertyKey": "",
                        "propertyType": "string",
                        "propertyCondition": "equals",
                        "propertyValue": ""
                    }
                ],
                fileTableData: [],
                shapeTableData: [],
                checkedTableData: {},// 已选中的数据记录
            }
        },
        mounted() {
            this.queryFilterResultData();
        },
        methods: {
            queryFilterResultData() {// 查询符合条件的筛选数据
                const that = this;
                const data = {
                    url:'jd',
                    data:{
                        cmd : "com.actionsoft.apps.coe.pal.batch_replace_process_condition_result_query",
                        conditionData : JSON.stringify(that.conditionData)
                    }
                };
                awsuiAxios.post(data).then(function (ro) {
                    if (ro.result == 'ok') {
                        if (that.conditionData.type == 'file') {
                            that.resultCount = ro.data.data.length;
                            for (let i = 0; i < ro.data.data.length; i++) {
                                ro.data.data[i].idVal = ro.data.data[i].versionId;
                            }
                            that.fileTableData = ro.data.data;
                        } else {
                            let count = 0;
                            const shapeTableData = [];
                            for (let i = 0; i < ro.data.data.length; i++) {
                                const curr = ro.data.data[i];
                                const shapeList = curr.shape;
                                for (let j = 0; j < shapeList.length; j++) {
                                    count++;
                                    const shape = shapeList[j];
                                    shapeTableData.push({
                                        id: curr.id + ',' + shape.id,
                                        idVal: curr.id,
                                        name: curr.name,
                                        shapeName: shape.name,
                                        namePath: curr.namePath,
                                        updateDate: curr.updateDate,
                                        updateUser: curr.updateUser
                                    })
                                }
                            }
                            that.resultCount = count;
                            that.shapeTableData = shapeTableData;
                        }
                    } else if (ro.result == 'warning') {
                        that.$message({message: ro.msg, type: 'warning'});
                    } else {
                        that.$message.error(ro.msg);
                    }
                }).catch(error=>{
                    console.log(error);
                })
            },
            handleSelectionChange(tableList) {// 表格数据选择监听
                this.checkedTableData = {};
                for (let i = 0; i < tableList.length; i++) {
                    this.checkedTableData[tableList[i].id] = tableList[i].idVal;
                }
            },
            removeRowRule(n) {// 删除行替换
                this.ruleData.splice(n, 1);
            },
            addRule() {// 添加替换规则
                this.ruleData.push({
                    "propertyName": "",
                    "propertyKey": "",
                    "propertyType": "string",
                    "propertyCondition": "equals",
                    "propertyValue": ""
                })
            },
            openBpmOrgAddress(n) {// 打开关联BPM组织架构数据选择
                const that = this;
                that.bpmOrgAddress.currRow = n;
                const row = this.ruleData[this.bpmOrgAddress.currRow];
                const ref = row.ref;

                const scope = ref.scope;
                that.bpmOrgAddress.addressType = scope.join(',');
                that.bpmOrgAddress.multiple = ref.multiple;
                that.bpmOrgAddress.title = row.propertyName;
                that.bpmOrgAddress.visible = true;
            },
            saveBpmOrgAddressResult(data) {// 关联BPM组织架构数据回调
                this.bpmOrgAddress.visible = false;
                // 保存
                const params = {};
                const propertyShowValue = [];
                for (let i = 0; i < data.length; i++) {
                    params[data[i].id] = {name: data[i].name, id: data[i].id, type: data[i].type};
                    propertyShowValue.push(data[i].name);
                }
                const row = this.ruleData[this.bpmOrgAddress.currRow];
                row.propertyValue = JSON.stringify(params);
                row.propertyShowValue = propertyShowValue.join(',');
            },
            openPalRelationAddress(n) {// 打开关联PAL组织架构数据选择
                const that = this;
                that.palRelationAddress.currRow = n;
                const row = this.ruleData[this.palRelationAddress.currRow];
                const ref = row.ref;
                const propertyValue = JSON.parse(row.propertyValue);
                const selectFileId = [];
                const selectShapeId = [];
                for (let j = 0; j < propertyValue.length; j++) {
                    selectFileId.push(propertyValue[j].relationFileId);
                    selectShapeId.push(propertyValue[j].relationShapeId);
                }
                this.palRelationAddress.relationType = ref.type;
                this.palRelationAddress.multiple = ref.multiple;
                this.palRelationAddress.title = row.propertyName;
                this.palRelationAddress.selectFileId = selectFileId.join(',');
                this.palRelationAddress.selectShapeId = selectShapeId.join(',');
                if (ref.method.indexOf('.') > 0) {
                    this.palRelationAddress.method = ref.method;
                    this.palRelationAddress.category = ref.method.split('.')[0];
                } else {
                    this.palRelationAddress.category = ref.method;

                }
                this.palRelationAddress.visible = true;
            },
            saveRelationResult(data) {// 关联PAL组织架构数据回调
                this.palRelationAddress.visible = false
                const row = this.ruleData[this.palRelationAddress.currRow];
                const ref = row.ref;
                const propertyValue = [];
                if (ref.type == 'file') {
                    for (let i = 0; i < data.length; i++) {
                        propertyValue.push({
                            fileId : "",
                            shapeId : "",
                            shapeText : "",
                            attrId : "",
                            relationFileId : data[i].versionId,
                            relationShapeId : '',
                            relationShapeText : data[i].name
                        });
                    }
                } else {
                    for (let i = 0; i < data.length; i++) {
                        const currFile = data[i];
                        const children = currFile.children;
                        for (let j = 0; j < children.length; j++) {
                            const currShape = children[j];
                            propertyValue.push({
                                fileId : "",
                                shapeId : "",
                                shapeText : "",
                                attrId : "",
                                relationFileId : currFile.id,
                                relationShapeId : currShape.shapeId,
                                relationShapeText : currShape.name
                            });
                        }
                    }
                }
                const propertyShowValue = [];
                row.propertyValue = JSON.stringify(propertyValue);
                for (let i = 0; i < propertyValue.length; i++) {
                    propertyShowValue.push(propertyValue[i].relationShapeText);
                }
                row.propertyShowValue = propertyShowValue.join(',');
            },
            openAttrTree(n) {// 打开自定义属性树组件
                const that = this;
                // 查询特性树
                that.attributeDlg.currRow = n;
                that.attributeDlg.methodId = that.conditionData.methodId;
                that.attributeDlg.type = that.conditionData.type;
                that.attributeDlg.visible = true;
            },
            saveAttrTreeResult(data) {// 选择属性树点击确定按钮
                const row = this.ruleData[this.attributeDlg.currRow];
                row.propertyName = data.label;
                row.propertyKey = data.id;
                row.propertyType = 'string';// 先默认string，在nextTick中重新渲染对应的类型
                row.propertyValue = '';
                row.selectTypeOpts = [];
                row.propertyShowValue = '';
                row.ref = data.ref;
                this.$nextTick(function() {
                    row.propertyType = data.attrType;
                    if (data.attrType == 'select' || data.attrType == 'select_m' || data.attrType == 'boolean') {
                        row.selectTypeOpts = [];
                        const refArr = data.ref.split(',');
                        for (let i = 0; i < refArr.length; i++) {
                            row.selectTypeOpts.push({value: refArr[i], label: refArr[i]});
                        }
                    } else if (data.attrType == 'relation' || data.attrType == 'awsorg') {
                        row.propertyShowValue = '';
                        row.propertyValue = JSON.stringify([]);
                    }
                    this.attributeDlg.visible = false;
                })
            },
            getResults() {// 获取筛选结果
                const param = {
                    wsId : wsId,
                    teamId : teamId,
                    uuid : palId,
                    methodId : this.conditionData.methodId,
                    type : this.conditionData.type,
                    conditionData : this.conditionData,
                    data: {},
                    isOk: true,
                    msg: ''
                };
                const replaceRule = [];
                // 筛选条件
                for (let i = 0; i < this.ruleData.length; i++) {
                    const row = this.ruleData[i];
                    if (row.propertyKey != undefined && row.propertyKey != '') {
                        var rowObj = {};
                        rowObj.propertyName = row.propertyName;
                        rowObj.propertyKey = row.propertyKey;
                        rowObj.propertyType = row.propertyType;
                        rowObj.propertyValue = row.propertyValue;
                        replaceRule.push(rowObj);
                    }
                }
                if (replaceRule.length == 0) {
                    param.isOk = false;
                    param.msg = '请添加替换规则';
                } else {
                    // 校验是否有重复属性
                    var key = {};
                    for (let rule in replaceRule) {
                        if (key[replaceRule[rule].propertyKey] != undefined) {
                            param.isOk = false;
                            param.msg = "属性[" + replaceRule[rule].propertyName + "]不允许重复";
                            break;
                        }
                        key[replaceRule[rule].propertyKey] = "";
                    }
                }
                param.replaceRule = replaceRule;
                // 筛选结果
                if (param.isOk) {
                    param.data = this.checkedTableData;
                    if (JSON.stringify(param.data) == "{}") {
                        param.isOk = false;
                        if (this.conditionData.type == 'file') {
                            param.msg = "请选择替换的流程文件";
                        } else {
                            param.msg = "请选择替换的流程形状";
                        }
                    }
                }
                return param;
            }
        }
    }
</script>

<style scoped>
    .opt-category-title {
        height: 25px;
        line-height: 25px;
        vertical-align: center;
        margin: 20px 30px 15px 20px;
        border-left: 3px solid #4E7FF9;
    }
    #replaceRule >>> .row:hover .operate-icon-display{
        visibility: visible;
    }
    .cursor-pointer {
        cursor: pointer;
        color: #4E7FF9;
    }
    #replaceRule >>> .row .operate-icon-display{
        visibility: hidden;
        cursor: pointer;
        color: red;
    }
</style>