<template>
    <div class="w-[100%] space-y-6" style="height: 80vh; overflow-y: auto;">
        <div class="bg-white rounded-lg p-6 shadow-sm">
            <h2 class="text-xl font-medium mb-6">工单信息</h2>
            <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="来电姓名" required prop="name">
                            <el-input v-model="form.name" placeholder="请输入来电姓名" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="联系电话" required prop="phone">
                            <el-input v-model="form.phone" placeholder="请输入联系电话" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="年龄">
                            <el-input v-model="form.age" type="number" placeholder="请输入年龄"
                                @input="updateAgeGroup" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="年龄分段">
                            <!-- <el-input v-model="form.ageGroup" /> -->
                            <el-select v-model="form.ageGroup" placeholder="请选择年龄分段" class="w-full">
                                <el-option v-for="item in ageGroupOptions" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>

                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    
                    <el-col :span="12">
                        <el-form-item label="性别">
                            <el-select v-model="form.sex" placeholder="请选择性别" class="w-full" clearable>
                                <el-option key="0" value="0" label="未知"/>
                                <el-option key="1" value="1" label="男"/>
                                <el-option key="2" value="2" label="女"/>
                            </el-select>
                        </el-form-item>

                    </el-col>
                </el-row>
                <el-form-item label="所在地区">
                    <el-cascader v-model="form.area" :options="areaTree" :props="{ value: 'id', checkStrictly: true,}"
                        placeholder="请选择所在地区" filterable clearable class="w-full" />
                </el-form-item>
                <el-form-item label="详细地址">
                    <el-input v-model="form.address" type="textarea" :rows="2" placeholder="请输入详细地址（如街道、门牌号等）"
                        class="w-full" />
                </el-form-item>

                <el-form-item label="工单类型" required prop="type">
                    <el-cascader ref="typeCascaderRef" class="w-full" v-model="form.type"
                        :props="{ value: 'id', }" placeholder="请选择工单类型" :options="ticketTypes" filterable
                        clearable @change="handleTypeChange" />
                </el-form-item>
                <el-form-item v-if="form.typeCode === 'complain'" label="投诉部门" required prop="department">
                    <!-- <el-select v-model="form.department" placeholder="请选择投诉部门" class="w-full">
                        <el-option v-for="item in departments" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select> -->
                    <el-cascader ref="deptCascaderRef" class="w-full" v-model="form.department"
                        :props="{ checkStrictly: true }" placeholder="请选择投诉科室" :options="departments" filterable
                        @change="deptChange" />
                </el-form-item>
                <el-form-item label="问题描述" required prop="description">
                    <el-input v-model="form.description" type="textarea" :rows="4" placeholder="请详细描述问题" />
                </el-form-item>
                <el-form-item label="干预建议" prop="suggest">
                    <el-input v-model="form.suggest" type="textarea" :rows="4" placeholder="请输入干预建议（最多2000字）"
                        maxlength="2000" show-word-limit />
                </el-form-item>
                <el-form-item label="处理措施" prop="handlingMeasures">
                    <el-select v-model="form.handlingMeasures" multiple filterable placeholder="请选择处理措施"
                        class="w-full">
                        <el-option v-for="item in order_handling_measures" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-row>
                    <el-col :span="12" v-if="form.handlingMeasures.indexOf('weijiganyu')!== -1">
                        <el-form-item label="干预项">
                            <el-select v-model="form.crisisInterfere" placeholder="请选择干预项" clearable>
                                <el-option v-for="item in order_weijiganyu" :key="item.value"
                                    :label="item.label" :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="12" v-if="form.crisisInterfere === 'jiuyuan'">
                        <el-form-item label="联动时间">
                            <el-date-picker style="width: 100%;" v-model="form.hmLinkageTime" type="datetime"
                                placeholder="请选择联动时间" format="YYYY-MM-DD hh:mm:ss"
                                value-format="YYYY-MM-DD hh:mm:ss" />
                            <!-- <el-input v-model="form.hmLinkageTime" placeholder="请输入联动时间" /> -->
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" v-if="form.crisisInterfere === 'jiuyuan'">
                        <el-form-item label="联动单位">
                            <el-input v-model="form.hmLinkageDept" placeholder="请输入联动单位" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" v-if="form.crisisInterfere === 'jiuyuan'">
                        <el-form-item label="联动电话">
                            <el-input v-model="form.hmLinkageTel" placeholder="请输入联动电话" />
                        </el-form-item>
                    </el-col>

                    <el-col :span="12" v-if="form.crisisInterfere === 'lianxi'">
                        <el-form-item label="联系他人">
                            <el-select v-model="form.agreeLink" placeholder="请选择是否同意联系" clearable>
                                <el-option label="未知" value="未知" />
                                <el-option label="同意" value="同意" />
                                <el-option label="拒绝" value="拒绝" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" v-if="form.agreeLink === '同意'">
                        <el-form-item label="联系电话">
                            <el-input v-model="form.aboutLinkTel" placeholder="请输入联系电话" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12" v-if="form.agreeLink === '同意'">
                        <el-form-item label="与来电者关系">
                            <el-select v-model="form.relation" placeholder="请选择与来电者关系" clearable>
                                <el-option label="家属" value="家属" />
                                <el-option label="朋友" value="朋友" />
                                <el-option label="其他" value="其他" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="是否需要回访">
                    <el-switch v-model="form.isNeedVisit" @change="handleNeedVisitChange" />
                </el-form-item>
                <el-form-item label="标记">
                    <el-cascader ref="labelCascaderRef" class="w-full" v-model="form.tag"  
                    :props="{ label: 'dictLabel', value: 'dictValue', multiple: true }" 
                    placeholder="请标记科室" :options="labels" filterable />
                </el-form-item>
                <!-- <el-form-item label="优先级">
                    <el-radio-group v-model="form.priority">
                        <el-radio-button label="high">高</el-radio-button>
                        <el-radio-button label="medium">中</el-radio-button>
                        <el-radio-button label="low">低</el-radio-button>
                    </el-radio-group>
                </el-form-item> -->
                <el-form-item label="处理方式" required prop="handleMethod">
                    <el-select v-model="form.handleMethod" placeholder="请选择处理方式" :disabled="form.handleMethod === '2'" class="w-full" @change="handleMethodChange">
                        <el-option v-for="item in handleMethods" :key="item.value" :label="item.label" 
                            :value="item.value" />
                    </el-select>
                </el-form-item>
                
            </el-form>
        </div>
        <div class="bg-white rounded-lg p-6 shadow-sm">
            <h2 class="text-xl font-medium mb-6">个人信息</h2>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="来电类型" label-width="120px">
                        <el-select v-model="form.callType" placeholder="请选择性别" class="w-full" clearable>
                            <el-option key="1" value="1" label="本人咨询" />
                            <el-option key="2" value="2" label="替他人咨询" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="教育状况" label-width="120px">
                        <el-select v-model="form.grade" placeholder="请选择教育状况" class="w-full" clearable>
                            <el-option v-for="item in order_grade" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="婚姻状况" label-width="120px">
                        <el-select v-model="form.maritalStatus" placeholder="请选择婚姻状况" class="w-full"
                            clearable>
                            <el-option v-for="item in order_marital_status" :key="item.value"
                                :label="item.label" :value="item.value" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="居住状态" label-width="120px">
                        <el-select v-model="form.livingStatus" placeholder="请选择居住状态" class="w-full"
                            clearable>
                            <el-option v-for="item in order_living_status" :key="item.value"
                                :label="item.label" :value="item.value" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="从业状况" label-width="120px">
                        <el-select v-model="form.career" placeholder="请选择从业状况" class="w-full" clearable>
                            <el-option v-for="item in order_career" :key="item.value" :label="item.label"
                                :value="item.value" />

                        </el-select>
                    </el-form-item>
                </el-col>

            </el-row>
        </div>
        <div class="bg-white rounded-lg p-6 shadow-sm">
            <h2 class="text-xl font-medium mb-6">业务信息</h2>
            <el-row>
                <el-col :span="24">
                    <el-form-item label="主导情绪" label-width="120px">
                        <el-select v-model="form.emotion" placeholder="请选择主导情绪" style="width: 42%;"
                            clearable>
                            <el-option v-for="item in order_emotion" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                        <el-input v-if="form.emotion === 'zdqxqita'" v-model="form.emotionOther"
                            placeholder="请输入其他情绪" style="width: 45%; margin-left: 5%;" />
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="主导情绪方式" label-width="120px">
                        <el-select v-model="form.replyMethod" placeholder="请选择主导情绪" style="width: 42%;"
                            clearable>
                            <el-option v-for="item in order_coping_style" :key="item.value"
                                :label="item.label" :value="item.value" />
                        </el-select>
                        <el-input v-if="form.replyMethod === 'ydfsqita'" v-model="form.replyMethodOther"
                            placeholder="请输入主导情绪应对方式" style="width: 45%; margin-left: 5%;" />
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="近期心境" label-width="120px">
                        <el-select v-model="form.recentMood" placeholder="请选择近期心境" style="width: 42%;"
                            clearable @change="handleRecentEmotion">
                            <el-option v-for="item in order_emotion" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                        <el-input v-if="form.recentMood === 'zdqxqita'" v-model="form.recentMoodOther"
                            placeholder="请输入近期心境" style="width: 45%; margin-left: 5%;" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <!-- 近期心境持续时间：______（天、月、年） -->

                    <el-form-item label="持续时间" label-width="120px">
                        <div class="flex items-center" style="width: 100%;">
                            <el-input-number v-model="form.recentMoodDuration" :min="1" :max="999" class="w-24" >
                                <template #suffix>
                                    <span>天</span>
                                </template>
                            </el-input-number>
                            <!-- <el-select v-model="form.durationUnit" style="width: 100px" class="ml-2 w-20">
                                <el-option label="天" value="天" />
                                <el-option label="月" value="月" />
                                <el-option label="年" value="年" />
                            </el-select> -->
                        </div>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="近期心境方式" label-width="120px">
                        <el-select v-model="form.copingStyle" placeholder="请选择主要应对方式" style="width: 42%;"
                            clearable @change="handleRecentEmotionWay">
                            <el-option v-for="item in order_coping_style" :key="item.value"
                                :label="item.label" :value="item.value" />

                        </el-select>
                        <el-input v-if="recentEmotionWayQiTa" v-model="form.copingStyleOther"
                            placeholder="请输入近期心境应对方式" style="width: 45%; margin-left: 5%;" />
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="社会支持情况" label-width="120px">
                        <el-input v-model="form.socialSupport" type="textarea" placeholder="请输入社会支持情况" />
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="易感因素" label-width="120px">
                        <el-select v-model="form.riskFactor" placeholder="请选择易感因素" style="width: 42%;"
                            clearable @change="handleSusceptibleFactors">
                            <el-option v-for="item in order_risk_factor" :key="item.value"
                                :label="item.label" :value="item.value" />
                        </el-select>
                        <el-input v-if="susceptibleFactorsQiTa" v-model="form.riskFactorOther"
                            placeholder="请输入其他易感因素" style="width: 45%; margin-left: 5%;" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="求助情况" label-width="120px">
                        <el-select v-model="form.pastHelp" placeholder="请选择求助情况" class="w-full" clearable>
                            <el-option v-for="item in order_past_help" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="治疗情况" label-width="120px">
                        <el-select v-model="form.treatNow" placeholder="请选择治疗情况" class="w-full" clearable>
                            <el-option v-for="item in order_treat_now" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12" v-if="form.treatNow === 'outpatient'">
                    <el-form-item label="门诊治疗" label-width="120px">
                        <el-select v-model="form.outpatient" placeholder="请选择治疗情况" class="w-full" clearable>
                            <el-option v-for="item in order_outpatient" :key="item.value"
                                :label="item.label" :value="item.value" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12" v-if="form.outpatient === 'yaowu'">
                    <el-form-item label="服用情况" label-width="120px">
                        <el-select v-model="form.medicationStatus" placeholder="请选择服用情况" class="w-full"
                            clearable>
                            <el-option v-for="item in order_medication_status" :key="item.value"
                                :label="item.label" :value="item.value" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="是否青少年" label-width="120px">
                        <el-select v-model="form.teenagerFlag" placeholder="请选择是否与青少年相关" class="w-full"
                            clearable>
                            <el-option label="不详" value="不详" />
                            <el-option label="是" value="是" />
                            <el-option label="否" value="否" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="自杀风险评估" label-width="120px">
                        <el-select v-model="form.suicideRisk" placeholder="请选择自杀风险评估" class="w-full"
                            clearable>
                            <el-option v-for="item in order_suicide_risk" :key="item.value"
                                :label="item.label" :value="item.value" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="是否出现自杀" label-width="120px">
                        <el-select v-model="form.suicide_occurrence" placeholder="请选择是否出现自杀"
                            style="width: 42%;" clearable>
                            <el-option label="是" value="是" />
                            <el-option label="否" value="否" />
                        </el-select>
                        <el-input-number style="width:150px; margin-left: 5%;"
                            v-if="form.suicide_occurrence === '是'" v-model="form.suicideCount" :min="1"
                            :max="100">
                            <template #suffix>
                                <span>次</span>
                            </template>
                        </el-input-number>

                        <!-- <el-input type="number" v-model="form.suicideCount" placeholder="请输入自杀次数" />  -->
                    </el-form-item>
                </el-col>

                <el-col :span="24">
                    <el-form-item label="是否出现自伤" label-width="120px">
                        <el-select v-model="form.selfInjury" placeholder="请选择是否出现自伤" style="width: 42%;"
                            clearable>
                            <el-option v-for="item in order_self_injury" :key="item.value"
                                :label="item.label" :value="item.value" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="形式" label-width="120px"
                        v-if="form.selfInjury && form.selfInjury !== 'fou'">
                        <el-input v-model="form.selfInjuryOther" placeholder="请输入形式" />
                    </el-form-item>
                </el-col>

                <el-col :span="12">
                    <el-form-item label="危害他人风险" label-width="120px">
                        <el-select v-model="form.harmOthers" placeholder="请选择危害他人风险评估" clearable>
                            <el-option v-for="item in order_harm_others" :key="item.value"
                                :label="item.label" :value="item.value" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="是否出现过" label-width="120px">
                        <el-select v-model="form.existHarmOthers" placeholder="请选择是否出现危害他人" clearable>
                            <el-option label="是" value="是" />
                            <el-option label="否" value="否" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="危害公共安全" label-width="120px">
                        <el-select v-model="form.endangerPublicSafe" placeholder="请选择危害公共安全风险评估" clearable>
                            <el-option v-for="item in order_harm_others" :key="item.value"
                                :label="item.label" :value="item.value" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="是否出现过" label-width="120px">
                        <el-select v-model="form.existEndangerPublicSafe" placeholder="请选择是否出现危害公共安全"
                            clearable>
                            <el-option label="是" value="是" />
                            <el-option label="否" value="否" />
                        </el-select>
                    </el-form-item>
                </el-col>

            </el-row>
        </div>
        <div class="bg-white rounded-lg p-6 shadow-sm" style="margin-bottom: 30px;">
            <h2 class="text-xl font-medium mb-6">来电处理</h2>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="主要问题" label-width="120px">
                        <el-cascader ref="typeCascaderRef" class="w-full" v-model="form.mainProblem"
                            :props="{ value: 'id', }" placeholder="请选择工单类型" :options="ticketTypes"
                            filterable clearable @change="handleTypeChange" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="随访预约" label-width="120px">
                        <el-select v-model="form.appointment" placeholder="请选择是否预约随访" clearable>

                            <el-option v-for="item in order_suifangyuyue" :key="item.value"
                                :label="item.label" :value="item.value" />

                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12" v-if="form.appointment === 'yuyue'">
                    <el-form-item label="随访联系人" label-width="120px" v-if="form.appointment === 'yuyue'">
                        <el-select v-model="form.sfLinkman" placeholder="请选择随访联系人" clearable>
                            <el-option label="本人" value="本人" />
                            <el-option label="他人" value="他人" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12" v-if="form.sfLinkman === '他人'">
                    <el-form-item label="联系电话" label-width="120px">
                        <el-input v-model="form.sfLinkmanTel" placeholder="请输入联系电话" />
                    </el-form-item>
                </el-col>
                <el-col :span="12" v-if="form.sfLinkman === '他人'">
                    <el-form-item label="预约时间" label-width="120px">
                        <el-date-picker style="width: 100%;" v-model="form.sfPlanTime" type="datetime"
                            placeholder="请选择预约时间" format="YYYY-MM-DD hh:mm:ss"
                            value-format="YYYY-MM-DD hh:mm:ss" />
                    </el-form-item>
                </el-col>
                
                <el-col :span="12">
                    <el-form-item label="自杀风险评估" label-width="120px">
                        <el-select v-model="form.callEndSuicideRisk" placeholder="请选择自杀风险评估" clearable>
                            <el-option v-for="item in order_call_end_suicide_risk" :key="item.value"
                                :label="item.label" :value="item.value" />

                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="危害他人评估" label-width="120px">
                        <el-select v-model="form.callEndHarmOthers" placeholder="请选择危害他人风险评估" clearable>
                            <el-option v-for="item in order_call_end_harm_others" :key="item.value"
                                :label="item.label" :value="item.value" />

                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="危害公共评估" label-width="120px">
                        <el-select v-model="form.callEndEndangerPublicSafe" placeholder="请选择危害公共安全风险评估"
                            clearable>

                            <el-option v-for="item in order_call_end_harm_others" :key="item.value"
                                :label="item.label" :value="item.value" />

                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="情绪舒缓评估" label-width="120px">
                        <el-select v-model="form.callEndMoodRelax" placeholder="请选择情绪舒缓评估" clearable>
                            <el-option v-for="item in order_call_end_mood_relax" :key="item.value"
                                :label="item.label" :value="item.value" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="信息咨询评估" label-width="120px">
                        <el-select v-model="form.callEndInfoConsult" placeholder="请选择信息咨询类评估" clearable>
                            <el-option v-for="item in order_call_end_info_consult" :key="item.value"
                                :label="item.label" :value="item.value" />
                        </el-select>
                    </el-form-item>
                </el-col>

                </el-row>

        </div>
        <!-- 悬浮提交按钮 -->
        <div class="bottom-0 left-0 right-0 p-4 bg-white border-t flex justify-end" style="position: absolute;">
            <el-button type="primary" class="w-32 !rounded-button whitespace-nowrap"
                @click="submit">提交工单</el-button>
        </div>
    </div>
