<template>
    <el-dialog
        destroy-on-close
        v-model="visible"
        center
        width="1000"
        class="list-dialog"
        :title="pageType=='add'?'新建跟进':'编辑跟进'"
    >
        <div v-loading="dialogLoading">
            <!-- <editor v-model="value" style="height: 600px" /> -->
            <el-form
                ref="ruleFormRef"
                :model="ruleForm"
                :rules="rules"
                label-width="auto"
                class="demo-ruleForm"
                :size="formSize"
                status-icon
            >

                <el-form-item  label="" class="business-item" prop="subject">
                    <!-- <el-input v-model="ruleForm.subject" placeholder="请输入跟进主题"/> -->
                    <el-autocomplete
                        placeholder="请输入跟进主题"
                        v-model="ruleForm.subject"
                        :fetch-suggestions="querySearch"
                        @select="subjectSelect"
                    >
                    </el-autocomplete>
                    <el-select v-if='changeTask' placeholder="选择任务" v-model="ruleForm.taskId"  fit-input-width filterable @change='gerTaskValue'>
                        <el-option v-for="item in taskList" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                    <el-input style='flex:1' v-else v-model="ruleForm.taskContent" disabled/>
                </el-form-item>

                <el-form-item label="" prop="">
                    <el-col :span="11">
                        <el-form-item label="" prop="followUpTime">
                            <el-date-picker
                                style="width: 100%;"
                                v-model="ruleForm.followUpTime"
                                value-format="YYYY-MM-DD HH:mm:ss"
                                type="datetime"
                                placeholder="跟进时间"
                                :disabled-date='disabledDates'
                            />
                        </el-form-item>
                    </el-col>

                    <el-col :span="2">
                    </el-col>
                    <el-col :span="11">
                        <el-form-item prop="objectiveValue">
                            <SelectDict v-model="ruleForm.objectiveValue" placeholder="选择跟进目的"
                                dictCode="objective_value"></SelectDict>
                        </el-form-item>
                    </el-col>
                </el-form-item>

                <el-form-item label="" prop="">
                    <el-col :span="11">
                        <el-form-item label="" prop="followUpTypeValue">
                            <SelectDict v-model="ruleForm.followUpTypeValue" placeholder="跟进方式" dictCode="follow_up_type"></SelectDict>
                        </el-form-item>
                    </el-col>
                    <el-col :span="2">
                    </el-col>
                    <el-col :span="11">
                        <el-form-item prop="inOutMark">
                            <SelectDict v-model="ruleForm.inOutMark" placeholder="选择跟进方向"
                                            dictCode="in_out_mark"></SelectDict>
                        </el-form-item>
                    </el-col>
                </el-form-item>
                <el-form-item label="" prop="content">
                    <!-- <el-input
                        v-model="ruleForm.content"
                        maxlength="300"
                        style="width: 100%"
                        placeholder="勤跟进，多签单"
                        show-word-limit
                        type="textarea"
                    /> -->
                    <ckeditor class="template_ckeditor" type="mini" @sendContnet="getContent" :content="ruleForm.content"></ckeditor>
                </el-form-item>
                <el-form-item label="上传附件：" class="form-item">
                    <Upload v-model="ruleForm.resourceIdList" :isTips='false' :resourceList="fileList" />
                </el-form-item>
                <el-form-item :label="(ruleForm.resourceType=='11'||ruleForm.resourceType=='20'&&ruleForm.customerForm=='11')?'线索名称：':'客户名称：'" prop="customerName">
                    <el-input v-model="ruleForm.customerName" disabled/>
                </el-form-item>

                <el-form-item v-if="changeType" label="关联业务：" class="business-item" prop="resourceType">
                    <el-select placeholder="选择业务类型" v-model="customerResourceType" clearable @change="changeBusiness">
                        <el-option v-for="item in dictData.businessData" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                    <el-select placeholder="选择" v-model="CustomerResourceTypeId" @change="changeBusinessId" v-loading="loading" fit-input-width filterable>
                        <el-option v-for="item in linkWorkData" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                </el-form-item>

                <!-- 客户、联系人 -->
                <template v-if="ruleForm.resourceType=='10'||(ruleForm.resourceType=='20'&&ruleForm.customerForm=='10')">
                    <el-form-item label="客户状态：" prop="resourceStageDictValue">
                        <SelectDict v-model="ruleForm.resourceStageDictValue" placeholder="客户状态" dictCode="customer_status"></SelectDict>
                    </el-form-item>
                </template>
                <!-- 线索 -->
                <template v-if="ruleForm.resourceType=='11'||(ruleForm.resourceType=='20'&&ruleForm.customerForm=='11')">
                    <el-form-item label="线索状态：" prop="resourceStageDictValue">
                        <SelectDict v-model="ruleForm.resourceStageDictValue" placeholder="请选择线索状态"
                            dictCode="clue_status"></SelectDict>
                    </el-form-item>
                </template>
                <!-- 商机 -->
                <template v-if="ruleForm.resourceType=='30'">
                    <el-form-item v-if='!changeType' label="商机标题：" prop="resourceName">
                        <el-input v-model="ruleForm.resourceName" disabled/>
                    </el-form-item>
                    <el-form-item label="商机阶段：" prop="resourceStageDictValue">
                        <SelectDict v-model="ruleForm.resourceStageDictValue" placeholder="请选择商机阶段"
                                    dictCode="business_stage"></SelectDict>
                    </el-form-item>
                </template>
                <!-- 订单 -->
                <template v-if="ruleForm.resourceType=='40'&&!changeType">
                    <el-form-item label="订单标题：" prop="resourceName">
                        <el-input v-model="ruleForm.resourceName" disabled/>
                    </el-form-item>
                </template>
                <el-form-item label="联系人：" prop="liaisonIdList" v-if='ruleForm.resourceType!="11"'>
                    <el-select-v2
                        multiple
                        v-model="ruleForm.liaisonIdList"
                        :options="liaisonOption"
                        placeholder="请选择客户联系人"
                        filterable
                        :disabled="ruleForm.resourceType=='20'"
                    />
                </el-form-item>


                <el-form-item label="提醒谁看：" prop="remindUserIdsTemp">
                    <SelectUser multiple @onOk="selectsUser" v-model='ruleForm.remindUserIdsTemp'></SelectUser>
                </el-form-item>
                <CreateQuickTask v-model="ruleForm.task" label="创建下次跟进任务"></CreateQuickTask>
            </el-form>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="visible = false">取消</el-button>
                <el-button :loading="buttonLoading"  type="primary" @click="save()">提交</el-button>
            </div>
        </template>
    </el-dialog>
