<template>
    <el-container>
        <el-main class="nopadding">
            <el-form label-width="120px" :model="formData" :disabled="localMode === 'show'">
                <div class="wf-form-section">
                    <span class="title">合同变更</span>
                </div>
                <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>
                <!-- 新增模式：多选员工 -->
                <template v-if="localMode === 'add'">
                    <el-form-item label="选择员工" required>
                        <xtSelect
                            v-model="selectedIds"
                            :apiObj="$API.hrm.employee.list"
                            :multiple="true"
                            @change="handleEmpChange"
                            style="width: 400px"
                            :tableWidth="650"
                        >
                            <el-table-column prop="name" label="姓名" width="80"></el-table-column>
                            <el-table-column prop="belong_dept_name" label="部门" width="120"></el-table-column>
                            <el-table-column prop="post_name" label="岗位" width="100"></el-table-column>
                            <el-table-column prop="start_date" label="入职日期" width="110"></el-table-column>
                            <el-table-column prop="contract_end_date" label="合同结束日期" width="120"></el-table-column>
                        </xtSelect>
                    </el-form-item>
                    <el-form-item v-if="selectedEmps.length > 0">
                        <el-table :data="selectedEmps" border size="small" style="width: 100%;" max-height="250">
                            <el-table-column type="index" label="#" width="40"></el-table-column>
                            <el-table-column prop="name" label="姓名" width="80"></el-table-column>
                            <el-table-column prop="gender" label="性别" width="50"></el-table-column>
                            <el-table-column prop="belong_dept_name" label="部门" width="120"></el-table-column>
                            <el-table-column prop="post_name" label="岗位" width="100"></el-table-column>
                            <el-table-column prop="start_date" label="入职日期" width="110"></el-table-column>
                            <el-table-column prop="contract_end_date" label="合同结束日期" width="120"></el-table-column>
                            <el-table-column label="操作" width="60">
                                <template #default="scope">
                                    <el-button type="danger" text size="small" @click="removeEmp(scope.$index)">移除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                        <div style="margin-top: 4px; color: #909399; font-size: 12px;">共选择 {{ selectedEmps.length }} 人</div>
                    </el-form-item>
                </template>
                <!-- 查看模式：显示变更人员列表 -->
                <template v-else>
                    <el-form-item label="变更人员">
                        <el-tag type="warning" effect="plain" style="margin-right: 8px;" v-if="batchEmployees.length > 0">共 {{ batchEmployees.length }} 人</el-tag>
                        <el-table :data="batchEmployees" border size="small" style="width: 100%; margin-top: 4px;" max-height="300">
                            <el-table-column type="index" label="#" width="40"></el-table-column>
                            <el-table-column prop="employee_name" label="姓名" width="80"></el-table-column>
                            <el-table-column prop="dept_name" label="部门" width="120"></el-table-column>
                            <el-table-column prop="post_name" label="岗位" width="100"></el-table-column>
                            <el-table-column prop="join_date" label="入职日期" width="110"></el-table-column>
                            <el-table-column prop="end_contract" label="合同结束日期" width="120"></el-table-column>
                        </el-table>
                    </el-form-item>
                </template>
                <el-divider>变更信息</el-divider>
                <el-form-item label="合同变更次数">
                    <el-input-number
                        v-model="formData.counts"
                        :min="0"
                        controls-position="right"
                        style="width: 160px"
                    ></el-input-number>
                </el-form-item>
                <el-form-item label="应续签">
                    <el-date-picker
                        v-model="formData.plan_renewal"
                        type="date"
                        placeholder="选择日期"
                        value-format="YYYY-MM-DD"
                        style="width: 230px"
                    ></el-date-picker>
                </el-form-item>
                <el-form-item label="正常续签">
                    <el-date-picker
                        v-model="formData.normal_renewal"
                        type="date"
                        placeholder="选择日期"
                        value-format="YYYY-MM-DD"
                        style="width: 230px"
                    ></el-date-picker>
                </el-form-item>
                <el-form-item label="续签/变更(年)">
                    <el-input-number
                        v-model="formData.change_date"
                        controls-position="right"
                        style="width: 160px"
                    ></el-input-number>
                </el-form-item>
                <el-form-item label="变更原因">
                    <el-input
                        v-model="formData.change_reason"
                        type="textarea"
                        rows="2"
                        placeholder="缩短续签/变更年限原因"
                        style="width: 400px"
                    ></el-input>
                </el-form-item>
            </el-form>
            <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=='add'"
                    type="primary"
                    style="margin-right: 4px;"
                    @click="handleSave"
                    :loading="saveLoading"
                    :disabled="selectedEmps.length === 0"
                >提交审批 ({{ selectedEmps.length }} 人)</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: 'EmpContractForm',
    components: {
        ticketd_b,
        ticketd
    },
    props: {
        mode: {
            type: String,
            default: 'show'
        },
        t_id: {
            type: String,
            default: ""
        }
    },
    data() {
        return {
            formData: {
                dept_need: "",
                counts: 0,
                plan_renewal: "",
                normal_renewal: "",
                change_date: null,
                change_reason: "",
            },
            selectedIds: [],
            selectedEmps: [],
            batchEmployees: [],
            ticket_data: {},
            localMode: this.mode,
            saveLoading: false,
            group: [],
            groupsProps: {
                multiple: false,
                emitPath: false,
                checkStrictly: true,
            },
        }
    },
    watch: {
        formData: {
            handler(val) {
                Object.assign(this.ticket_data, val);
            },
            deep: true,
            immediate: true
        }
    },
    mounted() {
        this.getGroup();
        if (this.t_id) {
            this.getTid();
        } else {
            this.localMode = "add";
        }
    },
    methods: {
        async getTid() {
            try {
                let res = await this.$API.hrm.empcontract.item.req(this.t_id);
                this.formData = res;
                // 加载同批次的员工列表
                if (res.batch_employees && res.batch_employees.length > 0) {
                    this.batchEmployees = res.batch_employees;
                } else {
                    // 单条记录兼容
                    this.batchEmployees = [{
                        employee_name: res.employee_name,
                        post_name: res.post_name,
                        dept_name: res.dept_name,
                        join_date: res.join_date,
                        end_contract: res.end_contract,
                    }];
                }
                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);
        },
        handleEmpChange(rows) {
            this.selectedEmps = rows || [];
        },
        removeEmp(index) {
            this.selectedEmps.splice(index, 1);
            this.selectedIds = this.selectedEmps.map(e => e.id);
        },
        handleDel() {
            this.$confirm(`确定删除吗？`, "提示", {
                type: "warning",
            }).then(() => {
                this.$API.hrm.empcontract.delete.req(this.formData.id).then(res => {
                    this.$message.success("删除成功");
                    this.$emit('success');
                })
            })
        },
        async handleSave() {
            if (!this.formData.dept_need) {
                this.$message.warning("请选择申请部门");
                return;
            }
            if (this.selectedEmps.length === 0) {
                this.$message.warning("请选择员工");
                return;
            }
            this.saveLoading = true;
            try {
                const batchData = this.selectedEmps.map(emp => ({
                    employee: emp.id,
                    dept_need: this.formData.dept_need,
                    counts: this.formData.counts,
                    plan_renewal: this.formData.plan_renewal,
                    normal_renewal: this.formData.normal_renewal,
                    change_date: this.formData.change_date,
                    change_reason: this.formData.change_reason,
                }));
                await this.$API.hrm.empcontract.create.req(batchData);
                this.$message.success(`提交成功，共 ${this.selectedEmps.length} 人`);
                this.$emit('success', 'add');
            } catch (error) {
                console.error('提交失败:', error);
            } finally {
                this.saveLoading = false;
            }
        },
    }
}
</script>