</template>

<script setup>
import { shallowRef, reactive, ref, onMounted, watch } from 'vue'

import useSelectStore from '@/store/commonSelect/common';
import { ElMessage } from 'element-plus';
import { getPageListData, editPageData, createPageData } from '@/api/main/system/system';
import { getUnprefixNuber} from '@/utils/index';

const areaTree = useSelectStore().areaTree;
let { proxy } = getCurrentInstance()

// 必须导出，否则模板中无法使用
const {
    order_handling_measures,
    order_grade,
    order_marital_status,
    order_living_status,
    order_career,
    order_emotion,
    order_coping_style,
    order_risk_factor,
    order_past_help,
    order_treat_now,
    order_medication_status,
    order_suicide_risk,
    order_self_injury,
    order_harm_others,
    order_weijiganyu,
    order_suifangyuyue,
    order_call_end_suicide_risk,
    order_call_end_harm_others,
    order_call_end_info_consult,
    order_call_end_mood_relax,
    order_outpatient } =
    proxy.useDict('order_handling_measures',
        'order_grade',
        'order_marital_status',
        'order_living_status',
        'order_career',
        'order_emotion',
        'order_coping_style',
        'order_risk_factor',
        'order_past_help',
        'order_treat_now',
        'order_medication_status',
        'order_suicide_risk',
        'order_self_injury',
        'order_harm_others',
        'order_handling_measures',
        'order_weijiganyu',
        'order_suifangyuyue',
        'order_call_end_suicide_risk',
        'order_call_end_harm_others',
        'order_call_end_info_consult',
        'order_call_end_mood_relax',
        'order_outpatient');

