<template>
    <div :class="(userAuthority || ownerApply) && is_end == 0 && share != 1 ? 'approvalAction' : null">
        <m-header v-if="share != 1" :isNative="false">
            <template #right>
                <van-icon @click="onShare" :name="iconShare" style="transform: translateY(5px);" size="22"></van-icon>
            </template>
        </m-header>
        <!-- <van-notice-bar
            v-if="activeIndex !== nodeStepList.length && is_end===1"
            style="margin-bottom: .1rem"
            :text="alertMessage"
            :scrollable="false"
        /> -->

        <van-cell class="headerInfo" v-if="processStructureValue.workOrder.priority">
            <template #title>
                <div class="titleSection" v-if="title">
                    <span class="titleContent">{{ title }}</span>
                    <template v-if="processStructureValue.workOrder.priority===2">
                        <van-tag size="small" style="background: #fff9f6;vertical-align: text-bottom;" plain type="warning">紧急</van-tag>
                    </template>
                    <template v-else-if="processStructureValue.workOrder.priority===3">
                        <van-tag size="small" style="background: #fff6f7;vertical-align: text-bottom;" plain type="danger">非常紧急</van-tag>
                    </template>
                    <template v-else-if="processStructureValue.workOrder.priority===1">
                        <van-tag size="small" style="background: #edfff6;vertical-align: text-bottom;" plain type="success">一般</van-tag>
                    </template>
                </div>
                <template v-if="is_end == 0">
                    <span v-if="userAuthority" class="waitStatus">等待我审批</span>
                    <span v-else class="waitStatus">{{ principals }}</span>
                </template>
                <template v-else>
                    <template v-if="is_cancel == 0">
                        <span v-if="processStructureValue.workOrder.is_denied" class="waitStatus">审批拒绝</span>
                        <span v-else class="waitStatus">审批通过</span>

                        <img v-if="processStructureValue.workOrder.is_denied" class="imgStatus" src="./images/icon_reject.png" />
                        <img v-else class="imgStatus" src="./images/icon_resolve.png" />
                    </template>
                    <template v-else>
                        <span class="waitStatus">已关闭</span>
                        <img class="imgStatus" src="./images/icon_close_round.png" />
                    </template>
                </template>
            </template>
        </van-cell>

        <div style="margin: 0 .12rem .12rem;border-radius: .05rem;overflow: hidden;">
            <template v-for="(tplItem, tplIndex) in processStructureValue.tpls">
                <form-modal
                    style="padding-bottom: .12rem; background: #fff;"
                    :key="tplIndex"
                    v-if="(currentNode.hideTpls!==undefined &&
                        currentNode.hideTpls!==null &&
                        currentNode.hideTpls.indexOf(tplItem.form_structure.id)!==-1) ||
                        (currentNode.writeTpls===undefined ||
                        currentNode.writeTpls===null ||
                        currentNode.writeTpls.indexOf(tplItem.form_structure.id)===-1)"
                    :formData="tplItem.form_structure"
                    :value="tplItem.form_data"
                    :preview="true" />
            </template>
        </div>
        <template v-if="userAuthority">
            <van-form ref="headForm" validate-first @submit="onSubmitHead" :scroll-to-error="true" :show-error="false">
                <template v-for="(tplItem, tplIndex) in processStructureValue.tpls">
                    <form-modal
                        :key="tplIndex"
                        v-if="(currentNode.writeTpls!==undefined &&
                        currentNode.writeTpls!==null &&
                        currentNode.writeTpls.indexOf(tplItem.form_structure.id)>-1)?true:false"
                        :ref="'generateForm-'+tplItem.id"
                        :value="tplItem.form_data"
                        :formData="tplItem.form_structure" />
                </template>
            </van-form>
        </template>

        <div class="step_section" v-if="circulationHistoryList.length > 0">
            <div class="step_title">流程</div>
            <van-steps v-if="currentNode.clazz !== undefined && currentNode.clazz !== null && currentNode.clazz !== ''" :active="activeIndex"  direction="vertical" inactive-color="#D8D8D8" active-color="#D8D8D8">
                <template v-for="(item, index) in circulationHistoryList">
                    <van-step v-if="item.isHideNode === false ||
                    item.isHideNode === undefined ||
                    item.isHideNode == null ||
                    item.id === processStructureValue.workOrder.current_state"
                    :key="index" class="step">
                        <template #inactive-icon>
                            <i class="inactive-icon"></i>
                        </template>
                        <template #active-icon>
                            <van-icon :name="iconWait" />
                        </template>
                        <template #finish-icon>
                            <template v-if="item.circulation == '转交'">
                                <van-icon :name="iconSystemTransfer" />
                            </template>
                            <template v-else>
                                <van-icon :name="iconReject" v-if="item.status == 0" />
                                <van-icon :name="iconComplete" v-else />
                            </template>
                        </template>
                        <div class="step-t">
                            <p class="apply-state">{{ item.state || item.label }}</p>
                            <p class="apply-time">{{ item.create_time ? dayjs(item.create_time).format('MM-DD HH:mm') : null }}</p>
                        </div>
                        <!-- 判断是否有审核数据 -->
                        <template v-if="!item.create_time">
                            <p class="apply-status" v-if="item.assignUsers && item.assignUsers.length > 0">
                                <!-- 判断是否是自己审批 -->
                                <template v-if="item.assignUsers[0].userId == userInfo.userId && activeIndex == index">
                                    我（审批中）
                                </template>
                                <template v-else>
                                     <template v-if="item.isCounterSign">
                                        <span v-for="(au, aIndex) in item.assignUsers" :key="aIndex">
                                            {{ au.username }}{{ aIndex<(item.assignUsers.length-1) ? '，' : null }}
                                        </span>
                                    </template>
                                    <template v-else>
                                        {{ item.assignUsers[0].username }}
                                    </template>
                                    {{ activeIndex == index ? `（审批中）` : null }}
                                    <!-- {{ item.assignUsers[0].username }}{{ activeIndex == index ? `（审批中）` : null }} -->
                                </template>
                            </p>
                        </template>
                        <template v-else>
                            <p class="apply-status" v-if="item.processor">{{ item.processor }}{{ item.circulation ? `（${item.circulation}）` : null }}</p>
                            <p class="remarks" v-if="item.remarks">{{ item.remarks }}</p>
                        </template>
                        <!-- 有抄送人并且，本节点已经审批完成了 -->
                        <template v-if="item.cc_user && item.cc_user.length > 0 && activeIndex > index">
                            <!-- 已抄送1人 -->
                            <div class="ccUsers" @click="onCCChange(item)">
                                <span>已抄送{{ item.cc_user.length }}人</span>
                                <van-icon v-show="!item.ccStatus" style="color: #CCCCCC" name="arrow-down" />
                                <van-icon v-show="item.ccStatus" style="color: #CCCCCC" name="arrow-up" />
                            </div>
                            <div class="ccUserDetail" v-if="item.ccStatus">
                                <span>{{ item.cc_user.join(',') }}</span>
                            </div>
                        </template>
                    </van-step>
                </template>
            </van-steps>
        </div>

        <!-- 是自己审批 或者 是自己提交的记录 并且不是分享连接 -->
        <van-goods-action v-if="(userAuthority || ownerApply) && is_end == 0 && share != 1">
            <van-goods-action-icon v-if="is_end == 0 && ownerApply" :icon="iconDing" text="催办" @click="handleUrge" />
            <van-goods-action-icon v-if="is_end == 0 && ownerApply" :icon="iconClose" text="关闭" @click="handleUnity" />
            <van-goods-action-icon v-if="is_end == 0 && userAuthority" :icon="iconTransfer" text="转交" @click="exchange" />
            <template v-if="userAuthority">
                <van-goods-action-button
                    v-for="(item, index) in btn_group"
                    :key="index"
                    :type="item.className"
                    :disabled="submitDisabled"
                    :text="item.labelShow"
                    plain
                    @click="onCheckSubmit(item)"
                />
                <!-- 拒绝按钮内置 -->
                <van-goods-action-button
                    v-if="endNodeDetail.id"
                    :disabled="submitDisabled"
                    plain
                    :text="endNodeDetail.label" type="danger"
                     @click="onCheckSubmit(endNodeDetail)" />
            </template>
        </van-goods-action>

        <!-- 审批时填写意见 -->
        <van-popup v-model="showMarks" closeable class="markModel">
            <div class="popup-marks">
                <h2>确认{{ popupMarkTxt }}</h2>
                <van-field
                    name='remarks'
                    v-model="remarks"
                    type="textarea"
                    row="5"
                    :autosize=" { maxHeight: 300, minHeight: 180 }"
                    :placeholder="'请输入审批意见'"
                />
                <van-button type="info" round @click="popupSubmit">确认{{ popupMarkTxt }}</van-button>
            </div>
        </van-popup>

        <!-- 转交 -->
        <van-popup v-model="transferStatus" position="bottom" :style="{ height: '100%', width: '100%' }">
            <m-header name="转交" :backUrl="backUrl2" />
            <transfer-modal v-if="transferStatus" :popupForm="popupForm" :columns="columns" :nodeList="nodeList" />
        </van-popup>
    </div>
