<template>
    <div class="app-container">
        <el-dialog :title="title" :visible.sync="dialogVisible" width="70%" :before-close="handleClose">
            <!-- 公告信息 -->
            <div class="detail-section">
                <h3 class="section-title">公告信息</h3>
                <el-form :model="formData" :rules="rules" ref="formRef" label-width="130px" size="small"
                    class="detail-form">
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="公告标题">
                                {{ formData.announcementTitle || '-' }}
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="公告类别">
                                {{ formData.announcementType || '-' }}
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="发布时间">
                                {{ formData.publishTime ? new Date(formData.publishTime).toLocaleString() : '-' }}
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="信息匹配词">
                                {{ formData.matchKeywords || '-' }}
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="是否有关">
                                <span class="bool-value"
                                    :class="{ true: formData.isRelevant === 1, false: formData.isRelevant === 0 }">
                                    {{ formData.isRelevant === 1 ? '是' : formData.isRelevant === 0 ? '否' : '-' }}
                                </span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="数据来源">
                                {{ formData.dataSource || '-' }}
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="公告地址">
                                <a v-if="formData.announcementUrl" :href="formData.announcementUrl" target="_blank"
                                    class="link-text">{{ formData.announcementUrl }}</a>
                                <span v-else>-</span>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="剑鱼地址">
                                <a v-if="formData.jianyuUrl" :href="formData.jianyuUrl" target="_blank"
                                    class="link-text">{{ formData.jianyuUrl }}</a>
                                <span v-else>-</span>
                            </el-form-item>
                        </el-col>
                    </el-row>

                </el-form>
            </div>

            <!-- 采购信息 -->
            <div class="detail-section">
                <h3 class="section-title">采购信息</h3>
                <el-form :model="formData" label-width="130px" size="small" class="detail-form">
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="采购单位">
                                {{ formData.purchaseUnit || '-' }}
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="最终使用客户">
                                {{ formData.finalUser || '-' }}
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="客户群">
                                {{ formData.customerGroup || '-' }}
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="预算（万元）">
                                {{ formData.budget || '-' }}
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="招标信息发布时间">
                                {{ formData.tenderInfoPublishTime ? new
                                    Date(formData.tenderInfoPublishTime).toLocaleString() : '-' }}
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="开标日期">
                                {{ formData.bidOpeningDate ? new Date(formData.bidOpeningDate).toLocaleString() : '-' }}
                            </el-form-item>
                        </el-col>
                    </el-row>

                </el-form>
            </div>

            <!-- 项目信息 -->
            <div class="detail-section">
                <h3 class="section-title">项目信息</h3>
                <el-form :model="formData" label-width="130px" size="small" class="detail-form">
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="项目编号">
                                {{ formData.projectCode || '-' }}
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="项目名称">
                                {{ formData.projectName || '-' }}
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="招标代理">
                                {{ formData.tenderAgent || '-' }}
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="招标代理联系电话">
                                {{ formData.tenderAgentPhone || '-' }}
                            </el-form-item>
                        </el-col>
                    </el-row>

                </el-form>
            </div>

            <!-- 扩展信息 -->
            <div class="detail-section">
                <h3 class="section-title">扩展信息</h3>
                <el-form :model="formData" label-width="130px" size="small" class="detail-form">
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="分公司">
                                {{ formData.branchCompany || '-' }}
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="分类">
                                {{ formData.category || '-' }}
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="20">
                        <!-- <el-col :span="12">
                            <el-form-item label="商机编号">
                                {{ formData.opportunityCode || '-' }}
                            </el-form-item>
                        </el-col> -->
                        <el-col :span="12">
                            <el-form-item label="是否知晓">
                                <span class="bool-value"
                                    :class="{ true: formData.isAware === 1, false: formData.isAware === 0 }">
                                    {{ formData.isAware === 1 ? '是' : formData.isAware === 0 ? '否' : '-' }}
                                </span>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="商机编号">
                                <div @click="handleSearchOpportunity" style="border: 1px solid #999999;
                                            border-radius: 5px;
                                            display: flex;
                                            align-items: center;
                                            padding: 0 10px;
                                            justify-content: space-between;">
                                    <span>{{ formData.opportunityCode || '-' }}</span>
                                    <i class="el-icon-search"></i>
                                </div>
                            </el-form-item>
                        </el-col>

                    </el-row>
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="是否参与" prop="isParticipate">
                                <el-select v-model="formData.isParticipate" placeholder="请选择是否参与" style="width: 100%">
                                    <el-option v-for="option in isParticipateOptions" :key="option.value"
                                        :label="option.label" :value="option.value"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>

                        <el-col :span="12" v-if="formData.isParticipate == 0">
                            <el-form-item label="不参与原因" prop="notParticipateReason">
                                <el-cascader v-model="formData.notParticipateReason"
                                    :options="notParticipateReasonOptions" placeholder="请选择不参与原因"
                                    style="width: 100%"></el-cascader>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>

            <span slot="footer" class="dialog-footer">
                <el-button @click="handleClose">关 闭</el-button>
                <el-button type="primary" @click="handleSave">保 存</el-button>
            </span>
        </el-dialog>
        <el-dialog title="选择商机" :visible.sync="dialogVisibleOpportunity" width="80%">
            <div class="search-container">
                <el-input @change="handleSearchOpportunity" v-model="opportunitySearchForm.keyword"
                    placeholder="请输入商机编号、商机名称" clearable style="width: 300px; margin-bottom: 20px;"></el-input>
            </div>
            <el-table :data="opportunityList" style="width: 100%" border v-loading="opportunityLoading"
                @selection-change="handleSelectionChange" ref="opportunityTable" row-key="id">
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column prop="opportunityCode" label="商机编号" width="180"></el-table-column>
                <el-table-column prop="opportunityName" label="商机名称" min-width="200"></el-table-column>
                <el-table-column prop="estimatedContractAmount" label="预计合同总金额（万元）"></el-table-column>
                <el-table-column prop="estimatedSignDate" label="预计签约时间" width="180">
                    <template slot-scope="scope">
                        {{ scope.row.estimatedSignDate ? new Date(scope.row.estimatedSignDate).toLocaleString() : '-' }}
                    </template>
                </el-table-column>
                <el-table-column prop="opportunityStage" label="商机阶段"></el-table-column>
                <el-table-column prop="supportUnit" label="支撑主要单位"></el-table-column>
                <el-table-column prop="supportPerson" label="支撑主要人"></el-table-column>
            </el-table>
            <!-- 分页 -->
            <div class="pagination-container" style="margin-top: 20px; text-align: right;">
                <pagination v-show="opportunityPagination.total > 0" :total="opportunityPagination.total"
                    :page.sync="opportunityPagination.pageNum" :limit.sync="opportunityPagination.pageSize"
                    @pagination="getOpportunityList" />
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisibleOpportunity = false">取消</el-button>
                <el-button type="primary" @click="handleSelectOpportunity">确定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import request from '@/utils/request'