const formRef = ref(null);
let form = ref({
    tag: [],
    handlingMeasures: [],
    ageGroup: '',
    age: '',
    area: '',
    address: '',
    suggest: '',
    sex: '0',
    isNeedVisit: false,
    id: 0,
    name: '',
    phone: '',
    type: [],
    typeCode: '',
    description: '',
    handleMethod: '1',
    department: '',

    crisisInterfere: '', // 干预项目
    hmLinkageTime: '', // 联动时间
    hmLinkageDept: '', // 联动单位
    hmLinkageTel: '', // 联动电话
    agreeLink: '', // 联系他人
    aboutLinkTel: '', // 联系电话
    relation: '', // 与来电者关系

    callType: '1', // 来电类型
    grade: '',     // 教育状况
    maritalStatus: '', // 婚姻状况
    livingStatus: '', // 居住状态
    career: '', // 从业状况
    emotion: '', // 主导情绪
    emotionOther: '', // 自定义情绪其他的
    replyMethod: '', // 主导情绪的主要应对方式
    replyMethodOther: '', // 自定义应对方式其他的
    recentMood: '', // 近期心境
    recentMoodOther: '', // 近期心境其他
    recentMoodDuration: '', // 近期心境持续时间
    // durationUnit: '天', // 持续时间单位
    copingStyle: '', // 近期心境的主要应对方式
    copingStyleOther: '', // 请输入其他应对方式
    socialSupport: '', // 社会支持
    riskFactor: '', // 易感因素
    riskFactorOther: '', // 其他易感因素"
    pastHelp: '', // 求助情况
    treatNow: '', // 治疗情况
    outpatient: '', // 门诊治疗
    medicationStatus: '', // 服用情况
    teenagerFlag: '不详', // 是否与青少年相关
    suicideRisk: '', // 自杀风险评估
    suicide_occurrence: '', // 是否出现自杀
    suicideCount: '', // 自杀次数
    selfInjury: '', // 自身伤害
    selfInjuryOther: '', // 自定义自身伤害其他
    harmOthers: '', // 危害他人风险评估
    existHarmOthers: '', // 是否出现危害他人
    endangerPublicSafe: '', // 危害公共安全
    existEndangerPublicSafe: '', // 是否出现过
    mainProblem: '', // 主要问题

    appointment: '', // 随访预约
    sfLinkman: '', // 随访联系人
    sfLinkmanTel: '', // 预约电话
    sfPlanTime: '', // 预约时间
    content: '', // 咨询记录
    callEndSuicideRisk: '', // 来电结束前自杀风险评估  
    callEndHarmOthers: '', // 危害他人风险评估   
    callEndEndangerPublicSafe: '', // 危害公共安全风险评估 
    callEndMoodRelax: '', // 情绪舒缓评估
    callEndInfoConsult: '', // 信息咨询类评估
});