</template>
<script>
import MHeader from '@/components/MHeader'
import { processStructure, handleWorkOrder, sysUserList, urgeWorkOrder, getInfo, unityWorkOrder, asyncPlayLog } from './api'
import FormModal from './modal/formModal'
import TransferModal from './modal/transferModal'
import copy from "copy-to-clipboard";
import dayjs from 'dayjs'
export default {
    name: 'approvalAction',
    components: { MHeader, FormModal, TransferModal },
    data() {
        let query = this.$route.query
        return {
            iconComplete: require('./images/system-complete-default.png'),
            iconWait: require('./images/system-wait.png'),
            iconReject: require('./images/system-reject.png'),
            iconSystemTransfer: require('./images/system-transfer.png'),
            iconTransfer: require('./images/icon_transfer.png'),
            iconDing: require('./images/icon_ding.png'),
            iconClose: require('./images/icon_close.png'),
            iconShare: require('./images/icon_share.png'),
            showMarks: false,
            popupMarkTxt: null,
            backUrl2: {
                callBack: () => {
                    this.transferStatus = false
                }
            },
            dayjs,
            active: 0,
            // classify: query.classify,
            processId: query.processId,
            workOrderId: query.workOrderId,
            principals: null,
            share: query.share,
            title: null,
            submitDisabled: false,
            ruleForm: {
                title: '',
                priority: 1,
                process: '',
                classify: '',
                state: [],
                source: '',
                source_state: '',
                process_method: '',
                tpls: {
                    'form_structure': [],
                    'form_data': []
                },
                tasks: []
            },
            currentNode: {
                hideTpls: null,
                writeTpls: null
            },
            isActiveProcessing: false,
            tpls: [],
            remarks: '', // 备注信息
            alertMessage: '',
            nodeStepList: [],
            circulationHistoryList: [],
            endNodeDetail: {}, // 结束结节信息
            activeIndex: 0,
            processStructureValue: {
                workOrder: { title: '' }
            },
            selectItem: null,
            btn_group: [],
            transferStatus: false,
            columns: [],
            popupForm: {
                work_order_id: '',
                node_id: '',
                user_id: '',
                remarks: ''
            },
            userInfo: {},
            userAuthority: false, // 是否是自己审批
            ownerApply: false, // 是否是自己提交的申请
            is_end: 0, // 是否结束
            is_cancel: 0, // 是否取消
        }
    },
    async mounted() {
        await this.getProcessNodeList()
        if(this.share != 1) {
            await this.getUserInfo()
        }
    },
    methods: {
        onShare() {
            const url = window.location.href + '&share=1'
            copy(url);
            copy(url);
            this.$toast('分享连接复制成功')
        },
        // 获取对应元素的值
        getFormDataDetail(formData, model) {
            let modelStatus = {
                status: false,
                value: null
            }
            for(let data in formData) {
                if(typeof formData[data] == 'object') {
                    // 没有子表单里面有子表单
                    for(let child in formData[data]) {
                        if(child == model) {
                            modelStatus = {
                                status: true,
                                model: child,
                                value: formData[data][child] ? formData[data][child].split(',') : []
                            }
                        }
                    }
                } else {
                    if(data == model) {
                        modelStatus = {
                            status: true,
                            model: data,
                            value: formData[data] ? formData[data].split(',') : []
                        }
                    }
                }
            }
            return modelStatus
        },
        getSelectValueObject(tpls, type = 'value', tplValues = []) {
            const tempData = tpls || []
            let selectList = []
            tempData.forEach((temp, index) => {
                let tempList = temp.form_structure.list || []
                let tempSelectList = tplValues[index] || []
                let listArray = []
                tempList.forEach(list => {
                    if(list.type == 'select') {
                        if(type == 'value') {
                            const result = this.getFormDataDetail(temp.form_data, list.model)
                            if(result.status) {
                                listArray.push(result)
                            }
                        } else {
                            let selectOptions = []
                            let selectValue = []
                            tempSelectList.forEach(tsl => {
                                if(tsl.model == list.model) {
                                    selectOptions = list.options?.options || []
                                    selectValue = tsl.value || []
                                }
                            })
                            selectOptions.forEach(so => {
                              if(selectValue.includes(so.value)) {
                                  let tempRo = so.relationOptions || []
                                  listArray.push(...tempRo)
                              }
                            })
                        }
                    }
                    if(list.type == 'subform') {
                        let childList = list.columns || []
                        childList.forEach(child => {
                            let childList = child.list || []
                            childList.forEach(c => {
                                if(c.type == 'select') {
                                    if(type == 'value') {
                                        const originObj = JSON.parse(JSON.stringify(c))
                                        const result = this.getFormDataDetail(temp.form_data, originObj.model)
                                        if(result.status) {
                                            listArray.push(result)
                                        }
                                    } else {
                                        let selectOptions = []
                                        let selectValue = []
                                        tempSelectList.forEach(tsl => {
                                            if(tsl.model == c.model) {
                                                selectOptions = c.options?.options || []
                                                selectValue = tsl.value || []
                                            }
                                        })
                                        selectOptions.forEach(so => {
                                            if(selectValue.includes(so.value)) {
                                                let tempRo = so.relationOptions || []
                                                listArray.push(...tempRo)
                                            }
                                        })
                                    }
                                }
                            })
                        });
                    }
                })
                selectList.push(listArray)
            })
            return selectList
        },
        async getProcessNodeList() {
            try {
                let params = {
                    processId: this.processId,
                    workOrderId: this.workOrderId
                }
                const userId = sessionStorage.getItem('userId')
                if(this.share != 1 && userId) {
                    params.userId = userId
                }
                let res = await processStructure(params)
                this.isActiveProcessing = false
                let tempData = res.data.tpls
                // 获取对应模板中，下拉框的key, value
                let selectList = this.getSelectValueObject(tempData)

                // 获取对应模板中，需要隐藏的字段
                let hiddenFormList = this.getSelectValueObject(tempData, 'hiddenForm', selectList)

                tempData.forEach((temp, index) => {
                    let tempList = temp.form_structure.list || []
                    tempList.forEach(item => {
                        if(hiddenFormList[index].length > 0) {
                            if(item.type != 'text' && !item.options.relationStatus) {
                                item.hidden = true
                            } else {
                                item.hidden = false
                            }
                            // item.hidden = false
                            if(hiddenFormList[index].includes(item.model)) {
                                item.hidden = false
                            }
                        } else {
                            item.hidden = false
                        }
                        // 子表单
                        if(item.type == 'subform') {
                            let childList = item.columns || []
                            let subFormStatus = true
                            childList.forEach(child => {
                                let childList = child.list || []
                                childList.forEach(c => {
                                    if(hiddenFormList[index].length > 0) {
                                        if(c.type != 'text' && !c.options.relationStatus) {
                                            c.hidden = true
                                        } else {
                                            c.hidden = false
                                            subFormStatus = false
                                        }
                                        if(hiddenFormList[index].includes(c.model)) {
                                            c.hidden = false
                                            subFormStatus = false
                                        }
                                    } else {
                                        c.hidden = false
                                        subFormStatus = false
                                    }
                                })
                            });
                            item.hidden = subFormStatus
                        }
                    })
                })
                this.processStructureValue = res.data
                this.circulationHistoryList = this.processStructureValue.circulationHistory
                this.userAuthority = this.processStructureValue.userAuthority
                this.is_end = res.data.workOrder.is_end
                this.is_cancel = res.data.workOrder.is_cancel
                if(res.data.workOrder.title) {
                    this.title = res.data.workOrder.title
                }

                // 获取当前展示节点列表
                this.nodeStepList = []
                this.tempNodeStepList = []
                const nodes = this.processStructureValue.nodes
                this.principals = '处理中'
                for (var i = 0; i < nodes.length; i++) {
                    if (nodes[i].id === this.processStructureValue.workOrder.current_state) {
                        // 当前节点
                        this.nodeStepList.push(nodes[i])
                        this.activeIndex = this.nodeStepList.length - 1
                        if (i + 1 === nodes.length) {
                            this.activeIndex = this.nodeStepList.length
                        }
                        this.currentNode = nodes[i]

                        // 处理是认谁在处理,已处理完成则显示处理中
                        const assignUsers = nodes[i].assignUsers
                        if(assignUsers && assignUsers.length > 0) {
                            this.principals = assignUsers[0].username + '处理中'
                        }
                    } else if (!nodes[i].isHideNode) {
                        // 非隐藏节点
                        this.nodeStepList.push(nodes[i])
                    }

                    // 判断节点里面是否有结束节点，而且一个流程里面只能有一个结束结点，
                    if(nodes[i].clazz == 'end') {
                        this.endNodeDetail = JSON.parse(JSON.stringify(nodes[i]))
                        this.endNodeDetail.target = nodes[i].id
                        this.endNodeDetail.flowProperties = 0 // 拒绝属性
                        this.endNodeDetail.label = '拒绝'
                    }
                }
                this.circulationHistoryList.reverse()
                // 如果审批流程没有结束则，流程和历史记录合并显示；结束了，就只显示历史记录
                if (!this.is_end) {
                    this.circulationHistoryList.forEach(cir => {
                        this.nodeStepList.forEach(node => {
                            if(cir.source == node.id) {
                                cir.label = node.label
                                cir.assignType = node.assignType
                                cir.assignValue = node.assignValue
                                cir.assignUsers = node.assignUsers
                                cir.id = node.id
                            }
                        })
                    })

                    let tempNodes = []
                    this.nodeStepList.forEach(node => {
                        let count = 0
                        this.circulationHistoryList.forEach(cir => {
                            if(node.id === cir.source) {
                                count += 1
                            }
                        })
                        if(count <= 0) {
                            tempNodes.push(node)
                        }
                    })
                    this.circulationHistoryList.push(...tempNodes)
                    this.circulationHistoryList.forEach((cir, index) => {
                        if(cir.id == this.processStructureValue.workOrder.current_state) {
                            this.activeIndex = index
                            if(index + 1 == this.circulationHistoryList.length) {
                                this.activeIndex = this.circulationHistoryList.length
                            }
                        }
                    })
                } else {
                    this.activeIndex = this.circulationHistoryList.length
                }
                // 添加抄送状态
                this.circulationHistoryList.forEach((res) => {
                    res.ccStatus = true
                })


                // 如果回退到初始节点则可编辑。
                if (this.activeIndex === 0 && this.currentNode.clazz === 'start') {
                    this.currentNode.writeTpls = []
                    for (var tplTmp of this.processStructureValue.tpls) {
                        this.currentNode.writeTpls.push(tplTmp.form_structure.id)
                    }
                }

                // 判断是否需要主动处理
                for (var stateValue of this.processStructureValue.workOrder.state) {
                    if (this.processStructureValue.workOrder.current_state === stateValue.id && stateValue.processor.length > 1) {
                        this.isActiveProcessing = true
                        break
                    }
                }

                 let psv = res.data?.edges || []
                 let btn_group = []
                psv.forEach(item => {
                    // console.log(this.currentNode)
                    // 过滤其它类型的操作
                    if(this.is_end===0 && item.source===this.currentNode.id && item.flowProperties == 1) {
                        if(item.flowProperties == 1) {
                            item.className = 'info'
                            item.labelShow = '同意'
                        } else if(item.flowProperties == 0) {
                            item.className = 'danger'
                        } else if(item.flowProperties == 2) {
                            item.className = 'info'
                        }
                        btn_group.push(item)
                    } else {
                        item.className = 'info'
                    }
                })
                this.btn_group = btn_group
                // console.log(this.endNodeDetail, btn_group , 'btn_group')

                this.getAlertMessage()
            } catch {
                //
            }
        },
        relationFormChange(value) {
            let temp = value || []
            this.formData.list?.forEach(item => {
                item.hidden = false
                if(temp.includes(item.model)) {
                    item.hidden = true
                }
                // 子表单
                if(item.type == 'subform') {
                    let childList = item.columns || []
                    childList.forEach(child => {
                        if(child.list?.length > 0) {
                            child.list.forEach(c => {
                                c.hidden = false
                                if(temp.includes(c.originModel)) {
                                    c.hidden = true
                                }
                            })
                        }
                    });
                    // 重置数据
                    let subForm = this.$refs.subform
                    subForm.forEach(item => {
                        item.reSetFormData()
                    })
                }
            })
        },
        async getUserInfo() {
            // 获取用户信息
            try {
                let user = await getInfo()
                this.userInfo = user.data

                this.ownerApply = this.processStructureValue.workOrder.creator == this.userInfo.userId ? true : false
            } catch {
                //
            }
        },
        // 获取提示消息
        getAlertMessage() {
            if (this.is_end === 1) {
                this.alertMessage = '当前工单已结束'
            }
        },
        // 转交
        async exchange() {
            let workOrder = this.processStructureValue.workOrder
            this.popupForm.work_order_id = workOrder.id
            this.nodeList = workOrder.state || []
            this.nodeList.forEach(item => {
                item.text = item.label
            })
            if (this.nodeList.length === 1) {
                this.popupForm.node_id = this.nodeList[0].id
            }
            try {
                // 获取所有用户
                const res = await sysUserList({ pageSize: 9999 })
                const users = res.data.list || []
                users.forEach(item => {
                    this.columns.push({
                        avatar: item.avatar,
                        text: item.nickName,
                        phone: item.phone,
                        id: item.userId
                    })
                })
            } catch {
                //
            }
            this.transferStatus = true
        },
        // 催办
        handleUrge() {
            this.$dialog.confirm({
                title: '催办',
                allowHtml : true,
                message: '<span style="font-size:15px ">对此工单处理人进行催办通知提醒, 是否继续?</span><br><span style="color: #c33; font-size: 10px">注意：十分钟内只能催办一次。</span>',
                confirmButtonColor: '#01C1B5'
            }).then(async () => {
                try {
                    let workOrder = this.processStructureValue.workOrder
                    let workOrderId = workOrder.id
                    await urgeWorkOrder({ workOrderId })
                    this.$toast('已进行催办通知')
                } catch {
                    //
                }
            })
        },
        handleUnity() {
            // 关闭
            this.$dialog.confirm({
                title: '提示',
                allowHtml : true,
                message: '<span style="font-size:15px ">此操作将会关闭该工单, 是否继续?</span>',
                confirmButtonColor: '#01C1B5'
            }).then(async () => {
                try {
                    let workOrder = this.processStructureValue.workOrder
                    let work_oroder_id = workOrder.id
                    await unityWorkOrder({ work_oroder_id })
                    this.$toast('已关闭工单')
                    setTimeout(() => {
                        this.$router.push({
                            path: '/myApproval',
                            query: {
                                classify: 2
                            }
                        })
                    }, 500)
                } catch {
                    //
                }
            })
        },
        onCheckSubmit(item) {
            this.selectItem = item
            this.$refs.headForm.validate().then(() => {
                this.showMarks = true
                this.popupMarkTxt = item.label
            })
        },
        popupSubmit() {
            this.$refs.headForm.submit()
            this.showMarks = false
            this.popupMarkTxt = null
        },
        onCCChange(item) {
            item.ccStatus = !item.ccStatus
            this.$forceUpdate()
        },
        async onSubmitHead(values) {
            // remarks
            let { ...res } = values
            let promiseList = []
            this.tpls = []
            for (let tpl of this.processStructureValue.tpls) {
                this.tpls.push({
                    tplDataId: tpl.id,
                    tplId: tpl.form_structure.id
                })
                // 说明是当前用户需要填写的列表数据
                if((this.currentNode.writeTpls!==undefined &&
                    this.currentNode.writeTpls!==null &&
                    this.currentNode.writeTpls.indexOf(tpl.form_structure.id)>-1)) {
                    let fd = this.formatData(res)
                    promiseList.push(fd)
                } else {
                    // 已存在的表单数据
                    promiseList.push(tpl.form_data)
                }
            }

            for (let tplDataIndex in this.tpls) {
                this.tpls[tplDataIndex].tplValue = promiseList[tplDataIndex]
            }

            let params = {
                tasks: this.processStructureValue.process.task,
                source_state: this.processStructureValue.workOrder.current_state,
                target_state: this.selectItem.target,
                circulation: this.selectItem.label,
                flow_properties: this.selectItem.flowProperties === undefined ? 2 : parseInt(this.selectItem.flowProperties),
                work_order_id: parseInt(this.workOrderId),
                remarks: this.remarks,
                tpls: this.tpls
            }

            let fileList = []
            this.tpls && this.tpls.forEach(tpl => {
                for(let val in tpl.tplValue) {
                    if(val.indexOf('file') != -1) {
                        const file = tpl.tplValue[val] || []
                        file.forEach(item => {
                            fileList.push(item.url)
                        })
                    }
                }
            })
            try {
                // const fileUrl = ''
                // console.log(params)
                // return
                // 确认提交
                await handleWorkOrder(params)

                await asyncPlayLog({ workOrderId: parseInt(this.workOrderId), fileUrl: fileList.join(',')})
                this.submitDisabled = false
                // workOrderId
                this.getProcessNodeList()
            } catch {
                //
                this.submitDisabled = false
            }
        },
        formatData(json) {
            let tempJson = {}
            let subFormList = {}
            for(let v in json) {
                let nameList = v.split('.')
                // 只要大于1说明是子表单
                if(nameList.length > 1) {
                    nameList.push(v)
                    let delName = nameList.shift()
                    if(subFormList[delName]) {
                        subFormList[delName].push(nameList)
                    } else {
                        subFormList[delName] = []
                        subFormList[delName].push(nameList)
                    }
                } else {
                    tempJson[v] = json[v]
                }
            }

            for(let sub in subFormList) {
                let subList = subFormList[sub] || []
                let subDown = []
                subList.forEach(item => {
                    if(subDown[item[1]]) {
                        subDown[item[1]][item[0]] = json[item[2]]
                    } else {
                        subDown[item[1]] = {}
                        subDown[item[1]][item[0]] = json[item[2]]
                    }
                })
                tempJson[sub] = subDown
            }
            return tempJson
        },
        getHideTplData(tpl) {
            // 獲取隱藏模板數據
            let list = tpl.list
            let data = {}
            list.forEach(item => {
                if(item.type == 'subform') {
                    if(item.columns.length > 0) {
                        data[item.model] = []
                        let arr = []
                        item.columns?.forEach(col => {
                            if(col.list?.length > 0) {
                                arr.push(...col.list)
                            }
                        })
                        let tempSub = {}
                        arr.forEach(a => {
                            tempSub[a.model] = a.options.defaultValue
                        })
                        data[item.model].push(tempSub)
                    } else {
                        data[item.model] = ''
                    }
                } else {
                    data[item.model] = item.options.defaultValue
                }
            })
            return data
        }
    }
}
</script>
<style lang='less' scoped>
@import url("../../assets/commonLess/variable.less");
.approvalAction {
    margin-bottom: 85px;
    padding-bottom: env(safe-area-inset-bottom)
}