</template>


<script setup lang="ts">
import { addFollow, getFollow } from '@/api/customer/follow';
import {useDictCache} from '@/hooks/web/useDict'
import { listDetialByCodes } from "@/api/system/dict/";
import { listLiaison } from '@/api/customer/liaison';
// import SelectUser from '@/components/SelectOrg/SelectUser.vue'
import Upload from '@/components/FileUpload/upload.vue'
import CreateQuickTask from '@/components/common/createQuickTask.vue';
import useUserStore from "@/store/modules/user";
import { noticeEventStore } from '@/store/modules/noticeEvent'
import { listTask } from '@/api/task';
import request from '@/utils/request';
import moment from "moment";
import { subjectRecordList,subjectRecordClick } from '@/api/emails'
import ckeditor from '@/components/ckeditor/index.vue'
const userNoticeEventStore = noticeEventStore()
const { queryDictDetailByCodes } = useDictCache(['customer_status', 'follow_up_type', 'sales_phase', 'task_remind_type', 'clue_status', 'task_mark_tag', 'task_priority_grade', 'task_remind_mode', 'business_stage','objective_value','in_out_mark'])
queryDictDetailByCodes()
    const visible = ref<Boolean>(false)
    const pageType = ref()
const followId = ref()

    const dictData: any = reactive({
        businessData: []
    })
    const getContact = ()=>{
        listDetialByCodes(['work_data_group']).then((res => {
            if(res.success) {
                dictData.businessData = res.result['work_data_group'].filter(item=>item.label=='商机'||item.label=='订单')
            }
        }))
    }
    const changeTask = ref(true)
    const changeType = ref()
    const pageResourceType = ref()
    const pageResourceTypeId = ref()
    const openData = ref()
    const open = async (data:any) => {
        reset()
        openData.value = data
        pageResourceType.value = data.resourceType
        pageResourceTypeId.value = data.resourceTypeId
        pageType.value = data.type?data.type:'add'
        changeType.value = data.changeType
        if(data.type=='edit'){
            followId.value = data.id
            await getLiaison(data.customerId)
            await followDetail(followId.value)
        }else{
            ruleFormRef.value?.resetFields();
            ruleForm.value.customerId = data.customerId?data.customerId:''
            ruleForm.value.customerName = data.customerName?data.customerName:data.resourceName
            ruleForm.value.resourceType = data.resourceType+''?data.resourceType+'':''
            ruleForm.value.resourceTypeId = data.resourceTypeId+''?data.resourceTypeId+'':''
            ruleForm.value.resourceName = data.resourceName?data.resourceName:''
            // ruleForm.value.resourceStageName = data.resourceStageName?data.resourceStageName:''
            ruleForm.value.resourceStageDictValue = data.resourceStageDictValue?data.resourceStageDictValue:''
            ruleForm.value.customerForm = data.customerForm?data.customerForm:''
            ruleForm.value.taskId = data.taskId
            ruleForm.value.subject = data.taskId?data.taskName:''
            ruleForm.value.dictCode = (data.resourceType=='10'||data.resourceType=='20')?'customer_status':data.resourceType=='11'?'clue_status':data.resourceType=='30'?'business_stage':''
            ruleForm.value.followUpTime = moment().format('YYYY-MM-DD HH:mm:ss')
            getContact()
            changeRule(data.resourceType)
            getTask()
        }
        if(data.resourceType!='11'){
            if(data.type!='edit'){
                await getLiaison(data.customerId)
                ruleForm.value.liaisonIdList = data.resourceType=='20'?[data.resourceTypeId]:[]
            }
        }
        visible.value = true
    }

    const getContent = (val: string) => {
        ruleForm.value.content = val
    }
    const customerResourceType = ref()
    const CustomerResourceTypeId = ref()

    const linkWorkData = ref<DictDataOption[] | null>([])
    const typeList = ref([])
    const loading = ref(false)
    const dialogLoading = ref(false)
    const changeBusiness = (val: string) => {
        if(val){
            CustomerResourceTypeId.value = undefined
            ruleForm.value.resourceTypeId = undefined
            ruleForm.value.resourceStageDictValue = '' //客户关联业务 置空商机或订单状态
            ruleForm.value.dictCode = val=='30'?'business_stage':''
            let obj: { extField: string } = dictData.businessData.find((a: { value: string }) => a.value == val)
            if(!obj.extField) return
            let extField =  JSON.parse(obj.extField)
            ruleForm.value.resourceType = val
            let params: any = { pageIndex: 1, pageSize: 999999, customerId:ruleForm.value.customerId, commonScope: 1, commonScopeType: val }
            loading.value = true
            request({
                url: extField.requesUrl,
                method: extField.method,
                data: params
            }).then(res => {
                if(res.success) {
                    typeList.value = res.result.records
                    linkWorkData.value = (res.result.records || []).map((item: any) => {
                        let data = { label: item[extField.fieldKey.nameKey], value: item[extField.fieldKey.idKey] }
                        return data
                    })
                }
            }).finally(() => {
                loading.value = false
            })
        }else{
            CustomerResourceTypeId.value = ''
            ruleForm.value.resourceType = pageResourceType.value
            ruleForm.value.resourceTypeId = pageResourceTypeId.value
            linkWorkData.value = []
            ruleForm.value.dictCode = 'customer_status'
            ruleForm.value.resourceStageDictValue = openData.value.resourceStageDictValue
        }

    }
    const changeBusinessId = (val)=>{
        ruleForm.value.resourceTypeId = val
        if(val){
            if(ruleForm.value.resourceType =='30'){
                let current = typeList.value.filter(item=>item.id== val)
                ruleForm.value.resourceStageDictValue = current[0].stage
            }
        }
    }

    const changeRule = (type)=>{
        if(type=='11'){
            rules.value.resourceStageDictValue[0].message='请选择线索状态'
        }
        if(type=='30'){
            rules.value.resourceStageDictValue[0].message='请选择商机阶段'
        }
    }
    const fileList = ref([])
    const followDetail = async (id:any) =>{
        dialogLoading.value = true
        await getFollow(id).then(res => {
            dialogLoading.value = false
            if (res.success) {
                Object.assign(ruleForm.value,res.result)
                ruleForm.value.remindUserIdsTemp = ruleForm.value.remindUserIds?ruleForm.value.remindUserIds.split(','):[]
                ruleForm.value.inOutMark = ruleForm.value.inOutMark+''
                ruleForm.value.resourceTypeId = ruleForm.value.resourceTypeId+''
                fileList.value = res.result.resourceList
                nextTick(() => {
                    ruleForm.value.content = res.result.content
                })
                if(ruleForm.value.taskId){
                    changeTask.value = false
                }
                getTask()
                if(ruleForm.value.resourceType=='10'){
                    getContact()
                    changeType.value = true
                }
                changeRule(ruleForm.value.resourceType)
            }
        })
    }

    const querySearch = (queryString, cb) => {
        subjectRecordList({ clickType: 2, title: queryString }).then(res => {
            if(res.success) {
                let subjectList = res.result.map(item => {
                    return { value: item.title, dataId: item.dataId }
                })
                cb(subjectList);
            }
        })
    }
    const subjectSelect = (item) => {
        subjectRecordClick({ clickType: 2, dataId: item.dataId })
    }

    const buttonLoading = ref(false);
    // 新建跟进
    interface RuleForm {
        dictCode:any,
        customerId:any,
        customerName:any,
        customerForm:any,
        resourceType:string,
        resourceTypeId:any,
        resourceName:string,
        resourceStageName:string,
        resourceStageDictValue:any,
        content: string,
        // customerId: any,
        followUpMemberId: any,
        followUpTime: string,
        followUpTypeValue: string,
        id: any,
        liaisonIdList: any,
        remindUserIds: string,
        remindUserIdsTemp: (string | number)[],
        setTask:boolean,
        resourceIdList:string[] | number[],
        task:{
            taskBeginTime:string,
            taskContent:string,
            ownerBy:string,
            remindType:string,
            remindModels:any,
            isCreateTask: boolean,
            objectiveValue:any,
        },
        taskId?: string
        objectiveValue:any,
        inOutMark:any,
        subject?: string,
        taskContent?: string,
    }
    const formSize = ref('default')
