<template>
    <div class="wrap">
        <div class="descripEle">
            <div class="title">
                <span class="title-text">{{ planDetail.name }}</span>
                <div class="title-btn">
                    <el-button :type="taskStatusMap[taskDetail.state].color" size="small"
                        v-if="taskStatusMap[taskDetail.state]">{{ taskStatusMap[taskDetail.state].title }}</el-button>
                </div>
                <div class="btn-call">
                    <el-button @click="callPhone" v-if="planDetail.way === 1 && planDetail.executionMethod === 1" :icon="Phone">呼叫</el-button>
                    <el-button @click="sendMessage" v-if="planDetail.way === 2 && planDetail.executionMethod === 1" :icon="Message">发送</el-button>
                </div>
            </div>
            <div class="content">
                <div class="content-info" v-if="planDetail.describes">{{ planDetail.describes }}</div>
                <div class="content-item">
                    <div class="item1">
                        更新时间：{{ planDetail.updateTime || planDetail.createTime }}
                    </div>
                    <div class="item2">
                        周期：{{ getTimeFrame(planDetail.beginEffective, planDetail.endEffective) }}
                    </div>
                </div>
                <div class="content-form"  v-show="planDetail.way && planDetail.way === 1">
                    <el-form-item label="结果">
                        <el-radio-group v-model="form.state">
                            <el-radio :value="item.value" size="large"
                                v-for="item in (taskResults && taskResults.filter((o) => { return !!o.value }))" :key="item.value">
                                {{ item.title  }}
                            </el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="标签">
                        <el-radio-group v-model="form.resultLabel">
                            <el-radio :value="item.value" size="large"
                                v-for="item in resultLabels && resultLabels.filter((o) => { return !!o.value })" :key="item.value">
                                {{ item.title  }}
                            </el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="备注">
                        <el-input v-model="form.desc" type="textarea" />
                    </el-form-item>
                </div>
                <div class="content-questionnaire">
                    
                    <!-- 短信内容 -->
                    <!--TODO: 等添加的组件写完直接照抄-->
                    <div v-if="planDetail.way === 2">
                        <div style="margin-bottom: 10px;"><el-text tag="b">短信内容</el-text></div>
                        <div>
                            <span v-for="(node, index) in msgContent" :key="index">
                              <el-tag v-if="node.isTag" @click="node.click">{{ node.content }}</el-tag>
                              <el-link type="primary" v-if="node.isLink" @click="handleQuestion" style="line-height: 24px;">{{ node.content }}</el-link>
                              <span v-if="!node.isTag && !node.isLink" v-html="node.content"></span>
                            </span>
                           
                        </div>
                    </div>

                    <!-- 问卷组件 -->
                    <question v-if="isParentMounted && (planDetail.way === 1 || (planDetail.messageType === 1 && planDetail.messageParameter))" ref="questionRef"
                        :surveyId="planDetail.questionnaire || planDetail.messageParameter" :userId="taskDetail.patientFiles" :taskId="taskDetail.patientTaskId"></question>
                </div>
                <div class="content-submit" v-if="taskDetail.state === 1 && planDetail.way === 1 && planDetail.executionMethod === 1">
                    <el-button @click="handleCreat">创建工单</el-button>
                    <el-button type="primary" @click="submit">提交</el-button>
                </div>
                <div class="content-submit" v-if="taskDetail.state === 3">
                    <el-button type="primary" @click="submit">保存</el-button>
                </div>
            </div>
        </div>
        <el-dialog
            v-model="dialogAddWorkorder"
            :title="modalTitle"
            center
            width="70%"
            :modal="true"
            :show-close="true"
        >
            <page-order :taskId="taskId" :getDefaultInfo="defaultOrderInfo" @refreshOrder="submitRefresh()"></page-order>
        </el-dialog>
    </div>
</template>
<script setup>
import { ref,onMounted,watch, h } from "vue";
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus'
import { userDecrypt } from '@/utils/aes'
import { Message, Phone } from '@element-plus/icons-vue'

import PageOrder from '@/components/page-order';
import question from '@/views/main/survey/fill.vue'

import { getTimeFrame, ArrayToMap } from '@/utils/tools'
import { taskResults, taskStatus } from "@/utils/commonDic.js"
import useSocketStore from '@/store/modules/socket';
import { Send } from '@/utils/telWebsocket';
import useUserStore from '@/store/modules/user'
import { matchTags } from '@/utils/sms'
import useSelectStore from '@/store/commonSelect/common';