/deep/.van-goods-action {
    box-shadow: 0 4px 10px 0 #cecece;
    z-index: 99;
    justify-content: space-around;
    height: 70px;
    .van-goods-action-icon__icon {
        font-size: 20px;
        min-width: 55px;
    }
    .van-goods-action-button--last {
        margin-right: .12rem;
    }
    .van-button--danger {
        background: #fff;
        border: 1px solid #01C1B5;
        color: #01C1B5;
    }
}

.style {
    margin-bottom: .12rem;
    padding: 12px 16px;
    line-height: 1.3;
    font-size: 16px;
    &.info {
        display: flex;
        flex-direction: column;
    }
    /deep/.van-field__label {
        margin-bottom: 7px;
        width: auto;
        color: #111F2C;
    }
    /deep/.van-field__value {
        padding: .03rem 0;
    }
}

.headerInfo {
    margin-bottom: 0.1rem;
    padding: 0.18rem 0.12rem;
    overflow: inherit;
    /deep/.van-cell__title {
        flex-direction: column;
        align-items: flex-start;
    }
}
.titleSection {
    .titleContent {
        font-size: 0.18rem;
        color: #333333;
        padding-right: 0.08rem;
    }
}
.waitStatus {
    color: #F39001;
    font-size: .14rem;
    display: inline-block;
    padding-top: .06rem;
}