const props = defineProps({
    getDefaultInfo: {
        type: Object,
        default: () => ({}),
    },
    propRecordData: {
        type: Object,
        default: () => ({}),
    }
});
watch(props, (nweProps) => {
    initMethod(props);
});

const ageGroupOptions = [{
    value: '青少年',
    label: '青少年'
}, {
    value: '中年',
    label: '中年'
}, {
    value: '老年',
    label: '老年'
}, {
    value: '未知',
    label: '未知'
}];


const updateAgeGroup = () => {
  const age = parseInt(form.value.age);
  if (!age || isNaN(age)) {
    form.value.ageGroup = '未知';
  } else if (age < 18) {
    form.value.ageGroup = '青少年';
  } else if (age < 55) {
    form.value.ageGroup = '中年';
  } else {
    form.value.ageGroup = '老年';
  }
};

// 近期心境逻辑
const recentEmotionQiTa = ref(false)
function handleRecentEmotion(val) {
    if (val === 'zdqxqita') {
        recentEmotionQiTa.value = true;
    } else {
        recentEmotionQiTa.value = false;
    }
}
const recentEmotionWayQiTa = ref(false)
function handleRecentEmotionWay(val) {
    if (val === 'ydfsqita') {
        recentEmotionWayQiTa.value = true;
    } else {
        recentEmotionWayQiTa.value = false;
    }
}
// 易感因素逻辑
const susceptibleFactorsQiTa = ref(false)
function handleSusceptibleFactors(val) {
    if (val === 'qita') {
        susceptibleFactorsQiTa.value = true;
    } else {
        susceptibleFactorsQiTa.value = false;
    }
}

