<template>
    <el-card shadow="never" class="list-card">
        <template #header>
            <div class="top_nav flex" v-if="queryRangeType==0">
                <template v-for="(item,index) in customerNav">
                    <div class="nav_list" v-if="item.show" @click="changeNav(index,item.value, item.perPrefix)">{{
                        item.label }}<i :class="navIndex==index?'on':''"></i></div>
                </template>

            </div>
            <div class="search table_area" v-show="showSearch">
                <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
                    <el-row :gutter="16">
                        <el-col :span="4">
                            <el-form-item prop="blurry">
                                <el-input v-model="queryParams.blurry" placeholder="搜索客户信息" clearable
                                    prefix-icon="Search" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="4">
                            <el-form-item prop="liaisonName">
                                <el-input v-model="queryParams.liaisonName" placeholder="搜索联系人" clearable
                                    prefix-icon="Search" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="4">
                            <el-form-item prop="customerStatusDictValue">
                                <SelectDict v-model="queryParams.customerStatusDictValue" placeholder="客户状态"
                                    dictCode="customer_status"></SelectDict>
                            </el-form-item>
                        </el-col>
                        <el-col :span="4">
                            <el-form-item prop="continent">
                                <el-cascader style="width: 100%" placeholder="区域名称" :options="region"
                                    v-model="regionValue" clearable filterable @change="getRegion" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="4" v-if='showAll'>
                            <el-form-item prop="customerTypeDictValue">
                                <SelectDict v-model="queryParams.customerTypeDictValue" placeholder="客户类型"
                                    dictCode="customer_type"></SelectDict>
                            </el-form-item>
                        </el-col>
                        <el-col :span="4" v-if='showAll'>
                            <el-form-item prop="customerLevelDictValue">
                                <SelectDict v-model="queryParams.customerLevelDictValue" placeholder="客户等级"
                                    dictCode="customer_level"></SelectDict>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6" v-if='!showAll'>
                            <el-form-item>
                                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                                <el-button type="primary" icon="ArrowDown" text @click="showAll=true">展开检索</el-button>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="16" v-if='showAll'>
                        <el-col :span="4">
                            <el-form-item prop="ownerByIds">
                                <SelectUser multiple v-model="queryParams.ownerByIds" placeholder="归属人员"></SelectUser>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item>
                                <el-date-picker v-model="daterange" type="datetimerange" range-separator="-"
                                    start-placeholder="最后跟进" end-placeholder="最后跟进" value-format="YYYY-MM-DD HH:mm:ss"
                                    @change="getDate" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item>
                                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                                <el-button type="primary" icon="ArrowUp" text @click="showAll=false">收起检索</el-button>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
        </template>

        <Table ref="CustomerTable" :tableParams="tableParams" :btnRole="btnRole" @handleAdd="handleAdd('add')"
            @handleEdit="handleAdd('edit', $event)" @selectionChange="handleSelectionChange">
            <template #left>
                <template v-for="item in leftBtn">
                    <el-button @click="openDialog(item.value)" v-if="item.show" :type="item.value=='check'?'danger':''">
                        {{ item.label }}
                    </el-button>
                </template>
            </template>
            <template #right>
                <el-checkbox v-model="followStyle" label="跟进模式" @change='setFollow'></el-checkbox>
                <el-tooltip class="box-item" effect="dark" content="选择跟进模式后，列表将展示有最新邮件和待跟进的客户，且客户详情切换至跟进面板状态"
                    placement="top">
                    <el-icon style='margin-right: 10px'>
                        <QuestionFilled />
                    </el-icon>
                </el-tooltip>
            </template>
        </Table>
    </el-card>

    <!-- 左侧按钮弹窗 -->
    <component v-bind="componentProps" :is="dialogComponent" :ref="($event: any) => setItemRef($event)"
        @refresh="handleQuery"></component>
</template>

<script setup name="Customer" lang="ts">
import {Search} from '@element-plus/icons-vue'
import {useDictCache} from '@/hooks/web/useDict'
import {listCustomer, delCustomer} from '@/api/customer';
import {CustomerVO, CustomerQuery} from '@/api/customer/types';
import auth from '@/plugins/auth'
import Table from '@/components/Table/index.vue'
import {tableTypes} from '@/components/Table/types'
import InSeas from '@/components/common/inSeas.vue'
import CreateTask from '@/components/common/createTask.vue'
import TransferClue from '@/components/common/transferClue.vue'
import Merge from '@/components/common/merge.vue'
import BulkEdit from '@/components/common/bulkEdit.vue'
import AddFollow from '@/components/Follow/add.vue'
import CustomerCheck from '@/components/common/customerCheck.vue'
import {region} from '@/utils/region';

