<template>
    <el-card shadow="never" class="list-card">

        <template #header>
            <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="customerName">
                                <el-input v-model="queryParams.customerName" placeholder="搜索客户" clearable
                                    @keyup.enter="handleQuery" prefix-icon="Search" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="4">
                            <el-form-item prop="title">
                                <el-input v-model="queryParams.title" placeholder="搜索标题" clearable
                                    @keyup.enter="handleQuery" prefix-icon="Search" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="4" v-if="props.stage != '4'">
                            <el-form-item prop="salesPhaseDictValue">
                                <SelectDict v-model="queryParams.stage" placeholder="销售阶段" dictCode="business_stage">
                                </SelectDict>
                            </el-form-item>
                        </el-col>
                        <el-col :span="4">
                            <el-form-item prop="continent">
                                <el-cascader style="width: 100%" placeholder="区域名称" filterable :options="region"
                                    v-model="regionValue" clearable @change="getRegion" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="4" v-if='showAll || props.stage == "4"'>
                            <el-form-item prop="sourcesOfBusinessDictValue">
                                <SelectDict v-model="queryParams.sourcesOfBusinessDictValue" placeholder="商机来源"
                                    dictCode="sources_of_business"></SelectDict>
                            </el-form-item>
                        </el-col>
                        <el-col :span="4" v-if='showAll'>
                            <el-form-item prop="transactionProbabilityDictValue">
                                <SelectDict v-model="queryParams.transactionProbabilityDictValue" placeholder="成交机率"
                                    dictCode="transaction_probability"></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="expectedSigningDate">
                                <el-date-picker clearable v-model="queryParams.expectedSigningDate" type="date"
                                    value-format="YYYY-MM-DD" placeholder="预计签单日期" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="4">
                            <el-form-item prop="businessTypeDictValue">
                                <SelectDict v-model="queryParams.businessTypeDictValue" placeholder="商机类型"
                                    dictCode="business_type"></SelectDict>
                            </el-form-item>
                        </el-col>
                        <el-col :span="4">
                            <el-form-item prop="ownerBy">
                                <SelectUser v-model.lazy="queryParams.ownerByIds" multiple placeholder="归属人员">
                                </SelectUser>
                            </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>
        <!--        <span>fdsafdsafffffffffffff</span>-->
        <!--        <svg class="icon" aria-hidden="true">-->
        <!--            <use xlink:href="#icon-youjianfujian"></use>-->
        <!--        </svg>-->
        <!--        <svg-icon icon-class="liushishangji" />-->
        <!--        <i class="iconfont icon-youdangdaichuli"></i>-->
        <!--        <el-icon>-->
        <!--            <i class="iconfont icon-youdangdaichuli"></i>-->
        <!--        </el-icon>-->
        <Table ref="allBusinessTable" :tableParams="tableParams" :btnRole="leftBtn" @handleAdd="handleAdd"
            @handleEdit="handleUpdate" @selectionChange="handleSelectionChange">
            <template #left>
                <el-button v-hasPermi="[`business:${props.perPrefix}:zysjlist`]" @click="turnBus">转移商机</el-button>
                <el-button v-hasPermi="[`business:${props.perPrefix}:tjxzlist`]"
                    @click="addCollaborateUsers">添加协作</el-button>
                <el-button v-hasPermi="[`business:${props.perPrefix}:xjrwlist`]" @click="addTask">新建任务</el-button>
            </template>

        </Table>
    </el-card>


    <createTask :isCorrelation="false" @refresh="handleQuery" ref="createTaskRef"></createTask>
    <AddFollow ref="addFollow"></AddFollow>

    <addCollaborate @onOk="handleQuery" ref="addCollaborateRef"></addCollaborate>
    <transferClue @refresh="handleQuery" ref="turnBusRef"></transferClue>
</template>

<script setup name="AllBusiness" lang="ts">
import {
    listAllBusiness,
    getById,
    delAllBusiness,
    addAllBusiness,
    updateAllBusiness
} from '@/api/business/allBusiness';
import transferClue from '@/components/common/transferClue.vue'
// import correlationSelect from '@/components/common/correlationSelect.vue'
import addCollaborate from '@/components/common/addCollaborate.vue'
import turnBussnese from '@/modules/sales/views/business/component/TurnBus.vue'
import createTask from '@/components/common/createTask.vue'
import AddFollow from '@/components/Follow/add.vue'

import {AllBusinessVO, AllBusinessQuery, AllBusinessForm} from '@/api/business/allBusiness/types';
import auth from '@/plugins/auth'
import Table from '@/components/Table/index.vue'
import {tableTypes} from '@/components/Table/types'
import {listCustomer} from "@/api/customer";
import {CustomerVO} from "@/api/customer/types";
import {region} from '@/utils/region';

import {useDictCache} from '@/hooks/web/useDict'

const {proxy} = getCurrentInstance() as ComponentInternalInstance;
const {queryDictDetailByCodes} = useDictCache(['sales_phase', 'business_type', 'transaction_probability', 'sources_of_business', 'task_remind_type', 'task_remind_mode', 'business_stage'])
queryDictDetailByCodes()
const addCollaborateRef = ref()
//创建任务
const createTaskRef = ref()
//转移商机
const turnBusRef = ref()
const router = useRouter();

