<template>
    <el-container>
        <el-main class="nopadding">
            <el-form label-width="80px" :model="formData" style="padding: 20px;" :disabled="localMode === 'show'">
                <el-form-item label="需求部门" required>
                    <el-cascader
                        v-model="formData.dept_need"
                        :options="group"
                        :props="groupsProps"
                        :show-all-levels="false"
                        clearable
                        style="width: 220px"
                    ></el-cascader>
                </el-form-item>
                <el-form-item label="日期" required>
                    <el-date-picker
                        v-model="formData.join_date"
                        type="date"
                        placeholder="日期"
                        value-format="YYYY-MM-DD"
                        :readonly="localMode === 'show'"
                    ></el-date-picker>
                </el-form-item>
            </el-form>
                <sc-form-table
                    v-model="formData.person"
                    :addTemplate="addTemplate"
                    :hideAdd="hideAdd"
                    :hideDelete="hideDelete"
                    placeholder="暂无数据"
                    >
                    <el-table-column prop="name" min-width="150">
                        <template #header>
                            <span style="color: red">*</span>
                            <span>姓名</span>
                        </template>
                        <template #default="scope">
                            <el-input
                                v-model="scope.row.name"
                                placeholder="请输入姓名"
                            ></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column prop="gender" min-width="150">
                        <template #header>
                            <span style="color: red">*</span>
                            <span>性别</span>
                        </template>
                        <template #default="scope">
                            <el-select v-model="scope.row.gender" placeholder="请选择">
                                <el-option label="男" :value="1"></el-option>
                                <el-option label="女" :value="2"></el-option>
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column prop="IDcard" min-width="150">
                        <template #header>
                            <span style="color: red">*</span>
                            <span>身份证号</span>
                        </template>
                        <template #default="scope">
                            <el-input
                                v-model="scope.row.IDcard"
                                placeholder="请输入身份证号"
                            ></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column prop="phone" min-width="150">
                        <template #header>
                            <span style="color: red">*</span>
                            <span>手机号</span>
                        </template>
                        <template #default="scope">
                        <el-input
                            v-model="scope.row.phone"
                            placeholder="请输手机号"
                        ></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column prop="note" label="备注" min-width="150">
                        <template #default="scope">
                        <el-input
                            v-model="scope.row.note"
                            placeholder="请输入备注"
                        ></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column prop="post" min-width="150" v-if="['交接部门负责人','结束'].includes(formData.ticket_?.state_?.name)">
                        <template #header>
                            <span style="color: red">*</span>
                            <span>岗位</span>
                        </template>
                        <template #default="scope">
                            <xtSelect
                                :apiObj="apiObjPost"
                                v-model="scope.row.post"
                                v-model:label="scope.row.post_name"
                                style="width: 150px"
                                >
                                <el-table-column label="名称" prop="name"></el-table-column>
                            </xtSelect>
                        </template>
                    </el-table-column>
                </sc-form-table>    
            <el-footer>
                <el-button type="danger"
                v-if="localMode=='edit'"
                style="margin-right: 4px;"
                @click="handleDel"
                :loading="saveLoading"
                >删除</el-button>
                <ticketd_b 
                        v-if = "formData.ticket_ && localMode=='show'"
                        :t_id="formData.id" 
                        :ticket_="formData.ticket_"
                        :ticket_data="ticket_data"
                        @success="$emit('success', localMode)" 
                        ref="ticketd_b"
                    ></ticketd_b>
                     <el-button 
                        v-if="localMode!='show'"
                        type="primary"
                        style="margin-right: 4px;"
                        @click="handleSave"
                        :loading="saveLoading"
                        >提交审批</el-button>
            </el-footer>
        </el-main>
        <el-aside width="20%" v-if="formData.ticket_">
            <ticketd :ticket_="formData.ticket_" @success="$emit('success')"></ticketd>
        </el-aside>
    </el-container>
</template>

<script>
import ticketd_b from "@/views/wf/ticketd_b.vue";
import ticketd from '@/views/wf/ticketd.vue';
import { genTree } from "@/utils/verificate";

export default {
    name: 'EnpJoinForm',
    components: {
        ticketd_b,
        ticketd
    },
    props: {
        mode: {
            type: String,
            default: 'show'
        },
        t_id: {
            type: String,
            default: ""
        }
    },
    data() {
        return {
            formData: {
                person: [],
            },
            ticket_data: {},
            localMode: this.mode,
            saveLoading: false,
            group:[],
            post:[],
            apiObjPost: this.$API.system.post.list,
            hideAdd:false,
            hideDelete:false,
            addTemplate: {
                name: "",
                gender: "",
                age: "",
                phone: "",
                note: "",
                },
            groupsProps: {
                multiple: false,
                emitPath: false,
                checkStrictly: true,
                },
            }
        },
    watch: {
        formData: {
            handler(val){
                Object.assign(this.ticket_data,{
                    person: val.person,
                })
            },
        deep: true,
        }
  },
    mounted() {
        this.getGroup();
        if (this.t_id) {
            this.getTid();
        } else {
            this.localMode = "add";
        }
    },
    methods: {
        async getTid() {
            try {
                let res = await this.$API.hrm.empjoin.item.req(this.t_id);
                // 获取岗位列表，填充 post_name
                if (res.person && res.person.length > 0) {
                    const postRes = await this.$API.system.post.list.req({ page: 0 });
                    const postList = Array.isArray(postRes) ? postRes : (postRes.results || postRes.data || []);
                    const postMap = {};
                    postList.forEach(p => { postMap[p.id] = p.name; });
                    res.person.forEach(p => {
                        if (p.post && !p.post_name) {
                            p.post_name = postMap[p.post] || '';
                        }
                    });
                }
                this.formData = res;
                if (res.ticket_ && res.ticket_.state_.type == 1 && res.create_by == this.$TOOL.data.get("USER_INFO").id) {
                    this.localMode = "edit";
                }
            } catch (error) {
                console.error('获取数据失败:', error);
            }
        },
        async getGroup() {
            let res = await this.$API.system.dept.list.req({ page: 0 });
            this.group = genTree(res);
        },
        handleDel() {
            this.$confirm(`确定删除吗？`, "提示", {
				type: "warning",
			})
				.then(()=>{
                    this.$API.hrm.empjoin.delete.req(this.formData.id).then(res=>{
                        this.$message.success("删除成功");
                        this.$emit('success');
                    })
                })
        },
        async handleSave() {
            if (this.localMode == "add") {
                try {
                    console.log('formData', this.formData);
                    let res = await this.$API.hrm.empjoin.create.req(this.formData);
                    this.$message.success("提交成功");
                    this.$emit('success', this.localMode);
                } catch (error) {
                    console.error('提交申请失败:', error);
                    throw error;
                }
            } else if (this.localMode == "edit") {
                this.$message.error("不支持编辑");
            }
        },
        handleQuery() {
			this.$refs.table.queryData(this.query);
		},
        

    }
}
</script>