<template>
    <!-- 添加编辑审批流 -->
    <div class="approve-edit-wrap approve-page-wrap" v-if="isETAApprove">
        <div class="head-box">
            <el-form :inline="true" :model="approveForm" ref="approve-form" :rules="formRules"
                label-width="100px" label-position="left">
                <el-form-item label="审批流名称" prop="name">
                    <el-input v-model="approveForm.name" :disabled="this.$route.query.flowId" placeholder="请输入审批流名称"></el-input>
                </el-form-item>
                <el-form-item label="关联报告" prop="classify">
                    <el-cascader v-model="approveForm.classify"
                        placeholder="请选择关联报告" clearable
                        :disabled="this.$route.query.flowId"
                        :options="classifyTree"
                        :props="{value:'ClassifyId',label:'ClassifyName',children:'Children'}"
                        style="margin-right: auto;margin-left: 15px;"></el-cascader>
                </el-form-item>
            </el-form>
            <div class="form-btn">
                <el-button type="primary" plain @click="$router.back()">取消</el-button>
                <el-button v-permission="permissionBtn.approveFlowPermission.reportApprove_save"
                    type="primary" @click="checkFlow">保存</el-button>
            </div>
        </div>
        <div class="form-item" style="color:#606266;width:100px;">
            <span style="color:#F56C6C;margin-right: 4px;">*</span>流程配置
        </div>
        <!-- 审批流画布 -->
        <div class="flow-editor-wrap">
            <FlowEdiotr
                ref='floweditor'
                :flowNodes="approveForm.flowNodes"
            />
        </div>
    </div>
    <div class="approve-page-wrap" v-else>
        <tableNoData :text="pageLoading?'':'系统暂未开通审批流程，请开启审批流程后再进行操作！'"></tableNoData>
    </div>
</template>

<script>
import FlowEdiotr from './components/flowEdiotr';
import {approveInterence} from '@/api/modules/approve.js';
import approveMixins from './mixins/approveMixins';
import reportApproveConfig from "@/mixins/reportApproveConfig.js"
const findParentNode = (arr, id)=>{
      // 遍历取父级code push数组
      for (let i of arr) {
        if (i.ClassifyId === id) {
          return [i.ClassifyId];
        }
        if (i.Children) {
          let node = findParentNode(i.Children, id);
          if (node) {
            return node.concat(i.ClassifyId);
          }
        }
      }
    }
export default {
    mixins:[approveMixins,reportApproveConfig],
    data() {
        return {
            approveForm:{
                name:'',
                classify:'',
                /* flowNodes:null */
            },
            formRules:{
                name:[{ required: true, message: '请输入审批流名称名称', trigger: 'blur' },
                      { max: 20, message: '长度在20个字符内', trigger: 'change' }],
                classify:[{ required: true, message: '请选择关联报告', trigger: 'blur' },]
            },

        };
    },
    methods: {
        async checkFlow(){
            //检查name,region是否为空
            await this.$refs["approve-form"].validate()
            //检查审批流内容:每个审批节点是否都选择了审批人
            const data = this.$refs.floweditor.flowData
            if(data.length<3){
                this.$message.warning("请添加审批节点")
                return
            }
            for(let item of data){
                if(item.nodeType===2&&!item.approvers.length){
                    this.$message.warning("有节点未选择审批人,请检查")
                    return
                }
            }
            let Nodes = []
            //不需要data的第一项和最后一项,其余转换为接口所需格式
            for(let i=1;i<data.length-1;i++){
                const Users = data[i].approvers.map((item,index)=>{
                    return {
                        UserType:'user',//目前只有审批节点,都是user
                        UserId:item.ItemId,
                        UserName:item.ItemName,
                        Sort:data[i].ApproveType===1?index+1:0
                    }
                })
                Nodes.push({
                    ApproveType:data[i].ApproveType,
                    Users
                })
            }
            this.modifyFlow(Nodes)
        },
        async modifyFlow(Nodes){
            const {name,classify} = this.approveForm
            const params = {
                FlowName:name,
                ReportType:classify[0],
                ClassifyFirstId:classify[classify.length-2]||0,
                ClassifySecondId:classify[classify.length-1]||0,
                Nodes
            }
            let res
            const id = this.$route.query.flowId||0
            if(id){
                res = await approveInterence.editApproveFlow({
                    ...params,
                    ReportApproveFlowId:Number(id)
                })
            }else{
                res = await approveInterence.addNewApproveFlow(params)
            }
            if(res.Ret!==200) return
            this.$message.success(`${id?'编辑':'新增'}成功`)
            this.$router.push('/approveSetting')
        },
        getFlowDetail(){
            const id = this.$route.query.flowId||0
            if(id){
                approveInterence.getApproveFlowDetail({
                    ReportApproveFlowId:Number(id)
                }).then(res=>{
                    if(res.Ret!==200) return 
                    const {FlowName,ReportType,ClassifySecondId,Nodes} = res.Data||{}
                    this.approveForm.name = FlowName||''
                    //递归获取所有父级id
                    const classify = this.classifyTree.find(i=>i.ClassifyId===ReportType)||{}
                    const tempArr = findParentNode(classify.Children||[],ClassifySecondId)
                    tempArr.push(ReportType)
                    this.approveForm.classify = tempArr.reverse()
                    this.approveForm.flowNodes = Nodes||[]
                })
            }
        }
    },
    async mounted(){
        this.getClassifyTree()
    },
    components: { FlowEdiotr }
};
</script>
<style lang="scss">
.approve-edit-wrap{
    .el-form-item__content{
        flex: 1;
    }
}
</style>
<style scoped lang="scss">
@import url('./css/pageStyle.scss');
.approve-edit-wrap{
    display: flex;
    flex-direction: column;
    height: calc(100vh - 120px);
    .head-box{
        display: flex;
        justify-content: space-between;
        .el-form{
            flex:1;
            .el-input,.el-cascader{
                min-width: 200px;
                max-width: 420px;
                width:100%;
            }
            .el-form-item{
                width:45%;
                display: inline-flex;
            }

        }
    }
    .flow-editor-wrap{
        padding-left: 100px;
        overflow: auto;
    }
}
</style>