const {queryDictDetailByCodes} = useDictCache(['customer_status', 'customer_type', 'customer_level'])
queryDictDetailByCodes()

const {proxy} = getCurrentInstance() as ComponentInternalInstance;

const props = defineProps({
    perPrefix: {
        type: String,
        required: true
    },
    queryRangeType: {
        type: [Number,String]
    }
})
const router = useRouter();
const CustomerList = ref<CustomerVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const followStyle = ref(false)
const showAll = ref(false)

const daterange = ref('')
const getDate = (val: string[] | null) => {
    tableParams.queryParams.lastFollowUpBeginTime = val ? val[0] : ''
    tableParams.queryParams.lastFollowUpEndTime = val ? val[1] : ''
}

const perPrefix = ref<string>('customerFormAll')
perPrefix.value = props.perPrefix

const btnRole = ref([])
// 左侧按钮弹窗
let leftBtn = ref([])
const single = ref(true);
const multiple = ref(true);

const tableParams = reactive<tableTypes<CustomerQuery, CustomerVO>>({
    cloumnCode:props.perPrefix,
    tableColumn: [
        // {show: false, label: '客户主键', prop: 'id', sortable: false},
        // {show: false, label: '客户种类', prop: 'Customer', sortable: false},
        // {show: false, label: '是否从线索过来', prop: 'hasFromClue', sortable: false},
        // {show: false, label: '是否是公共线索/公海客户', prop: 'hasPublicCustomer', sortable: false},
        {show: true, label: '客户代码', prop: 'dataCode', sortable: true},
        {show: false, label: '所属大洲', prop: 'continent', sortable: true},
        {show: false, label: '所属国家', prop: 'country', sortable: true},
        {show: false, label: '客户归属', prop: 'ownerByName', sortable: false},
        {show: true, label: '企业网址', prop: 'customerCompany.website', sortable: false},
        {
            show: true,
            label: '客户名称',
            prop: 'customerName',
            width:'150',
            sortable: true,
            render: ({column}: { column: CustomerVO }) => {
                return [
                    h('div', {
                        class: 'link', onClick: async () => {
                            if(followStyle.value){
                                router.pushTarget('/customer/followPanel?id=' + column.id+'&scopeMenuId='+router.currentRoute.value?.meta?.menuId+'&resourceType=10&blurry='+tableParams.queryParams.blurry+'&customerForm=10&customerStatusDictValue='+tableParams.queryParams.customerStatusDictValue+'&customerTypeDictValue='+tableParams.queryParams.customerTypeDictValue+'&customerLevelDictValue='+tableParams.queryParams.customerLevelDictValue+'&lastFollowUpTime='+tableParams.queryParams.lastFollowUpTime+'&queryRangeType='+tableParams.queryParams.queryRangeType+'&hasOrderForm='+tableParams.queryParams.hasOrderForm+'&hasPublicCustomer='+tableParams.queryParams.hasPublicCustomer+'&ownerByIds='+tableParams.queryParams.ownerByIds+'&hasFollowMode='+tableParams.queryParams.hasFollowMode+'&customerName='+tableParams.queryParams.customerName+'&liaisonName='+tableParams.queryParams.liaisonName+'&country='+tableParams.queryParams.country+'&preNextScopeMenuId='+router.currentRoute.value?.meta?.menuId)
                            }else{
                                router.pushTarget('/customer/customerDetail?id=' + column.id+'&scopeMenuId='+router.currentRoute.value?.meta?.menuId+'&resourceType=10&blurry='+tableParams.queryParams.blurry+'&customerForm=10&customerStatusDictValue='+tableParams.queryParams.customerStatusDictValue+'&customerTypeDictValue='+tableParams.queryParams.customerTypeDictValue+'&customerLevelDictValue='+tableParams.queryParams.customerLevelDictValue+'&lastFollowUpTime='+tableParams.queryParams.lastFollowUpTime+'&queryRangeType='+tableParams.queryParams.queryRangeType+'&hasOrderForm='+tableParams.queryParams.hasOrderForm+'&hasPublicCustomer='+tableParams.queryParams.hasPublicCustomer+'&ownerByIds='+tableParams.queryParams.ownerByIds+'&hasFollowMode='+tableParams.queryParams.hasFollowMode+'&customerName='+tableParams.queryParams.customerName+'&liaisonName='+tableParams.queryParams.liaisonName+'&country='+tableParams.queryParams.country+'&preNextScopeMenuId='+router.currentRoute.value?.meta?.menuId)
                            }
                        }
                    }, column.customerName),
                ]
            }
        },
        {show: false, label: '意向产品id', prop: 'intendedProductsIds', sortable: false},
        {show: false, label: '意向产品', prop: 'intendedProductsNames', sortable: false},
        {show: true, label: '客户状态', prop: 'customerStatusName', sortable: false},
        {show: false, label: '客户来源', prop: 'customerSourceName', sortable: false},
        {show: false, label: '客户类型', prop: 'customerTypeName', sortable: false},
        {show: true, label: '客户等级', prop: 'customerLevelName', sortable: false},
        {show: true, label: '首联系人', prop: 'liaison.name', sortable: false},
        {show: true, label: '邮箱', prop: 'liaison.email', sortable: false},
        {show: true, label: '最后跟进', prop: 'lastFollowUpTime', sortable: true},
        {show: true, label: '未跟进天数', prop: 'noFollowUpDate', sortable: true},
        {show: false, label: '客户信用等级', prop: 'customerCreditLevelName', sortable: false},
        {show: false, label: '客户经济性质', prop: 'customerEconomicNatureName', sortable: false},
        {show: false, label: '助记名称', prop: 'mnemonicName', sortable: false},
        {show: false, label: '备注信息', prop: 'remark', sortable: false},
        {show: false, label: '开户行', prop: 'openingBank', sortable: false},
        {show: false, label: '税号', prop: 'taxNumber', sortable: false},
        {show: false, label: '银行账号', prop: 'bankAccount', sortable: false},
        {show: false, label: '创建时间', prop: 'createTime', sortable: true},
        {show: false, label: '更新时间', prop: 'updateTime', sortable: false},
        // {show: false, label: '创建者', prop: 'createBy', sortable: false},
        // {show: false, label: '拥有者', prop: 'ownerByName', sortable: false},
        // {show: false, label: '更新者', prop: 'updateBy', sortable: false},
        // {show: false, label: '显示顺序', prop: 'sort', sortable: true},

        {
            show: true,
            label: '操作',
            width: 200,
            prop: 'operation',
            disabledMove: true,
            render: ({column}: { column: CustomerVO }) => {
                return [
                    auth.hasPermi(`customer:${perPrefix.value}:follow`) ? h(ElButton, {
                        link: true, type: 'primary', onClick: () => {
                            openDialog('follow', column)
                        }
                    }, () => '跟进') : '',
                    // h(ElButton, {
                    //     link: true, type: 'primary', onClick: async () => {
                    //         console.log(column)
                    //     }
                    // }, () => '置顶')
                ]
            }
        },
    ],
    queryParams: {
        blurry: '',
        customerForm: 10,
        customerStatusDictValue: '',
        customerTypeDictValue: '',
        customerLevelDictValue: '',
        lastFollowUpTime: '',
        queryRangeType: props.queryRangeType=='order'?0:props.queryRangeType,
        hasOrderForm:props.queryRangeType=='order'?1:'',
        hasPublicCustomer:0,
        ownerByIds:[],
        hasFollowMode:false,
        customerName:'',
        liaisonName:'',
        country:'',
    },
    listFn: listCustomer,
    delFn: delCustomer,
    keyId: 'id',
    menuId: router.currentRoute.value?.meta?.menuId,
    importCode: 'IMPORT_CUSTOM_EXCEL',
    exportCode: 'EXPORT_CUSTOM_EXCEL',
    importType: props.queryRangeType=='order'?'1':props.queryRangeType==60?'4':'0',
    commonQueryOrderBy: 'lastFollowUpTime',
    sortMethod: 'asc'
})