const addCollaborateUsers = async () => {
    if (ids.value.length <= 0) {
        ElMessage.error('请选择需要添加协作的数据')
        return
    }
    addCollaborateRef.value.open({
        resourceType: 30,
        resourceIdList: ids.value
    })
}
const turnBus = async () => {
    if (ids.value.length <= 0) {
        ElMessage.error('请选择需要转移的数据')
        return
    }
    turnBusRef.value.open({
        resourceType: 30,
        typeName: '商机',
        idList: ids,
    })
}

const addTask = async () => {
    if (ids.value.length <= 0) {
        ElMessage.error('请选择需要添加任务的数据')
        return
    }
    createTaskRef.value.open({
        type: 'add',
        obj: {
            resourceType: '30',
            resourceTypeId: ids.value
        }
    })
}


const customerOption = ref([])
const getCustomerData = () => {
    listCustomer({pageIndex: 1, pageSize: 999999}).then(res => {
        if (res.success) {
            customerOption.value = res.result.records.map((item: { customerName: string, id: number }) => {
                let obj = {label: item.customerName, value: item.id}
                return obj
            })
        }
    })
}

const allBusinessList = ref<AllBusinessVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);

const props = defineProps({
    leftBtn: {
        type: Array,
        required: true
    },
    perPrefix: {
        type: String,
        required: true
    },
    stage: {
        type: String,
        required: true
    },
    queryRangeType: {
        type: [Number, String],
        required: true
    },
    isLoss:{
        type: Boolean,
        required: true

    }
})
const leftBtn = ref([
    { type: 'add', hasPermi: `business:${props.perPrefix}:add` },
    {type: 'edit', hasPermi: `business:${props.perPrefix}:edit`},
    {type: 'remove', hasPermi: `business:${props.perPrefix}:remove`},
    {type: 'import', hasPermi: `business:${props.perPrefix}:import`},
    {type: 'export', hasPermi: `business:${props.perPrefix}:export`}
])

const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const showAll = ref(false)

const queryFormRef = ref<ElFormInstance>();
const allBusinessFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
    visible: false,
    title: ''
});

const route = useRoute();
const detailCus = async (column: AllBusinessVO) => {
    router.pushTarget('/customer/customerDetail?id=' + column.customerId + '&from=' + props.perPrefix)
}
const detail = async (id: string | number) => {
    router.pushTarget('/business_opportunity/detail?id=' + id + '&type=detail&from=' + props.perPrefix + '&scopMenuId=' + router.currentRoute.value?.meta?.menuId)
}