const handleNeedVisitChange = (val) => { }

const handleMethodChange = (val) => { console.log(val, 'val') } // 处理方式
const ticketTypes = useSelectStore().dictOrderTypeList;
const departments = useSelectStore().deptListData;
onMounted(() => {
    initMethod(props);
    getLabelsTree();
});

const initMethod = (props) => {
    if (props.getDefaultInfo.workorderId) {
        console.log('props.getDefaultInfo', props.getDefaultInfo);
        
        form.value = {
            id: props.getDefaultInfo.workorderId,
            name: props.getDefaultInfo.caller || '',
            phone: props.getDefaultInfo.callnum || '',
            type: props.getDefaultInfo.workordercate,
            typeCode: '',
            tag: props.getDefaultInfo.tag && props.getDefaultInfo.tag.split(',') || [],
            description: props.getDefaultInfo.content,
            handleMethod: props.getDefaultInfo.isend.toString(),
            department: '',
            sex: (props.getDefaultInfo.sex || '0') + '',
            ageGroup: props.getDefaultInfo.ageGroup || '未知',
            age: props.getDefaultInfo.age || '',
            area: props.getDefaultInfo.area || '',
            address: props.getDefaultInfo.address || '',
            suggest: props.getDefaultInfo.suggest || '',
            handlingMeasures: props.getDefaultInfo.handlingMeasures && props.getDefaultInfo.handlingMeasures.split(',') || [],
            isNeedVisit: props.getDefaultInfo.isNeedVisit ? true : false,

            crisisInterfere: props.getDefaultInfo.handling.crisisInterfere || '', // 干预项目
            hmLinkageTime: props.getDefaultInfo.handling.hmLinkageTime || '', // 联动时间
            hmLinkageDept: props.getDefaultInfo.handling.hmLinkageDept || '', // 联动单位
            hmLinkageTel: props.getDefaultInfo.handling.hmLinkageTel || '', // 联动电话
            agreeLink: props.getDefaultInfo.handling.agreeLink || '', // 联系他人
            aboutLinkTel: props.getDefaultInfo.handling.aboutLinkTel || '', // 联系电话
            relation: props.getDefaultInfo.handling.relation || '', // 与来电者关系

            callType: props.getDefaultInfo.callType.toString() || '1', // 来电类型
            grade: props.getDefaultInfo.grade || '', // 教育状况
            maritalStatus: props.getDefaultInfo.maritalStatus || '', // 婚姻状况
            livingStatus: props.getDefaultInfo.livingStatus || '', // 居住状态
            career: props.getDefaultInfo.career || '', // 从业状况
            emotion: props.getDefaultInfo.assessment.emotion || '', // 主导情绪
            emotionOther: props.getDefaultInfo.assessment.emotionOther || '', // 自定义情绪其他的
            replyMethod: props.getDefaultInfo.assessment.replyMethod || '', // 主导情绪的主要应对方式
            replyMethodOther: props.getDefaultInfo.assessment.replyMethodOther || '', // 自定义应对方式其他的
            recentMood: props.getDefaultInfo.assessment.recentMood || '', // 近期心境 
            recentMoodOther: props.getDefaultInfo.assessment.recentMoodOther || '', // 近期心境其他  str.match(/\d+/g)  
            recentMoodDuration:props.getDefaultInfo.assessment.recentMoodDuration || '', // 近期心境持续时间
            // durationUnit: props.getDefaultInfo.assessment.recentMoodDuration && (props.getDefaultInfo.assessment.recentMoodDuration.match(/[\u4e00-\u9fa5]/g).join(',') || '天'), // 持续时间单位
            copingStyle: props.getDefaultInfo.assessment.copingStyle || '', // 近期心境的主要应对方式
            copingStyleOther: props.getDefaultInfo.assessment.copingStyleOther || '', // 请输入其他应对方式    
            socialSupport: props.getDefaultInfo.assessment.socialSupport || '', // 社会支持
            riskFactor: props.getDefaultInfo.assessment.riskFactor || '', // 易感因素
            riskFactorOther: props.getDefaultInfo.assessment.riskFactorOther || '', // 其他易感因素"
            pastHelp: props.getDefaultInfo.assessment.pastHelp || '', // 求助情况
            treatNow: props.getDefaultInfo.assessment.treatNow || '', // 治疗情况
            outpatient: props.getDefaultInfo.assessment.outpatient || '', // 门诊治疗
            medicationStatus: props.getDefaultInfo.assessment.medicationStatus || '', // 服用情况
            teenagerFlag: props.getDefaultInfo.assessment.teenagerFlag || '不详', // 是否与青少年相关
            suicideRisk: props.getDefaultInfo.assessment.suicideRisk || '', // 自杀风险评估    
            suicide_occurrence: props.getDefaultInfo.assessment.suicideCount?'是':'否', // 是否出现自杀
            suicideCount: props.getDefaultInfo.assessment.suicideCount || '', // 自杀次数
            selfInjury: props.getDefaultInfo.assessment.selfInjury || '', // 自身伤害
            selfInjuryOther: props.getDefaultInfo.assessment.selfInjuryOther || '', // 自定义自身伤害其他
            harmOthers: props.getDefaultInfo.assessment.harmOthers || '', // 危害他人风险评估
            existHarmOthers: props.getDefaultInfo.assessment.existHarmOthers || '', // 是否出现危害他人

            endangerPublicSafe: props.getDefaultInfo.assessment.endangerPublicSafe || '', // 危害公共安全
            existEndangerPublicSafe: props.getDefaultInfo.assessment.existEndangerPublicSafe || '', // 是否出现过
            mainProblem: props.getDefaultInfo.handling.mainProblem || '', // 主要问题

            appointment: props.getDefaultInfo.handling.appointment || '', // 随访预约
            sfLinkman: props.getDefaultInfo.handling.sfLinkman || '', // 随访联系人
            sfLinkmanTel: props.getDefaultInfo.handling.sfLinkmanTel || '', // 预约电话
            sfPlanTime: props.getDefaultInfo.handling.sfPlanTime || '', // 预约时间
            callEndSuicideRisk: props.getDefaultInfo.assessment.callEndSuicideRisk || '', // 来电结束前自杀风险评估
            callEndHarmOthers: props.getDefaultInfo.assessment.callEndHarmOthers || '', // 危害他人风险评估
            callEndEndangerPublicSafe: props.getDefaultInfo.assessment.callEndEndangerPublicSafe || '', // 危害公共安全风险评估
            callEndMoodRelax: props.getDefaultInfo.assessment.callEndMoodRelax || '', // 情绪舒缓评估
            callEndInfoConsult: props.getDefaultInfo.assessment.callEndInfoConsult || '', // 信息咨询类评估     

        }
    } else {
        resetForm()
    }
   
    
    if (props.propRecordData.id) {
        form.value = {
            callId: props.propRecordData.id,
            phone: getUnprefixNuber(props.propRecordData.phone),
            handleMethod:'1'
        }
    }

}

