<template>
    <div :class="[btn_group && btn_group.length > 0 ? 'approvalApply' : null]">
        <!-- <m-header :name="name" :isNative="false" /> -->

        <van-form ref="headForm" validate-first @submit="onSubmitHead" @failed="onFailed" validate-trigger="onSubmit" :scroll-to-error="false" :show-error="false">
            <van-field
                clearable
                name='deptName'
                v-show="deptList.length > 1"
                class="style"
                required
                v-model="deptName"
                placeholder="请选择申请部门"
                readonly
                @click="showSelect = true"
                :rules="[{ required: true, message: '请选择申请部门' }]"
            >
                <template #label>申请部门
                    <span style="color: red" v-if="!socialId">
                        (未设置社保部门)
                    </span>
                    <template v-else>
                        <span style="color: red" v-if="socialId != ruleForm.deptId">
                            (该部门非社保部门)
                        </span>
                    </template>
                </template>
                <template #right-icon>
                    <i class="van-icon van-icon-arrow van-cell__right-icon"></i>
                </template>
            </van-field>
            <van-field
                :label="'优先级'"
                clearable
                name='priority'
                class="style"
                required
                :rules="[{ required: true, message: '请选择工单优先级' }]"
            >
                <template #input>
                    <van-radio-group v-model="ruleForm.priority" direction="horizontal">
                        <van-radio :name="1">一般</van-radio>
                        <van-radio :name="2">紧急</van-radio>
                        <van-radio :name="3">非常紧急</van-radio>
                    </van-radio-group>
                </template>
            </van-field>
            <template v-for="(tplItem, tplIndex) in processStructureValue.tpls">
                <form-modal
                    :key="tplIndex"
                    v-if="currentNode.hideTpls === undefined || currentNode.hideTpls === null || currentNode.hideTpls.indexOf(tplItem.id) === -1"
                    :ref="'generateForm-'+tplItem.id"
                    :formData="tplItem.form_structure"
                    :disabled="currentNode.readonlyTpls===undefined || currentNode.readonlyTpls===null || currentNode.readonlyTpls.indexOf(tplItem.id)===-1?null:true" />
            </template>
        </van-form>
        <!-- 是自己审批 或者 是自己提交的记录 -->
        <van-goods-action v-if="btn_group && btn_group.length > 0" style="padding: 0 4%;">
            <van-goods-action-button
                v-for="(item, index) in btn_group"
                :key="index"
                :type="item.className"
                :disabled="submitDisabled"
                text="提交"
                plain
                @click="onCheckSubmit(item)"
            />
        </van-goods-action>

        <van-popup v-model="showSelect" position="bottom">
            <van-picker
                show-toolbar
                :columns="deptList"
                @confirm="onConfirm"
                visible-item-count="4"
                @cancel="showSelect = false"
            />
        </van-popup>
    </div>