const tableParams = reactive<tableTypes<AllBusinessQuery, AllBusinessVO>>({
    cloumnCode: props.perPrefix,
    tableColumn: [
        {
            show: true, label: '商机标题', prop: 'title', sortable: true, render: ({column}: { column: AllBusinessVO }) => {
                return h('span', {
                    class: 'link',
                    style: {cursor: 'pointer'}, onClick: () => {
                        detail(column.id)
                    }
                }, column.title)
            }
        },
        {
            show: true, label: '关联客户', prop: 'title', sortable: false, render: ({column}: { column: AllBusinessVO }) => {
                return h('span', {
                    class: 'link',
                    style: {cursor: 'pointer'}, onClick: () => {
                        detailCus(column)
                    }
                }, column.customerName)
            }
        },
        // {show: true, label: '关联客户', prop: 'customerName', sortable: false},
        {show: true, label: '商机阶段', prop: 'stageName', sortable: false},
        // {show: true, label: '报价记录', prop: 'offerRecord', sortable: false},
        {show: true, label: '预计销售金额(￥)', prop: 'estimatedSalesAmount', sortable: true, toFixed: true},
        {show: true, label: '报价金额(￥)', prop: 'offerAmount', sortable: false, toFixed: true},
        {show: true, label: '最后跟进', prop: 'lastFollowUpTime', sortable: false},
        {show: true, label: '未跟进天数', prop: 'notFollowedDays', sortable: false},
        {show: false, label: '成交机率', prop: 'stransactionProbabilityName', sortable: true},
        {show: false, label: '商机来源', prop: 'sourcesOfBusinessName', sortable: false},
        {show: false, label: '获取日期', prop: 'getedDate', sortable: true},
        {show: false, label: '备注信息', prop: 'remark', sortable: false},
        {show: props.isLoss, label: '流失原因', prop: 'lossReasonName', sortable: false},
        {show: false, label: '创建时间', prop: 'createTime', sortable: true},
        {show: false, label: '修改时间', prop: 'updateTime', sortable: false},
        {
            show: true,
            label: '操作',
            prop: 'operation',
            disabledMove: true,
            render: ({column}: { column: AllBusinessVO }) => {
                return [
                    auth.hasPermi(`business:${props.perPrefix}:flowUp`) ? h(ElButton, {
                        link: true, type: 'primary', onClick: () => {
                            openFllow(column)
                        }
                    }, '跟进') : '',
                    // auth.hasPermi(`business:${props.perPrefix}:top`) ? h(ElButton, {
                    //     link: true, type: 'primary', onClick: () => {
                    //
                    //     }
                    // }, '置顶') : '',
                ]
            }
        },
    ],
    keyId: 'id',
    menuId: router.currentRoute.value?.meta?.menuId,
    queryParams: {
        blurry: undefined,
        title: undefined,
        customerId: undefined,
        liaisonId: undefined,
        estimatedSalesAmount: undefined,
        expectedSigningDate: undefined,
        salesPhaseDictValue: undefined,
        businessTypeDictValue: undefined,
        transactionProbabilityDictValue: undefined,
        sourcesOfBusinessDictValue: undefined,
        getedDate: undefined,
        isDelete: undefined,
        enabled: undefined,
        ownerBy: undefined,
        sort: undefined,
        queryRangeType: props.queryRangeType,
        stage: props.stage,
        hasLoss: props.isLoss ? 1 : undefined,
        ownerByIds: [],
        customerName:undefined,
        country:undefined,
    },
    listFn: listAllBusiness,
    delFn: delAllBusiness,
    importCode: 'IMPORT_BUSINESS_EXCEL',
    exportCode: 'EXPORT_BUSINESS_EXCEL',
    commonQueryOrderBy: 'getedDate'
})
const regionValue = ref([])
const getRegion = (value) => {
    tableParams.queryParams.country = value?value[1]:''
}
// @queryRangeType(value = "归属分类(QueryRangeTypeEnum)（0全部客户、10：我的客户、20:我发起的、30：下属客户、40我协作的、50：下属协作的，70：重点）")
const addFollow = ref()
const openFllow = (column: AllBusinessVO) => {
    let query = {
        type: 'add',
        customerId: column.customerId,
        customerName: column.customerName,
        resourceType: 30,
        resourceTypeId: column.id,
        resourceName: column.title,
        resourceStageName: column?.stageName,//阶段
        resourceStageDictValue: column?.stage

    }
    console.log(query)
    addFollow.value.open(query)
}
const initFormData: AllBusinessForm = {
    id: undefined,
    title: undefined,
    customerId: undefined,
    liaisonId: undefined,
    estimatedSalesAmount: undefined,
    expectedSigningDate: undefined,
    salesPhaseDictValue: undefined,
    businessTypeDictValue: undefined,
    transactionProbabilityDictValue: undefined,
    sourcesOfBusinessDictValue: undefined,
    getedDate: undefined,
    remark: undefined,
    isDelete: undefined,
    enabled: undefined,
    ownerBy: undefined,
    sort: undefined,
    isCreateTask: undefined,
    task: {
        taskBeginTime: '',
        taskContent: '',
        remindModels: [],
        remindType: undefined,
        ownerBy: undefined
    }
}
const data = reactive<PageData<AllBusinessForm, AllBusinessQuery>>({
    form: {...initFormData},
    rules: {
        id: [
            {required: true, message: "商机主键不能为空", trigger: "blur"}
        ],
        title: [
            {required: true, message: "商机标题不能为空", trigger: "blur"}
        ],
        customerId: [
            { required: true, message: "关联客户id不能为空", trigger: "change" }
        ],
        liaisonId: [
            { required: true, message: "主要联系人id不能为空", trigger: "change" }
        ],
        estimatedSalesAmount: [
            {required: true, message: "预计销售金额不能为空", type: 'string', trigger: "change"}
        ],
        expectedSigningDate: [
            {required: true, message: "预计签单日期不能为空", trigger: "change"}
        ],
        salesPhaseDictValue: [
            {required: true, message: "销售阶段不能为空", trigger: "change"}
        ],
        businessTypeDictValue: [
            {required: true, message: "商机类型不能为空", trigger: "change"}
        ],
        transactionProbabilityDictValue: [
            {required: true, message: "成交机率不能为空", trigger: "change"}
        ],
        sourcesOfBusinessDictValue: [
            {required: true, message: "商机来源不能为空", trigger: "change"}
        ],
        getedDate: [
            {required: true, message: "获取日期不能为空", trigger: "blur"}
        ],
        remark: [
            {required: true, message: "备注信息不能为空", trigger: "blur"}
        ],

        ownerBy: [
            {required: true, message: "拥有者不能为空", type: 'string', trigger: "blur, change"}
        ],
        'task.taskBeginTime': [
            {required: true, message: "拥有者不能为空", type: 'date', trigger: "blur, change"}
        ],
        'task.ownerBy': [
            {required: true, message: "拥有者不能为空", trigger: "blur, change"}
        ],

    }
});

const {form, rules} = toRefs(data);

const {queryParams} = toRefs(tableParams);
/** 取消按钮 */
const cancel = () => {
    reset();
    dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
    form.value = {...initFormData};
    allBusinessFormRef.value?.resetFields();
}

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

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

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

/** 新增按钮操作 */
const handleAdd = () => {
    router.push('./addbus')
}

const handleUpdate = (row) => {

    router.push(`./addbus?id=${row.id}`)
}

const getList = () => {
    allBusinessTable.value.getData()
}


onMounted(() => {
    getCustomerData()
});
</script>