const {queryParams} = toRefs(tableParams);

const regionValue = ref([])
const getRegion = (value) => {
    tableParams.queryParams.country = value?value[1]:''
}

const CustomerTable = ref()
/** 搜索按钮操作 */
const handleQuery = () => {
    CustomerTable.value?.getData()
}

// 顶部客户类型切换
const customerNav = [
    {label: '全部客户', value: '0', perPrefix: 'customerFormAll', show: auth.hasPermi('customer:customerFormAll:list')},
    {label: '我的客户', value: '10', perPrefix: 'customerFormMine', show: auth.hasPermi('customer:customerFormMine:list')},
    {label: '下属客户', value: '30', perPrefix: 'customerFormSubordinate', show: auth.hasPermi('customer:customerFormSubordinate:list')},
    // {label: '重点客户', value: '60', perPrefix: 'cut_important', show: true},
    {label: '我协作的', value: '40', perPrefix: 'customerFormCollaborate', show: auth.hasPermi('customer:customerFormCollaborate:list')},
    {label: '下属协作的', value: '50', perPrefix: 'customerFormSC', show: auth.hasPermi('customer:customerFormSC:list')},
]
const navIndex = ref(0)
const changeNav = (index: number, val: string | number, perPrefixVal: string) => {
    navIndex.value = index
    tableParams.queryParams.queryRangeType = val
    perPrefix.value = perPrefixVal
    btnRole.value = [
        {type: 'add', hasPermi: `customer:${perPrefixVal}:add`},
        {type: 'edit', hasPermi: `customer:${perPrefixVal}:edit`},
        {type: 'remove', hasPermi: `customer:${perPrefixVal}:remove`},
        {type: 'import', hasPermi: `customer:${perPrefixVal}:import`},
        {type: 'export', hasPermi: `customer:${perPrefixVal}:export`}
    ]
    leftBtn.value = [
        {label: '新建任务', value: 'task', show: auth.hasPermi(`customer:${perPrefixVal}:xjrw`)},
        {label: '转移客户', value: 'transfer', show: auth.hasPermi(`customer:${perPrefixVal}:zykh`)},
        {label: '移入公海', value: 'inSeas', show: auth.hasPermi(`customer:${perPrefixVal}:yrgh`)},
        {label: '合并客户', value: 'merge', show: auth.hasPermi(`customer:${perPrefixVal}:hbkh`)},
        {label: '批量编辑', value: 'edit', show: auth.hasPermi(`customer:${perPrefixVal}:plbj`)},
        {label: '查重', value: 'check', show: auth.hasPermi(`customer:${perPrefixVal}:cc`)},
    ]
    if(index==1){
        followStyle.value = true
        tableParams.queryParams.hasFollowMode = true
    }else{
        followStyle.value = false
        tableParams.queryParams.hasFollowMode = false
    }
    handleQuery()
}
const value2 = ref('')
const type =  props.queryRangeType=='order'?0:props.queryRangeType
changeNav(0, type, props.perPrefix)