</template>
<script>
import MHeader from '@/components/MHeader'
import { processStructure, createWorkOrder, checkCourseReturnFee } from './api'
import FormModal from './modal/formModal'
// import { launchInfo, approvalCancel } from '@/api/message'
export default {
    name: 'approvalApply',
    components: { MHeader, FormModal },
    data() {
        const query = this.$route.query
        return {
            active: 0,
            processId: query.processId,
            name: query.name,
            submitDisabled: false,
            showSelect: false,
            deptName: null, // 部门名称
            socialId: null, // 是否是社保分部
            ruleForm: {
                deptId: null, // 部门编号
                priority: 1,
                process: '',
                classify: '',
                state: [],
                source: '',
                source_state: '',
                process_method: '',
                tpls: {
                    'form_structure': [],
                    'form_data': []
                },
                tasks: []
            },
            currentNode: {},
            processStructureValue: {},
            tempProcessStructureValue: {},
            selectTarget: null,
            btn_group: [],
            deptList: [], // 部门列表
        }
    },
    async mounted() {
        document.title = this.name
        this.getProcessNodeList()
    },
    methods: {
        async getProcessNodeList() {
            try {
                const userId = sessionStorage.getItem('userId')
                let params = {
                    processId: this.processId
                }
                if(userId) {
                    params.userId = userId
                }
                const res = await processStructure(params)
                this.processStructureValue = res.data || {}
                this.tempProcessStructureValue = JSON.parse(JSON.stringify(res.data || {}))
                this.processStructureValue.nodes.forEach((node, index) => {
                    if(node.clazz == 'start') {
                        this.active = index
                        this.currentNode = node
                    }
                })

                this.deptList = res.data.depts || []
                const defaultDept = res.data.deptId
                this.socialId = defaultDept
                this.deptList.forEach((item, index) => {
                    if(defaultDept) {
                        if(item.deptId == defaultDept) {
                            this.deptName = item.deptName
                            this.ruleForm.deptId = item.deptId
                        }
                    } else {
                        if(index == 0) {
                            this.deptName = item.deptName
                            this.ruleForm.deptId = item.deptId
                        }
                    }
                    item.text = item.deptName
                })
                let psv = res.data?.edges || []
                let btn_group = []
                psv.forEach(item => {
                    if(item.source===this.currentNode.id && item.flowProperties == 1) {
                        if(item.flowProperties == 1) {
                            item.className = 'info'
                        } 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

                if(!this.socialId && this.deptList.length <= 0) {
                    this.$dialog.alert({
                        message: '您当前暂未设置所属部门，请联系管理员',
                        confirmButtonColor: '#01C1B5'
                    })
                }
            } catch {
                //
            }
        },
        onConfirm(value) {
            this.deptName = value.deptName
            this.ruleForm.deptId = value.deptId
            this.showSelect = false
        },
        onCheckSubmit(item) {
            if(!this.socialId && this.deptList.length <= 0 || !this.deptName) {
                this.$dialog.alert({
                    message: '您当前暂未设置所属部门，请联系管理员',
                    confirmButtonColor: '#01C1B5'
                })
                return
            }
            this.selectTarget = item.target
            this.$refs.headForm.submit()
        },
        onFailed() {
            // console.log(errorInfo)
        },
        async onSubmitHead(values) {
            // eslint-disable-next-line no-unused-vars
            let { priority, deptName, ...res } = values
            const psv = this.tempProcessStructureValue
            this.submitDisabled = true
            let ruleForm = this.ruleForm
            ruleForm.priority = priority
            let stateMap = {}
            ruleForm.process = parseInt(this.processId)
            ruleForm.classify = psv.process.classify
            stateMap['id'] = this.selectTarget
            ruleForm.source_state = psv.nodes[this.active].label
            for (let v of psv.nodes) {
                if (v.id === this.selectTarget) {
                    if (v.assignType !== undefined) {
                        stateMap['process_method'] = v.assignType
                    }
                    if (v.assignValue !== undefined) {
                        stateMap['processor'] = Array.from(new Set(v.assignValue))
                    }
                    stateMap['label'] = v.label
                    break
                }
            }
            ruleForm.state = [stateMap]

            ruleForm.tpls = {
                'form_structure': [],
                'form_data': []
            }
            // 绑定流程任务
            ruleForm.tasks = psv.process.task === undefined ? [] : psv.process.task
            // 追加节点任务
            if (psv.nodes[this.active].task !== undefined && psv.nodes[this.active].task.length > 0) {
                for (var task of psv.nodes[this.active].task) {
                    if (ruleForm.tasks.indexOf(task) === -1) {
                        ruleForm.tasks.push(task)
                    }
                }
            }
            // 不能一個流程用多个模板
            for (let tpl of psv.tpls) {
                tpl.form_structure.id = tpl.id
                ruleForm.tpls.form_structure.push(tpl.form_structure)
                if(this.currentNode.hideTpls === undefined || this.currentNode.hideTpls === null || this.currentNode.hideTpls.indexOf(tpl.id) === -1) {
                    let fd = this.formatData(res)
                    ruleForm.tpls.form_data.push(fd)
                } else {
                    let hideFd = this.getHideTplData(tpl.form_structure)
                    ruleForm.tpls.form_data.push(hideFd)
                }
            }
            ruleForm.source = psv.nodes[this.active].id
            try {
                // console.log(ruleForm)
                const tplInfo = this.processStructureValue.tpls[0] // 默认只用第一个模板
                const formData = ruleForm?.tpls?.form_data[0]
                await checkCourseReturnFee({ tplInfoId: tplInfo.id, formData }) // 做校验
                await createWorkOrder(ruleForm)
                this.submitDisabled = false
                this.$toast('申请成功')
                setTimeout(() => {
                    this.$router.push({
                        path: '/myApproval',
                        query: {
                            classify: 2
                        }
                    })
                }, 500)
            } 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");
.approvalApply {
    margin-bottom: 85px;
}

/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;
    display: flex;
    flex-direction: column;
    font-size: 16px;
    /deep/.van-field__label {
        margin-bottom: 7px;
        width: auto;
        color: #111F2C;
        font-size: 14px;
    }
    /deep/.van-field__value {
        padding: .03rem 0;
    }
}
</style>