.imgStatus {
    bottom: -35%;
    width: 0.75rem;
    height: 0.75rem;
    position: absolute;
    z-index: 98;
    right: .2rem;
}

.markModel {
    width: 90%;
    border-radius: .08rem;
    padding: .2rem 0;
}
.popup-marks {
    // width: 95%;
    h2 {
        font-size: .16rem;
        text-align: center;
    }
    /deep/.van-cell {
        font-size: .14rem;
    }
    /deep/.van-button {
        width: 90%;
        margin-left: 5%;
        font-size: .16rem;
    }
}

.step_section {
    margin: 0px 0.12rem 0.12rem;
    border-radius: .1rem;
    overflow: hidden;
    .step_title {
        background: #fff;
        padding: .1rem 0.16rem;
        color: #333333;
        font-size: .18rem;
        font-weight: 500;
    }
    /deep/.van-steps--vertical {
        padding-left: .45rem;
        .van-step__circle-container, .van-step__line {
            left: -22px;
        }
    }
    .step {
        font-size: .13rem;
        .step-t {
            display: flex;
            align-content: center;
            justify-content: space-between;
            font-size: .16rem;
            color: #444;
        }
        .inactive-icon {
            width: .1rem;
            height: .1rem;
            background: #D8D8D8;
            display: inline-block;
            border-radius: 1rem;
        }
        .apply-state {
            line-height: 1.5;
            flex-basis: 73%;
        }
        .apply-time {
            font-size: .14rem;
            color: #999999;
            flex-basis: 27%;
        }
        .apply-status {
            padding: .05rem 0;
            color: #999;
        }
        .remarks {
            background: #f5f5f5;
            padding: .08rem;
            color: #323233;
        }
        .van-icon {
            font-size: .17rem;
        }
    }
    .ccUsers {
        display: flex;
        align-items: center;
        justify-content: space-between;
        color: #444;
        padding-top: .08rem;
    }
    .ccUserDetail {
        color: #444;
    }
}
</style>