const setFollow  = (val)=>{
    tableParams.queryParams.hasFollowMode = val
    handleQuery()
}

const dialogComponent = shallowRef()
const dialogRef = ref()
const setItemRef = (el: any) => {
    if (el) {
        dialogRef.value = el
    }
}
const componentProps = shallowRef()
let propData = {}
const openDialog = (val: string, column?: any) => {
    switch (val) {
        case 'task': // 新建任务
            if (ids.value.length == 0) {
                ElMessage.error('请选择相对应的客户')
                return
            }
            componentProps.value = { isCorrelation: false }
            propData = {
                type:'add',
                obj: {
                    resourceType: '10',
                    resourceTypeIdls: ids.value
                }
            }
            dialogComponent.value = CreateTask
            break;
        case 'inSeas': // 移入公海
            if (ids.value.length == 0) {
                ElMessage.error('请选择需要移入公海的客户')
                return
            }
            propData = ids.value
            dialogComponent.value = InSeas
            break;
        case 'transfer': // 转移客户
            if (ids.value.length == 0) {
                ElMessage.error('请选择需要转移的客户')
                return
            }
            propData = {
                resourceType: '10',
                typeName: '客户',
                idList: ids.value
            }
            dialogComponent.value = TransferClue
            break;
        case 'merge': // 合并客户
            if (ids.value.length > 2) {
                ElMessage.error('仅可选择两位客户进行合并')
                return
            } else {
                dialogComponent.value = Merge
                propData = {
                    ids:ids.value,
                    querys:tableParams.queryParams,
                    selectedData: selectedData.value,
                    scopeMenuId:router.currentRoute.value?.meta?.menuId,
                }
            }
            break;
        case 'edit': // 批量编辑
            if (ids.value.length == 0) {
                ElMessage.error('请选择批量编辑的客户')
                return
            } else {
                dialogComponent.value = BulkEdit
                propData = {
                    ids:ids.value
                }
            }
            break;
        case 'follow': // 跟进
            dialogComponent.value = AddFollow
            propData = {
                type: 'add',
                customerId: column.id,
                resourceType: 10,
                resourceTypeId: column.id,
                resourceName: column.customerName,
                resourceStageName: column.customerStatusName,
                resourceStageDictValue: column.customerStatusDictValue,
                changeType:true,
            }
            break;
        case 'check': // 查重
            dialogComponent.value = CustomerCheck
            propData = {
                resourceType: 10,
            }
            break;
    }
    nextTick(() => {
        dialogRef.value.open(propData)
    })
}


const queryFormRef = ref<ElFormInstance>();

/** 重置按钮操作 */
const resetQuery = () => {
    regionValue.value = []
    tableParams.queryParams.country = ''
    queryFormRef.value?.resetFields();
    handleQuery();
}

/** 多选框选中数据 */
const selectedData = ref<CustomerVO[]>([])
const handleSelectionChange = (selection: CustomerVO[]) => {
    selectedData.value = selection
    ids.value = selection.map(item => item.id);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = (type: string, data?: CustomerVO) => {
    router.push('../customer/addCustomer?type=' + type + "&id=" + data?.id)
}
</script>

<style lang="scss" scoped>

</style>