const emit = defineEmits(["refreshOrder", "orderTypeChange"]);


const rules = {
    name: [
        { required: true, message: '请输入姓名', trigger: 'blur' },
        { min: 2, max: 20, message: '姓名长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        // { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
    ],
    type: [
        { required: true, message: '请选择工单类型', trigger: 'change' }
    ],
    description: [
        { required: true, message: '请输入问题描述', trigger: 'blur' },
        { min: 5, max: 2000, message: '问题描述5-2000个字符', trigger: 'blur' },
    ],
    suggest: [
        // { required: true, message: '请输入问题描述', trigger: 'blur' },
        { min: 5, max: 2000, message: '干预建议5-2000个字符', trigger: 'blur' },
    ],
    handleMethod: [
        { required: true, message: '请选择处理方式', trigger: 'change' }
    ],
};


const handleMethods = [
    { label: '立即完结', value: '1' },
    { label: '待交办', value: '0' },
    // { label: '待回访', value: '2' },
];

const typeCascaderRef = ref(null);

const handleTypeChange = (value) => {
    if (typeCascaderRef.value) {
        const selectNode = typeCascaderRef.value.getCheckedNodes();
        form.value.typeCode = selectNode[selectNode.length - 1].data.code;
    }
}

// 投诉部门切换
const deptCascaderRef = ref(null);
const deptChange = (value) => {
    // if (deptCascaderRef.value) {
    //     const selectNode = deptCascaderRef.value.getCheckedNodes()[0];
    //     form.value.department = selectNode.data.label;
    // }
}

const submit = async () => {
    console.log(form.value, 'submit');
    // 验证表单必填项
    formRef.value.validate(async (valid) => {
        if (valid) {
            const params = {
                caller: form.value.name,
                callnum: form.value.phone,
                content: form.value.description,
                customerno: form.value.phone,
                firsttype: 1000,
                isend: +form.value.handleMethod,
                workordercate: form.value.type[form.value.type.length - 1],

                callType: form.value.callType,  // 来电类型
                grade: form.value.grade,     // 教育状况
                handling:{
                    aboutLinkTel: form.value.aboutLinkTel, // 联系电话
                    agreeLink: form.value.agreeLink, // 联系他人    
                    appointment: form.value.appointment, // 随访预约
                    crisisInterfere: form.value.crisisInterfere, // 干预项目
                    hmLinkageDept: form.value.hmLinkageDept, // 联动单位
                    hmLinkageTel: form.value.hmLinkageTel, // 联动电话
                    hmLinkageTime: form.value.hmLinkageTime, // 联动时间
                    mainProblem: form.value.mainProblem ? form.value.mainProblem[form.value.mainProblem.length - 1] : '', // 主要问题
                    relation: form.value.relation, // 与来电者关系
                    sfLinkman: form.value.sfLinkman, // 随访联系人
                    sfLinkmanTel: form.value.sfLinkmanTel, // 预约电话
                    sfPlanTime: form.value.sfPlanTime, // 预约时间
                },
                assessment:{
                    callEndEndangerPublicSafe: form.value.callEndEndangerPublicSafe, // 危害公共安全风险评估
                    callEndHarmOthers: form.value.callEndHarmOthers, // 危害他人风险评估
                    callEndInfoConsult: form.value.callEndInfoConsult, // 信息咨询类评估
                    callEndMoodRelax: form.value.callEndMoodRelax, // 情绪舒缓评估  
                    callEndSuicideRisk: form.value.callEndSuicideRisk, // 来电结束前自杀风险评估
                    copingStyle: form.value.copingStyle, // 近期心境的主要应对方式
                    copingStyleOther: form.value.copingStyleOther, // 请输入其他应对方式
                    emotion: form.value.emotion, // 主导情绪
                    emotionOther: form.value.emotionOther, // 自定义情绪其他的
                    endangerPublicSafe: form.value.endangerPublicSafe, // 危害公共安全
                    existEndangerPublicSafe: form.value.existEndangerPublicSafe, // 是否出现过
                    existHarmOthers: form.value.existHarmOthers, // 是否出现危害他人    
                    harmOthers: form.value.harmOthers, // 危害他人风险评估
                    medicationStatus: form.value.medicationStatus, // 服用情况
                    outpatient: form.value.outpatient, // 门诊治疗
                    pastHelp: form.value.pastHelp, // 求助情况
                    recentMood: form.value.recentMood, // 近期心境
                    recentMoodDuration: form.value.recentMoodDuration , // 近期心境持续时间   ? (form.value.recentMoodDuration + form.value.durationUnit) : ''
                    recentMoodOther: form.value.recentMoodOther, // 近期心境其他
                    replyMethod: form.value.replyMethod, // 主导情绪的主要应对方式
                    replyMethodOther: form.value.replyMethodOther, // 自定义应对方式其他的
                    riskFactor: form.value.riskFactor, // 易感因素
                    riskFactorOther: form.value.riskFactorOther, // 其他易感因素"
                    selfInjury: form.value.selfInjury, // 自身伤害
                    selfInjuryOther: form.value.selfInjuryOther, // 自定义自身伤害其他
                    socialSupport: form.value.socialSupport, // 社会支持
                    suicideCount: form.value.suicideCount, // 自杀次数
                    suicideRisk: form.value.suicideRisk, // 自杀风险评估
                    treatNow: form.value.treatNow, // 治疗情况  
                },
                
                maritalStatus: form.value.maritalStatus, // 婚姻状况
                livingStatus: form.value.livingStatus, // 居住状态  
                career: form.value.career, // 从业状况
                teenagerFlag: form.value.teenagerFlag, // 是否与青少年相关
                suicide_occurrence: form.value.suicide_occurrence, // 是否出现自杀  
                appointment: form.value.appointment, // 随访预约

            };
            if (form.value.callId) {
                params.callId = form.value.callId
            }

            if (form.value.area) {
                params.area = form.value.area ? form.value.area[form.value.area.length - 1] : '';
            }

            if (form.value.age) params.age = form.value.age;
            if (form.value.ageGroup) params.ageGroup = form.value.ageGroup;
            if (form.value.address) params.address = form.value.address;
            if (form.value.suggest) params.suggest = form.value.suggest;
            if (form.value.sex) params.sex = form.value.sex;
            params.isNeedVisit = form.value.isNeedVisit ? 1 : 0;

            if (form.value.handlingMeasures.length > 0) {
                params.handlingMeasures = form.value.handlingMeasures.join(',');
            }

            if (form.value.tag) {
                params.tag = form.value.tag.join(',');
            }

            // 提交表单
            if (form.value.id) {
                params.workorderId = form.value.id;
                editPageData('/order/workorder', params).then((data) => {
                    console.log(data, 'submit');
                    if (data.state === 'success') {
                        ElMessage.success('提交成功');
                        // resetForm()
                        emit("refreshOrder");
                    } else {
                        ElMessage.error(data.message || '提交失败');
                    }

                })
            } else {
                createPageData('/order/workorder', params).then((data) => {
                    console.log(data, 'submit');
                    if (data.state === 'success') {
                        ElMessage.success('提交成功');
                        // resetForm()
                        emit("refreshOrder");
                    } else {
                        ElMessage.error(data.message || '提交失败');
                    }

                })
            }


        } else {
            ElMessage.error('请填写完整信息');
        }

    });
}

const labels = ref([]);
const labelCascaderRef = ref(null);
const getLabelsTree = () => {
    getPageListData('/patient/tag/getdata').then(({ data }) => {
        labels.value = data;
    });
}
/**
 * 重置表单
 */
const resetForm = () => {
    form.value = {
        ageGroup: '',
        age: '',
        area: '',
        address: '',
        suggest: '',
        isNeedVisit: false,
        name: '',
        phone: '',
        type: '',
        typeCode: '',
        description: '',
        handleMethod: '1',
        department: '',

        callType: '1', // 来电类型
        grade: '',     // 教育状况
        maritalStatus: '', // 婚姻状况
        livingStatus: '', // 居住状态
        career: '', // 从业状况
        emotion: '', // 主导情绪
        emotionOther: '', // 自定义情绪其他的
        replyMethod: '', // 主导情绪的主要应对方式
        replyMethodOther: '', // 自定义应对方式其他的
        recentMood: '', // 近期心境
        recentMoodOther: '', // 近期心境其他
        recentMoodDuration: '', // 近期心境持续时间
        copingStyle: '', // 近期心境的主要应对方式
        copingStyleOther: '', // 请输入其他应对方式
        socialSupport: '', // 社会支持
        riskFactor: '', // 易感因素
        riskFactorOther: '', // 其他易感因素"
        pastHelp: '', // 求助情况
        treatNow: '', // 治疗情况
        outpatient: '', // 门诊治疗
        medicationStatus: '', // 服用情况
        teenagerFlag: '不详', // 是否与青少年相关
        suicideRisk: '', // 自杀风险评估
        suicide_occurrence: '', // 是否出现自杀
        suicideCount: '', // 自杀次数
        selfInjury: '', // 自身伤害
        selfInjuryOther: '', // 自定义自身伤害其他
        harmOthers: '', // 危害他人风险评估
        existHarmOthers: '', // 是否出现危害他人
        endangerPublicSafe: '', // 危害公共安全
        existEndangerPublicSafe: '', // 是否出现过
        mainProblem: '', // 主要问题
        handlingMeasures: [], // 处理措施
        crisisInterfere: '', // 干预项目
        hmLinkageTime: '', // 联动时间
        hmLinkageDept: '', // 联动单位
        hmLinkageTel: '', // 联动电话
        agreeLink: '', // 联系他人
        aboutLinkTel: '', // 联系电话
        relation: '', // 与来电者关系
        appointment: '', // 随访预约
        sfLinkman: '', // 随访联系人
        sfLinkmanTel: '', // 预约电话
        sfPlanTime: '', // 预约时间
        content: '', // 咨询记录

        callEndSuicideRisk: '', // 来电结束前自杀风险评估  
        callEndHarmOthers: '', // 危害他人风险评估   
        callEndEndangerPublicSafe: '', // 危害公共安全风险评估 
        callEndMoodRelax: '', // 情绪舒缓评估
        callEndInfoConsult: '', // 信息咨询类评估
    };
    formRef.value.resetFields();
}
</script>


<style lang="scss" scoped>
.order-main {
    width: 100%;
}

.order-layout {
    display: flex;
    margin-top: 10px;
}
</style>