const ruleFormRef = ref<ElFormInstance>()
const initForm: RuleForm = {
    dictCode:'',
    customerId: '',
    customerName: '',
    resourceType: '',
    resourceTypeId: '',
    resourceName: '',
    resourceStageName: '',
    resourceStageDictValue: '',
    content: '',
    // customerId:customerId?customerId:'',
    followUpMemberId: null,
    followUpTime: '',
    followUpTypeValue: '',
    id: null,
    liaisonIdList: null,
    remindUserIds: '',
    remindUserIdsTemp: [],
    setTask: true,
    task: {
        taskBeginTime: '',
        taskContent: '',
        ownerBy: '',
        remindType: '',
        remindModels: ['site'],
        isCreateTask: false,
        objectiveValue:'',
    },
    taskId: undefined,
    resourceIdList: [],
    objectiveValue:undefined,
    inOutMark:undefined,
    subject:undefined,
    customerForm:undefined,
}
const ruleForm = ref<RuleForm>({ ...initForm })

const rules = ref({
    subject: [
        { required: true, message: '请输入跟进主题', trigger: 'change' },
    ],
    followUpTypeValue: [
        { required: true, message: '请选择跟进方式', trigger: 'change' },
    ],
    followUpTime: [
        { required: true, message: '请选择本次跟进时间', trigger: 'change' },
    ],
    content: [
        { required: true, message: '请填写本次跟进内容', trigger: 'blur' },
    ],
    objectiveValue: [
        { required: true, message: '请选择本次跟进目的', trigger: 'change' },
    ],
    inOutMark: [
        { required: true, message: '请选择本次跟进方向', trigger: 'change' },
    ],
    customerId: [
        { required: true, message: '请选择跟进客户', trigger: 'blur' },
    ],
    resourceStageDictValue: [
        { required: true, message: ruleForm.value.resourceType == '30' ? '请选择商机阶段' : '请选择客户状态', trigger: 'change' },
    ],
    liaisonIdList: [
        { required: true, message: '请选择联系人', trigger: 'change' },
    ],
    'task.taskBeginTime': [
        { required: true, message: '请选择下次跟进时间', trigger: 'blur' },
    ],
    'task.taskContent': [
        { required: true, message: '请填写下次任务主题', trigger: 'blur' },
    ],
    'task.objectiveValue': [
        { required: true, message: '请选择下次任务目的', trigger: 'change' },
    ],
    'task.remindType': [
        { required: true, message: "任务提醒不能为空", trigger: "change" }
    ],
    'task.ownerBy': [
        { required: true, message: '请选择跟进人员', trigger: 'change' },
    ],
})