import { createPageData, } from '@/api/main/system/system';

import { getPlanInfo } from '@/api/patient/plan';
import { getTaskInfo, submitTaskResult } from '@/api/patient/task';
import { smsDetail } from '@/api/system/sms'
import { getPhoneFix } from '@/api/main/main';

const router = useRouter();
let planDetail = ref({});
let taskDetail = ref({});
const isParentMounted = ref(false);
const questionRef = ref();
const { proxy } = getCurrentInstance();
const callId = ref('');
const lineState = ref('');
const resultLabels = ref([]);
const defaultOrderInfo = ref({
    caller: '',
    callnum: '',

});

const msgContent = ref();

const form = ref({
    state: '',
    desc: '',
    resultLabel: '',
})

const props = defineProps({
    planId: {
        type: Number,
        default: 0
    },
    taskId: {
        type: Number,
        default: 0
    },
});
watch(props, (nweProps) => {
    console.log('watch props', nweProps);
    initMethod(props)
});

const emit = defineEmits([
    'submit'
])
const dialogAddWorkorder = ref(false)
const modalTitle = ref('添加工单')
function submitRefresh() {
    ElMessage({
        message: '创建成功',
        type: 'success',
    })
    dialogAddWorkorder.value = false
}
function handleCreat() {
    defaultOrderInfo.value.caller = taskDetail.value.name;
    defaultOrderInfo.value.callnum = userDecrypt(taskDetail.value.mobile);
    console.log(defaultOrderInfo.value, 'defaultOrderInfo.value')
    dialogAddWorkorder.value = true
}

const smsTempDetail = ref({})

onMounted(() => {
    resultLabels.value = useSelectStore().resultLabels;
    initMethod(props)
});

const clickTag = () => {
    console.log('处理厂k');
}


async function initMethod(props) {
    callId.value = '';

    const promiseAll = []
    const types = [];
    if (props.planId) {
        types.push('plan');
        promiseAll.push(getPlanInfo(props.planId));
    }
    if (props.taskId) {
        types.push('task');
        promiseAll.push(getTaskInfo(props.taskId));
    }

    const result = await Promise.all(promiseAll);

    for (let index = 0; index < types.length; index++) {
        const type = types[index];
        const res = result[index];
        if (res && res.state === 'success') {
            if (type === 'plan') {
                planDetail.value = res.data || {}
            }
            if (type === 'task') {
                taskDetail.value = res.data || {}

                if (taskDetail.value.callState && taskDetail.value.state > 1) {
                    form.value.state = taskDetail.value.callState;
                    form.value.desc = taskDetail.value.sfResult;
                    form.value.resultLabel = taskDetail.value.labelValue;
                } else {
                    form.value.desc = '';
                    const initStatus = taskResults.find((o) => { return !!o.checked });
                    if (initStatus) form.value.state = initStatus.value
                }
                taskDetail.value.seatName = res.data.seatName ? res.data.seatName : useUserStore().name
                isParentMounted.value = true;
            }
        }
    }

    if (planDetail.value.message && planDetail.value.way === 2) {
        smsDetail(planDetail.value.message).then((smsRes) => {
            if (smsRes && smsRes.state === 'success') {
                smsTempDetail.value = smsRes.data

                let urlLabel = '';
                if (planDetail.value.messageType === 2) urlLabel = planDetail.value.messageParameter;
                if (planDetail.value.messageType === 1) {
                    urlLabel = '问卷'
                }
                msgContent.value = matchTags(smsRes.data.content, {
                    userName: {
                        label: taskDetail.value.name,
                    },
                    seatUser: {
                        label: taskDetail.value.seatName,
                        // click: () => {
                        //     console.log(111);
                        // }
                    },
                    url: {
                        label: urlLabel,
                    },
                });

            }
        })
    }
}

const taskStatusMap = ArrayToMap(taskStatus, 'value');