import { getOpportunityList, updateOpportunity } from '@/api/newApi/bizoppmanage'

export default {
    props: {
        dialogVisible: {
            type: Boolean,
            default: false
        },
        formData: {
            type: Object,
            default: () => ({})
        },
        title: {
            type: String,
            default: '编辑'
        }
    },
    data() {
        return {
            selected: {},
            // 表单验证规则
            rules: {},
            // 是否参与下拉选项
            isParticipateOptions: [
                { value: 1, label: '是' },
                { value: 0, label: '否' }
            ],
            // 不参与原因级联选择器数据
            notParticipateReasonOptions: [
                {
                    value: '客户原因',
                    label: '客户原因',
                    children: [
                        { value: '意向供应商', label: '意向供应商' },
                        { value: '项目已实施补招标手续', label: '项目已实施补招标手续' },
                        { value: '单一来源不能参与', label: '单一来源不能参与' },
                        { value: '13%税率占比高', label: '13%税率占比高' },
                        { value: '应收账款风险高', label: '应收账款风险高' }
                    ]
                },
                {
                    value: '资质技术',
                    label: '资质技术',
                    children: [
                        { value: '资质不具备', label: '资质不具备' },
                        { value: '供应商不授权', label: '供应商不授权' },
                        { value: '分析招标文件扣分多', label: '分析招标文件扣分多' },
                        { value: '专业性强', label: '专业性强' },
                        { value: '面向中小', label: '面向中小' }
                    ]
                },
                {
                    value: '自身原因',
                    label: '自身原因',
                    children: [
                        { value: '未及时获取商机', label: '未及时获取商机' },
                        { value: '推进不及时客户已选择其他供应商', label: '推进不及时客户已选择其他供应商' },
                        { value: '集团不支持投标', label: '集团不支持投标' },
                        { value: '部队/黑名单', label: '部队/黑名单' }
                    ]
                }
            ],
            // 商机选择弹窗相关
            dialogVisibleOpportunity: false,
            opportunityList: [],
            opportunityLoading: false, // 表格加载状态
            opportunitySearchForm: {
                keyword: ''
            },
            opportunityPagination: {
                pageNum: 1,
                pageSize: 10,
                total: 0
            },
            selectedOpportunity: null,
            multipleSelection: []
        };
    },
    methods: {
        handleClose() {
            this.$emit('update:dialogVisible', false);
        },
        handleSearchOpportunity() {
            this.dialogVisibleOpportunity = true;
            this.getOpportunityList();
        },
        // 获取商机列表
        getOpportunityList() {
            this.opportunityLoading = true; // 开始加载
            const params = {
                pageNum: this.opportunityPagination.pageNum,
                pageSize: this.opportunityPagination.pageSize,
                keyword: this.opportunitySearchForm.keyword,
                unassociated: true
            };
            getOpportunityList(params).then(response => {
                this.opportunityList = response.rows
                this.opportunityPagination.total = response.total;
            }).catch(error => {
                console.error('获取商机列表失败:', error);
            }).finally(() => {
                this.opportunityLoading = false; // 加载结束，无论成功失败
            });
        },
        // 表格行点击事件
        handleRowClick(row) {
            console.log(row)
        },
        handleSave() {
            this.$refs.formRef.validate((valid) => {
                if (valid) {
                    if (this.formData.isParticipate === 1) {
                        this.formData.notParticipateReason = [];
                    }
                    updateOpportunity({
                        opportunityId: this.selected.id,
                        id: this.formData.fmId,
                        isParticipate: this.formData.isParticipate,
                        notParticipateReason: Array.isArray(this.formData?.notParticipateReason) ? this.formData.notParticipateReason.join(',') : ''
                    }).then(response => {
                        this.$message.success('更新成功');
                        this.$emit('update:dialogVisible', false);
                    }).catch(error => {
                        console.error('更新商机失败:', error);
                        this.$message.error('更新失败');
                    });
                } else {
                    // 验证失败，保留错误提示
                    return false;
                }
            });
        },
        // 选择商机确定
        handleSelectOpportunity() {
            if (this.multipleSelection.length > 0) {
                this.selected = this.multipleSelection[0];
                this.formData.opportunityCode = this.selected.opportunityCode;
                this.dialogVisibleOpportunity = false;
            } else {
                this.$message.warning('请选择一条商机');
            }
        },
        // 处理选择变化，限制只能选择一项
        handleSelectionChange(val) {
            if (val.length > 1) {
                this.$refs.opportunityTable.clearSelection();
                this.$refs.opportunityTable.toggleRowSelection(val.pop());
            } else {
                this.multipleSelection = val;
            }
        },
    }
}
</script>