const disabledDates = (time:Date) => {
    // 选择今天以及今天之前的日期
    return time.getTime() > Date.now() // 如果后面-8.64e7就是不可以选择今天的
}

const reset = () => {
    customerResourceType.value = undefined
    CustomerResourceTypeId.value = undefined // 置空关联业务
    fileList.value = [] //置空附件
    ruleForm.value = { ...initForm };
}

    const remindUserIds = ref([])
    const selectsUser = (data: any) => {
        ruleForm.value.remindUserIds = data.map(item=>item.id.toString()).join(',')
    }

    const liaisonOption = ref([])
    const getLiaison = (customerId: string) => {
        listLiaison({ pageIndex: 1, pageSize: 999999, customerId }).then(res => {
            if(res.success) {
                nextTick(() => {
                    liaisonOption.value = res.result.records.map((item: { name: string, id: number }) => {
                        let obj = { label: item.name, value: item.id }
                        return obj
                    })
                })
            }
        })
    }

    const taskList = ref([])
    const taskListAll= ref([])
    const getTask = () => {
        listTask({ pageIndex: 1, pageSize: 999999, resourceType: ruleForm.value.resourceType,resourceTypeId: ruleForm.value.resourceTypeId,taskStatusList:[0,3,4],commonScope: 1, commonScopeType: ruleForm.value.resourceType }).then(res => {
            if(res.success) {
                taskListAll.value = res.result.records
                taskList.value = res.result.records.map((item: { taskContent: any, id: any }) => {
                    let obj = { label: item.taskContent, value: item.id }
                    return obj
                })
            }
        })
    }
    const gerTaskValue = (val)=>{
        let currentTask:any = taskListAll.value.filter(item=>item.id == val)
        console.log(currentTask)
        ruleForm.value.followUpTime = currentTask[0].taskBeginTime
        ruleForm.value.subject = currentTask[0].taskContent
        ruleForm.value.objectiveValue = currentTask[0].objectiveValue
        if(changeType.value){
            if(currentTask[0].resourceType=='30'||currentTask[0].resourceType=='40'){
                customerResourceType.value = currentTask[0].resourceType
                changeBusiness(currentTask[0].resourceType)
                ruleForm.value.resourceTypeId = currentTask[0].resourceTypeId
                CustomerResourceTypeId.value = currentTask[0].resourceTypeId
                if(currentTask[0].resourceType=='30'){
                    ruleForm.value.resourceStageDictValue = currentTask[0].resourceObject.stage
                }
            }
        }

        console.log(ruleForm.value)
    }

    /** 保存按钮 */
    const save = () => {
        if(customerResourceType.value&&!CustomerResourceTypeId.value){
            ElMessage.error("请选择关联的"+customerResourceType.value=='30'?'商机业务':'订单业务');
            return false
        }
        ruleFormRef.value?.validate(async (valid: boolean) => {
            if (valid) {
                buttonLoading.value = true;
                await addFollow(ruleForm.value).finally(() => buttonLoading.value = false);
                let text = pageType.value=='add'?'新建':'编辑'
                ElMessage.success(text+"跟进成功");
                visible.value = false
                ruleFormRef.value?.resetFields();
                userNoticeEventStore.noticeFllowEvent()
                reset()

            }
        });
    }



    defineExpose({
        open
    })


</script>
<style lang="scss" scoped>
.business-item{
    :deep(.el-form-item__content){
        display: flex;
        column-gap: 0;
        .el-select{
            flex:1
        }
        .el-autocomplete{
            flex: 2
        }
    }
}
</style>