// 提交结果
const submit = () => {
    console.log(lineState.value)
    if (!(lineState.value === '' || lineState.value === '在线')) return proxy.$modal.msgError('请等待用户挂断');
    let params = {}
    if (planDetail.value.way === 1 &&  form.value.state === '正常接听') {
    // if (planDetail.value.way === 1) {
        params = questionRef.value.getParams();
    }
    console.log(params, 'params');
    
    if (!params &&  form.value.state === '正常接听') return;
    // if (!params) return;
    params.entername = taskDetail.value.name;
    params.answeruser = taskDetail.value.patientFiles;
    params.enterphone = taskDetail.value.mobile;

    

    // 更新state
    const stateInfo = taskResults.find((o) => {
        return o.value === form.value.state
    });

    let resultParams = {
        patientTaskId: taskDetail.value.patientTaskId,
        callState: form.value.state,
        sfResult: form.value.desc,
        labelValue: form.value.resultLabel || '',
    };
    if (callId.value) resultParams.callRecords = callId.value;
    if (stateInfo) {
        if (stateInfo.error) {
            resultParams.state = 4;
        } else if (stateInfo.end) {
            resultParams.state = 3;
        }
    }
    
    // if (stateInfo && stateInfo.end) resultParams.state = 3;
    // if (form.value.state === '无人接听') {
    //     resultParams.state = 1
    // }


    console.log(resultParams)
    console.log(params)
    // return
    //TODO: 增加判断，电话类型的如果接通，必须挂点电话之后才可以提交
    submitTaskResult({  
        ...resultParams,
        answer: params,
        planId: planDetail.value.plId,
    }).then((res) => {
        if (res.state === 'success') {
            ElMessage({
                message: '操作成功',
                type: 'success',
            })

            // 告诉父级组件完成了
            emit('submit')
        } else {
            // 失败
            ElMessage({
                message: '操作失败',
                type: 'error',
            })
        }
    })
}

// 发送短信
const sendMessage = () => {
    //TODO: 组装短信，并发送短信
   console.log(taskDetail.value.patientTaskId)
   const  params = {
        taskId: taskDetail.value.patientTaskId,
   }
   createPageData('/SfPlanPatient/sfplanpatient/submitsms?taskId='+taskDetail.value.patientTaskId).then((data) => {
        proxy.$modal.msgSuccess('发送成功！');

    })
    // 点击发送成功之后，需要更改状态
}
const scoketDatas = ref({});
const stateObj = {
  0:'离线',
  1:'登录中',
  2:'在线',
  3:'通话中',
  4:'话后处理中',
  5:'离线',
  6:'振铃',
  7:'注销',
}
// 外呼
const callPhone = () => {
    lineState.value = '发起外呼';
    // 获取解密后的手机号
    
    const phone = userDecrypt(taskDetail.value.mobile);
    // const phone = '15838094023'
    //TODO: 增加外呼逻辑
    if (!useSocketStore().accountNumber) {
        proxy.$modal.msgSuccess('还没有签入');
        lineState.value = '';
        return
    }
    getPhoneFix(phone).then((data) => {
        if (data.state === 'success') {
            scoketDatas.value = {
                AgentID: useSocketStore().accountNumber,
                AgentExten: useSocketStore().extensionNumber,
                Type: 'MakeCall',
                DestinationNumber: data.data[0],
            };
            console.log(scoketDatas.value);
            Send(scoketDatas.value, (data) => {
                console.log(data, 'data'); //{CallID: 'c6207188-1361-11ef-8802-2b593e364a61', RecPath: '/home/wav/luyin/20240516/1009/165344_c6207188136111ef88022b593e364a61.wav', Result: true, Type: 'RecordPath'}
                if (data.Type === 'MakeCall') {
                    console.log('外呼');
                   
                    if (data.Result == true) {
                        proxy.$modal.msgSuccess('外呼成功');
                    } else {
                        proxy.$modal.msgError('外呼失败');
                    }
                }

                if (data.Type === 'CallID') {
                    callId.value = data.CallID;
                }

                if (data.Type === 'State') {
                    lineState.value = stateObj[data.State];
                }
                console.log(lineState.value)
            });
        } else {
            lineState.value = '';
        }
    }).catch(() => {
        proxy.$modal.msgError('外呼失败');
        lineState.value = '';
    });

    
}

</script>
<style scoped lang="scss">
.wrap {
    .descripEle {
        .title {
            position: relative;
            display: flex;

            .title-text {
                font-size: 18px;
                font-weight: bold;
                line-height: 36px;
                margin-right: 30px;
            }

            .title-btn {
                margin-top: 7px;
                display: inline-block;
            }

            .btn-call {
                position: absolute;
                right: 15px;
                top: 3px;
            }
        }

        .content {
            font-size: 14px;
            color: #606266;

            .content-info {
                line-height: 28px;
            }

            .content-item {
                display: flex;
                margin-bottom: 15px;

                .item1 {
                    margin-right: 30px;
                }
            }

            .content-submit {
                margin: 0 auto;
                text-align: center;
                position: absolute;
                bottom: 12px;
                width: 45%;
            }

        }

    }
}
</style>