<style scoped>
.app-container {
    padding: 0;
}

/* 详情区域整体样式优化 */
.detail-section {
    margin-bottom: 24px;
    padding: 20px;
    border: 1px solid #ebeef5;
    border-radius: 8px;
    background-color: #ffffff;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
    transition: all 0.3s ease;
}

/* 悬停效果 */
.detail-section:hover {
    box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.08);
    border-color: #dcdfe6;
}

/* 标题样式优化 */
.section-title {
    margin: 0 0 20px 0;
    padding-bottom: 8px;
    border-bottom: 2px solid #409eff;
    font-size: 16px;
    font-weight: bold;
    color: #303133;
    display: flex;
    align-items: center;
}

/* 标题前添加图标 */
.section-title::before {
    content: '';
    display: inline-block;
    width: 4px;
    height: 18px;
    background-color: #409eff;
    margin-right: 8px;
    border-radius: 2px;
}

.detail-form {
    margin: 0;
}

/* 表单行间距优化 */
.el-row {
    margin-bottom: 16px;
}

/* 表单列间距优化 */
.el-col {
    margin-bottom: 0;
}

/* 表单内容样式优化 */
.el-form-item {
    margin-bottom: 0;
}

/* 标签样式增强 */
.el-form-item__label {
    font-weight: 500;
    color: #606266;
}

/* 表单内容区域 */
.el-form-item__content {
    word-break: break-all;
    color: #303133;
    line-height: 1.5;
}

/* 商机选择弹窗样式 */
.search-container {
    margin-bottom: 20px;
}

.pagination-container {
    margin-top: 20px;
    text-align: right;
}

/* 公告正文样式优化 */
.content-box {
    max-height: 250px;
    overflow-y: auto;
    padding: 15px;
    border: 1px solid #ebeef5;
    border-radius: 6px;
    background-color: #fafafa;
    white-space: pre-wrap;
    line-height: 1.6;
    font-size: 14px;
    color: #303133;
}

/* 滚动条样式 */
.content-box::-webkit-scrollbar {
    width: 6px;
    height: 6px;
}

.content-box::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 3px;
}

.content-box::-webkit-scrollbar-thumb {
    background: #c0c4cc;
    border-radius: 3px;
}

.content-box::-webkit-scrollbar-thumb:hover {
    background: #909399;
}

/* 链接样式优化 */
.link-text {
    color: #409eff;
    text-decoration: none;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    display: inline-block;
    max-width: 100%;
    transition: all 0.3s ease;
    padding: 2px 0;
}

.link-text:hover {
    color: #66b1ff;
    text-decoration: underline;
}

/* 对话框底部按钮居中 */
.dialog-footer {
    text-align: center;
    padding-top: 20px;
}

/* 响应式设计 */
@media screen and (max-width: 768px) {
    .detail-section {
        padding: 15px;
        margin-bottom: 16px;
    }

    .section-title {
        font-size: 14px;
        margin-bottom: 15px;
    }

    .content-box {
        max-height: 200px;
        padding: 12px;
    }

    .el-form-item__label {
        font-size: 13px;
    }

    .el-form-item__content {
        font-size: 13px;
    }
}

/* 数据为空时的占位样式 */
.el-form-item__content:empty::after {
    content: '-';
    color: #c0c4cc;
}

/* 布尔值样式优化 */
.bool-value {
    display: inline-block;
    padding: 2px 8px;
    border-radius: 10px;
    font-size: 12px;
    font-weight: 500;
}

.bool-value.true {
    background-color: #f0f9eb;
    color: #67c23a;
}

.bool-value.false {
    background-color: #fef0f0;
    color: #f56c6c;
}
</style>