<template>
  <UserShell
    title="MCN机构数字资产评估申请"
    subtitle="填写以下评估信息，系统将生成专业的资产评估报告。该报告可用于银行信贷、投融资等金融服务场景。"
    :profile="profile"
    :menu-items="menuItems"
    active-key="asset"
    center-path="/user/org"
  >
    <div class="notice-box">
      <img class="notice-icon" :src="tipIcon" alt="提示" />
      <div>
        <strong>资产评估报告的价值</strong>
        <p>MCN机构的核心资产在于旗下主播的粉丝规模、内容转化率以及机构的商业化流水能力。本评估报告将从主播孵化能力、内容影响力、账号资产积累、运营数据及商业化表现五大维度进行综合评估，为银行信贷审批提供权威数据支持。</p>
      </div>
    </div>

    <div class="stepper">
      <button
        v-for="step in steps"
        :key="step.no"
        type="button"
        :class="['step-item', stepState(step.no)]"
        @click="jumpToStep(step.no)"
      >
        <span class="step-no">{{ step.no }}</span>
        <span>{{ step.label }}</span>
      </button>
    </div>

    <section class="panel">
      <template v-if="currentStep === 1">
        <div class="panel-title">一、数字资产基本信息</div>
        <div class="panel-sub">填写MCN机构的基本工商信息及资产概况</div>

        <div class="form-grid top-grid">
          <div class="field-item wide"><label>MCN机构全称 <span class="required">*</span></label><el-input v-model.trim="form.companyName" placeholder="请输入机构工商注册全称" class="control" :disabled="readonlyMode" /></div>
          <div class="field-item wide"><label>统一社会信用代码 <span class="required">*</span></label><el-input v-model.trim="form.creditCode" placeholder="18位统一社会信用代码" class="control" :disabled="readonlyMode" /></div>
          <div class="field-item wide"><label>资产类别</label><el-select v-model="form.assetType" placeholder="请选择资产类别" class="control" :disabled="readonlyMode"><el-option label="机构资产" value="机构资产" /></el-select></div>
        </div>

        <div class="sub-section">权属人股权及融资信息</div>

        <div class="form-grid">
          <div class="field-item"><label>注册资本（万元） <span class="required">*</span></label><el-input v-model.trim="form.registerCapital" placeholder="请输入注册资本" class="control" :disabled="readonlyMode" /></div>
          <div class="field-item"><label>实缴资本（万元）</label><el-input v-model.trim="form.paidCapital" placeholder="请输入实缴资本" class="control" :disabled="readonlyMode" /></div>
        </div>

        <div class="textarea-item"><label>股权结构 <span class="minor-tip">（持股比例、主要股东及实际控制人）</span></label><el-input v-model.trim="form.shareholders" type="textarea" :rows="3" resize="none" placeholder="请详细描述股权结构，例如：实际控制人张三持股60%，李四持股30%，员工持股平台持股10%" class="control textarea" :disabled="readonlyMode" /></div>
        <div class="textarea-item"><label>融资历史 <span class="minor-tip">（轮次、金额、投资方、估值）</span></label><el-input v-model.trim="form.financeHistory" type="textarea" :rows="3" resize="none" placeholder="例如：2023年A轮融资5000万元，投资方为XX资本，投后估值5亿元" class="control textarea" :disabled="readonlyMode" /></div>
        <div class="textarea-item"><label>控股子公司/关联公司 <span class="minor-tip">（与主营业务相关的关联主体）</span></label><el-input v-model.trim="form.relatedCompanies" type="textarea" :rows="3" resize="none" placeholder="列出与主播业务相关的控股子公司或关联公司" class="control textarea" :disabled="readonlyMode" /></div>

        <div class="sub-section">机构基本情况</div>

        <div class="form-grid">
          <div class="field-item"><label>成立时间 <span class="required">*</span></label><el-date-picker v-model="form.foundedAt" type="date" value-format="yyyy-MM-dd" placeholder="yyyy/mm/日" class="control" :disabled="readonlyMode" /></div>
          <div class="field-item"><label>全职员工人数 <span class="required">*</span></label><el-input v-model.trim="form.staffCount" placeholder="人" class="control" :disabled="readonlyMode" /></div>
          <div class="field-item"><label>签约主播人数 <span class="required">*</span></label><el-input v-model.trim="form.anchorCount" placeholder="人" class="control" :disabled="readonlyMode" /></div>
        </div>

        <div class="chips-block">
          <label>主营业务范围 <span class="required">*</span></label>
          <el-checkbox-group v-model="form.businessScopes" class="chips-group" :disabled="readonlyMode">
            <el-checkbox v-for="item in businessScopeOptions" :key="item" :label="item">{{ item }}</el-checkbox>
          </el-checkbox-group>
        </div>

        <div class="chips-block">
          <label>核心合作平台 <span class="required">*</span></label>
          <el-checkbox-group v-model="form.corePlatforms" class="chips-group" :disabled="readonlyMode">
            <el-checkbox v-for="item in corePlatformOptions" :key="item" :label="item">{{ item }}</el-checkbox>
          </el-checkbox-group>
        </div>

        <div class="chips-block">
          <label>经营资质</label>
          <el-checkbox-group v-model="form.certificates" class="chips-group" :disabled="readonlyMode">
            <el-checkbox v-for="item in certificateOptions" :key="item" :label="item">{{ item }}</el-checkbox>
          </el-checkbox-group>
        </div>

        <div class="form-grid bottom-grid">
          <div class="field-item wide"><label>机构办公地址 <span class="required">*</span></label><el-input v-model.trim="form.officeAddress" placeholder="省/市" class="control" :disabled="readonlyMode" /></div>
          <div class="field-item wide"><label>行业荣誉认证 <span class="minor-tip">（MCN等级、行业奖项）</span></label><el-input v-model.trim="form.honors" placeholder="如：抖音金牌MCN、快手年度影响力机构" class="control" :disabled="readonlyMode" /></div>
        </div>
      </template>

      <template v-if="currentStep === 2">
        <div class="panel-title">二、主播孵化数据情况</div>
        <div class="panel-sub">填写MCN机构旗下主播的培养与梯队建设信息</div>

        <div class="sub-section">主播签约结构</div>
        <div class="form-grid three-grid">
          <div class="field-item"><label>签约主播总数 <span class="required">*</span></label><el-input v-model.trim="form.step2.signedAnchorCount" placeholder="人" class="control" :disabled="readonlyMode" /></div>
          <div class="field-item"><label>独家签约主播 <span class="required">*</span></label><el-input v-model.trim="form.step2.exclusiveAnchorCount" placeholder="人" class="control" :disabled="readonlyMode" /></div>
          <div class="field-item contract-group">
            <label>合同类型分布</label>
            <div class="dual-inputs">
              <el-input v-model.trim="form.step2.fullTimeContractCount" placeholder="全约人" class="control" :disabled="readonlyMode" />
              <el-input v-model.trim="form.step2.businessContractCount" placeholder="商务约人" class="control" :disabled="readonlyMode" />
            </div>
          </div>
        </div>

        <div class="sub-section">主播梯队结构</div>
        <div class="form-grid three-grid">
          <div class="field-item"><label>头部主播 <span class="minor-tip">（粉丝≥500万）</span></label><el-input v-model.trim="form.step2.topAnchorCount" placeholder="人" class="control" :disabled="readonlyMode" /></div>
          <div class="field-item"><label>腰部主播 <span class="minor-tip">（100万-500万）</span></label><el-input v-model.trim="form.step2.midAnchorCount" placeholder="人" class="control" :disabled="readonlyMode" /></div>
          <div class="field-item"><label>成长型主播 <span class="minor-tip">（＜100万）</span></label><el-input v-model.trim="form.step2.growthAnchorCount" placeholder="人" class="control" :disabled="readonlyMode" /></div>
        </div>

        <div class="chips-block">
          <label>主播覆盖垂类 <span class="required">*</span> <span class="minor-tip">（列出TOP3垂类赛道）</span></label>
          <el-checkbox-group v-model="form.step2.coverCategories" class="chips-group" :disabled="readonlyMode">
            <el-checkbox v-for="item in extendedCategoryOptions" :key="item" :label="item">{{ item }}</el-checkbox>
          </el-checkbox-group>
        </div>

        <div class="sub-section">孵化投入成本</div>
        <div class="textarea-item"><label>孵化周期与过程描述</label><el-input v-model.trim="form.step2.incubationDescription" type="textarea" :rows="4" resize="none" placeholder="描述主播从签约到成熟的标准孵化流程、典型周期（月）、各阶段的投入资源（培训、流量投放、内容团队配置等）" class="control textarea" :disabled="readonlyMode" /></div>
        <div class="form-grid">
          <div class="field-item"><label>单主播平均孵化成本（万元）</label><el-input v-model.trim="form.step2.avgIncubationCost" placeholder="万元/人" class="control" :disabled="readonlyMode" /></div>
          <div class="field-item"><label>年度孵化总投入（万元）</label><el-input v-model.trim="form.step2.totalIncubationCost" placeholder="万元" class="control" :disabled="readonlyMode" /></div>
        </div>
      </template>

      <template v-if="currentStep === 3">
        <div class="panel-title">三、主播内容与影响力评估</div>
        <div class="panel-sub">填写MCN机构旗下主播的内容能力数据及资产估值信息</div>

        <div class="sub-section">主播资产综合估值</div>
        <div class="field-item estimate-row"><label>主播资产综合估值（万元） <span class="required">*</span></label><el-input v-model.trim="form.step3.assetValuation" placeholder="万元" class="control" :disabled="readonlyMode" /></div>
        <div class="textarea-item"><label>估值说明</label><el-input v-model.trim="form.step3.valuationDescription" type="textarea" :rows="3" resize="none" placeholder="基于主播粉丝规模、商业化效率、内容创作能力、平台生态适配度等多维度综合测算的估值说明" class="control textarea" :disabled="readonlyMode" /></div>

        <div class="sub-section">内容创作与粉丝质量数据</div>
        <div class="form-grid three-grid">
          <div class="field-item"><label>短视频月均更新量</label><el-input v-model.trim="form.step3.monthlyUpdateCount" placeholder="条" class="control" :disabled="readonlyMode" /></div>
          <div class="field-item"><label>短视频爆款率 <span class="minor-tip">（播放≥100万）</span></label><el-input v-model.trim="form.step3.viralRate" placeholder="%" class="control" :disabled="readonlyMode" /></div>
          <div class="field-item"><label>直播间平均停留时长（秒）</label><el-input v-model.trim="form.step3.avgStaySeconds" placeholder="秒" class="control" :disabled="readonlyMode" /></div>
          <div class="field-item"><label>粉丝互动率</label><el-input v-model.trim="form.step3.fanInteractionRate" placeholder="%" class="control" :disabled="readonlyMode" /></div>
          <div class="field-item"><label>直播间互动率</label><el-input v-model.trim="form.step3.liveInteractionRate" placeholder="%" class="control" :disabled="readonlyMode" /></div>
          <div class="field-item"><label>跨平台账号总数</label><el-input v-model.trim="form.step3.crossPlatformAccountCount" placeholder="个" class="control" :disabled="readonlyMode" /></div>
        </div>

        <div class="sub-section">合规与风控体系说明</div>
        <div class="textarea-item"><label>选品审核流程说明</label><el-input v-model.trim="form.step3.selectionProcess" type="textarea" :rows="3" resize="none" placeholder="描述机构的选品审核流程、标准及执行情况..." class="control textarea" :disabled="readonlyMode" /></div>
        <div class="textarea-item"><label>内容合规机制</label><el-input v-model.trim="form.step3.contentCompliance" type="textarea" :rows="3" resize="none" placeholder="描述内容审核机制、合规团队配置及相关制度建设情况..." class="control textarea" :disabled="readonlyMode" /></div>
      </template>

      <template v-if="currentStep === 4">
        <div class="panel-title">四、主播账号资产与权益数据</div>
        <div class="panel-sub">上传主播账号权属证明、作品著作权及商业合约等文件</div>

        <div class="sub-section">主播账号权属信息</div>
        <div class="field-item upload-top-field"><label>账号归属主体 <span class="minor-tip">（可多选）</span></label><el-select v-model="form.step4.ownershipSubjects" multiple collapse-tags placeholder="请选择" class="control upload-select" :disabled="readonlyMode"><el-option v-for="item in ownershipSubjectOptions" :key="item" :label="item" :value="item" /></el-select></div>

        <div class="upload-block"><div class="upload-title">上传授权文件 <span class="required">*</span></div><button type="button" class="upload-area" :disabled="readonlyMode" @click="triggerFile('authorizationFile')"><div class="upload-emoji folder">📁</div><div class="upload-text">点击上传或拖拽文件到此区域</div><div class="upload-sub">支持 PDF、JPG、PNG，单个文件不超过 10MB</div><div v-if="form.step4.authorizationFileName" class="upload-file-name">{{ form.step4.authorizationFileName }}</div></button><input ref="authorizationFile" type="file" class="hidden-input" accept=".pdf,.jpg,.jpeg,.png" @change="handleFileChange($event, 'authorizationFileName', 10)" /></div>
        <div class="sub-section">使用权内主播账号</div>
        <div class="upload-block"><div class="upload-title">上传授权文件 <span class="required">*</span></div><button type="button" class="upload-area" :disabled="readonlyMode" @click="triggerFile('usageFile')"><div class="upload-emoji folder">📁</div><div class="upload-text">点击上传主播账号使用权授权文件</div><div class="upload-sub">上传主播账号在授权期内的使用权证明，支持 PDF、JPG、PNG，单个文件不超过 10MB</div><div v-if="form.step4.usageFileName" class="upload-file-name">{{ form.step4.usageFileName }}</div></button><input ref="usageFile" type="file" class="hidden-input" accept=".pdf,.jpg,.jpeg,.png" @change="handleFileChange($event, 'usageFileName', 10)" /></div>
        <div class="sub-section">收益权内主播账号</div>
        <div class="upload-block"><div class="upload-title">上传授权文件 <span class="required">*</span></div><button type="button" class="upload-area" :disabled="readonlyMode" @click="triggerFile('incomeFile')"><div class="upload-emoji folder">📁</div><div class="upload-text">点击上传主播账号收益权授权文件</div><div class="upload-sub">上传主播账号在授权期内的收益权证明，支持 PDF、JPG、PNG，单个文件不超过 10MB</div><div v-if="form.step4.incomeFileName" class="upload-file-name">{{ form.step4.incomeFileName }}</div></button><input ref="incomeFile" type="file" class="hidden-input" accept=".pdf,.jpg,.jpeg,.png" @change="handleFileChange($event, 'incomeFileName', 10)" /></div>
        <div class="sub-section">作品著作权与内容资产处置权</div>
        <div class="upload-block"><div class="upload-title">上传证明文件 <span class="required">*</span></div><button type="button" class="upload-area" :disabled="readonlyMode" @click="triggerFile('copyrightFile')"><div class="upload-emoji doc">📄</div><div class="upload-text">点击上传著作权登记证书、内容版权证明等</div><div class="upload-sub">支持 PDF、JPG、PNG，单个文件不超过 10MB</div><div v-if="form.step4.copyrightFileName" class="upload-file-name">{{ form.step4.copyrightFileName }}</div></button><input ref="copyrightFile" type="file" class="hidden-input" accept=".pdf,.jpg,.jpeg,.png" @change="handleFileChange($event, 'copyrightFileName', 10)" /></div>
        <div class="sub-section">商业合约与品牌合作</div>
        <div class="upload-block"><div class="upload-title">上传证明文件 <span class="required">*</span></div><button type="button" class="upload-area" :disabled="readonlyMode" @click="triggerFile('commercialFile')"><div class="upload-emoji doc">📋</div><div class="upload-text">点击上传品牌合作协议、商业合同摘要等</div><div class="upload-sub">支持 PDF、JPG、PNG，单个文件不超过 10MB，敏感信息可脱敏处理</div><div v-if="form.step4.commercialFileName" class="upload-file-name">{{ form.step4.commercialFileName }}</div></button><input ref="commercialFile" type="file" class="hidden-input" accept=".pdf,.jpg,.jpeg,.png" @change="handleFileChange($event, 'commercialFileName', 10)" /></div>
      </template>

      <template v-if="currentStep === 5">
        <div class="panel-title">五、主播运营数据情况</div>
        <div class="panel-sub">录入旗下核心主播的运营数据，至少添加一位主播信息</div>

        <div v-for="(item, index) in form.step5.anchorMetrics" :key="item.id" class="anchor-card">
          <div class="anchor-card-head">
            <strong>主播 #{{ index + 1 }}</strong>
            <button v-if="!readonlyMode && form.step5.anchorMetrics.length > 1" type="button" class="remove-anchor-btn" @click="removeAnchorMetric(index)">×</button>
          </div>
          <div class="form-grid three-grid anchor-grid">
            <div class="field-item wide-two"><label>全网各平台ID账号</label><el-input v-model.trim="item.platformAccounts" placeholder="请填写，例：抖音：dy123454552，小红书：34455666767" class="control" :disabled="readonlyMode" /></div>
            <div class="field-item"><label>主播名称 <span class="required">*</span></label><el-select v-model="item.anchorName" placeholder="请选择主播" class="control" :disabled="readonlyMode"><el-option v-for="option in anchorNameOptions" :key="option" :label="option" :value="option" /></el-select></div>
            <div class="field-item"><label>全网粉丝总数（万）</label><el-input v-model.trim="item.totalFans" placeholder="万" class="control" :disabled="readonlyMode" /></div>
            <div class="field-item"><label>全网作品点击量（万）</label><el-input v-model.trim="item.totalViews" placeholder="万" class="control" :disabled="readonlyMode" /></div>
            <div class="field-item"><label>近一年直播场次</label><el-input v-model.trim="item.liveSessions" placeholder="场" class="control" :disabled="readonlyMode" /></div>
            <div class="field-item"><label>近一年利润（万元）</label><el-input v-model.trim="item.annualProfit" placeholder="万" class="control" :disabled="readonlyMode" /></div>
            <div class="field-item"><label>场均观看（万）</label><el-input v-model.trim="item.avgViewers" placeholder="万" class="control" :disabled="readonlyMode" /></div>
            <div class="field-item"><label>粉丝增长率（月均%）</label><el-input v-model.trim="item.fanGrowthRate" placeholder="%" class="control" :disabled="readonlyMode" /></div>
            <div class="field-item"><label>直播转化率（%）</label><el-input v-model.trim="item.conversionRate" placeholder="%" class="control" :disabled="readonlyMode" /></div>
            <div class="field-item"><label>场均GMV（万元）</label><el-input v-model.trim="item.avgGmv" placeholder="万" class="control" :disabled="readonlyMode" /></div>
            <div class="field-item"><label>客单价（元）</label><el-input v-model.trim="item.unitPrice" placeholder="元" class="control" :disabled="readonlyMode" /></div>
            <div class="field-item wide-two"><label>近12个月GMV（万元）</label><el-input v-model.trim="item.last12MonthGmv" placeholder="万" class="control" :disabled="readonlyMode" /></div>
            <div class="field-item"><label>垂类赛道</label><el-input v-model.trim="item.category" placeholder="如：美妆护肤、服饰穿搭" class="control" :disabled="readonlyMode" /></div>
          </div>
        </div>

        <button v-if="!readonlyMode" type="button" class="add-anchor-btn" @click="addAnchorMetric">+ 添加主播</button>

        <div class="sub-section">总体运营指标汇总</div>
        <div class="form-grid three-grid">
          <div class="field-item"><label>机构年度总GMV（万元） <span class="required">*</span></label><el-input v-model.trim="form.step5.summary.annualGMV" placeholder="万元" class="control" :disabled="readonlyMode" /></div>
          <div class="field-item"><label>机构年度总营收（万元） <span class="required">*</span></label><el-input v-model.trim="form.step5.summary.annualRevenue" placeholder="万元" class="control" :disabled="readonlyMode" /></div>
          <div class="field-item"><label>机构年度净利润（万元） <span class="required">*</span></label><el-input v-model.trim="form.step5.summary.annualNetProfit" placeholder="万元" class="control" :disabled="readonlyMode" /></div>
          <div class="field-item"><label>近12个月直播场次</label><el-input v-model.trim="form.step5.summary.last12MonthsSessions" placeholder="场" class="control" :disabled="readonlyMode" /></div>
          <div class="field-item"><label>场均观看人数</label><el-input v-model.trim="form.step5.summary.avgViewersCount" placeholder="万人" class="control" :disabled="readonlyMode" /></div>
          <div class="field-item"><label>总粉丝覆盖量</label><el-input v-model.trim="form.step5.summary.totalFanCoverage" placeholder="万人" class="control" :disabled="readonlyMode" /></div>
        </div>

        <div class="sub-section">收入结构与成本分析</div>
        <div class="form-grid two-grid">
          <div class="field-item"><label>佣金收入占比（%）</label><el-input v-model.trim="form.step5.incomeStructure.commissionRatio" placeholder="%" class="control" :disabled="readonlyMode" /></div>
          <div class="field-item"><label>坑位费收入占比（%）</label><el-input v-model.trim="form.step5.incomeStructure.slotFeeRatio" placeholder="%" class="control" :disabled="readonlyMode" /></div>
          <div class="field-item"><label>品牌营销收入占比（%）</label><el-input v-model.trim="form.step5.incomeStructure.brandIncomeRatio" placeholder="%" class="control" :disabled="readonlyMode" /></div>
          <div class="field-item"><label>其他收入占比（%）</label><el-input v-model.trim="form.step5.incomeStructure.otherIncomeRatio" placeholder="%" class="control" :disabled="readonlyMode" /></div>
          <div class="field-item"><label>运营成本率（%）</label><el-input v-model.trim="form.step5.incomeStructure.costRatio" placeholder="%" class="control" :disabled="readonlyMode" /></div>
          <div class="field-item"><label>净利润率（%）</label><el-input v-model.trim="form.step5.incomeStructure.netProfitRatio" placeholder="%" class="control" :disabled="readonlyMode" /></div>
        </div>

        <div class="sub-section">收入预测 <span class="minor-tip">（综合多平台数据测算）</span></div>
        <div class="form-grid two-grid">
          <div class="field-item"><label>短期收益-未来6个月（万元）</label><el-input v-model.trim="form.step5.forecast.shortTermIncome6" placeholder="万元" class="control" :disabled="readonlyMode" /></div>
          <div class="field-item"><label>全生命周期收益-3年预估（万元）</label><el-input v-model.trim="form.step5.forecast.lifecycleIncome3" placeholder="万元" class="control" :disabled="readonlyMode" /></div>
        </div>
        <div class="textarea-item"><label>收益测算依据</label><el-input v-model.trim="form.step5.forecast.forecastBasis" type="textarea" :rows="3" resize="none" placeholder="说明上述收益预测的测算方法和依据..." class="control textarea" :disabled="readonlyMode" /></div>
        <div class="textarea-item"><label>第三方支撑与生态协作 <span class="minor-tip">（如带货数据平台、第三方监测报告等）</span></label><el-input v-model.trim="form.step5.forecast.thirdPartySupport" type="textarea" :rows="3" resize="none" placeholder="列出提供数据支撑的第三方平台或机构..." class="control textarea" :disabled="readonlyMode" /></div>
      </template>

      <template v-if="currentStep === 6">
        <div class="panel-title">六、商业化情况评估</div>
        <div class="panel-sub">汇总MCN机构的商业化能力及未来收益预测</div>

        <div class="sub-section">收入预测</div>
        <div class="form-grid two-grid">
          <div class="field-item"><label>短期收益-未来12个月（万元） <span class="required">*</span></label><el-input v-model.trim="form.step6.shortTermIncome12" placeholder="万元" class="control" :disabled="readonlyMode" /></div>
          <div class="field-item"><label>全生命周期收益-5年（万元） <span class="required">*</span></label><el-input v-model.trim="form.step6.lifecycleIncome5" placeholder="万元" class="control" :disabled="readonlyMode" /></div>
        </div>

        <div class="sub-section">评估申请确认与提交</div>
        <div class="confirm-box">
          <div class="confirm-title">提交前确认</div>
          <ul>
            <li>以上所填信息真实、准确、完整，如有虚假，愿承担相应法律责任</li>
            <li>授权四川数字世界文化科技有限公司对提交数据进行核验</li>
            <li>评估报告仅供银行信贷、投融资等金融服务参考使用</li>
            <li>上传的权属文件及商业合约将严格保密，仅用于本次资产评估</li>
          </ul>
        </div>

        <el-checkbox v-model="form.step6.confirmAgreement" class="push-t-10" :disabled="readonlyMode">我已阅读并同意《资产评估服务协议》和《数据授权协议》</el-checkbox>
      </template>
    </section>

    <div v-if="!readonlyMode" class="footer-actions" :class="{ split: currentStep > 1 }">
      <button v-if="currentStep > 1" type="button" class="footer-btn back" @click="goPrev">← 上一步</button>
      <div class="right-actions">
        <button type="button" class="footer-btn ghost" @click="saveDraft">保存草稿</button>
        <button v-if="currentStep < 6" type="button" class="footer-btn primary" @click="goNext">下一步 →</button>
        <button v-else type="button" class="footer-btn submit" @click="submitApplication">提交评估申请</button>
      </div>
    </div>
  </UserShell>
</template>

<script>
import UserShell from './components/UserShell.vue';
import sidebarBg from '@/assets/img/user/背景卡图.png';
import userAvatar from '@/assets/img/user/avatar.png';
import overviewActiveIcon from '@/assets/img/user/griconxz.png';
import overviewActiveIconIn from '@/assets/img/user/gricon.png';
import talentActiveIcon from '@/assets/img/user/zbglxz.png';
import talentInactiveIcon from '@/assets/img/user/zbgl.png';
import assetActiveIcon from '@/assets/img/user/申请icon.png';
import assetInactiveIcon from '@/assets/img/user/申请未选中.png';
import tipIcon from '@/assets/img/user/提示.png';

const LIST_STORAGE_KEY = 'cog.org.assetApplications';
const DRAFT_STORAGE_KEY = 'cog.org.assetDraft';
const TALENT_STORAGE_KEY = 'cog.org.talents';
const API_ENDPOINTS = {
  saveDraft: '/api/mcn/assets/save-draft',
  stepSave: '/api/mcn/assets/step-save',
  submit: '/api/mcn/assets/submit',
  detail: '/api/mcn/assets/detail'
};

function createMenu() {
  return [
    { key: 'overview', label: '首页概览', path: '/user/org', activeIcon: overviewActiveIcon,inactiveIcon: overviewActiveIconIn},
    { key: 'talent', label: '主播管理', path: '/user/org/talents', activeIcon: talentActiveIcon, inactiveIcon: talentInactiveIcon },
    { key: 'asset', label: '资产评估申请', path: '/user/org/assets', activeIcon: assetActiveIcon, inactiveIcon: assetInactiveIcon }
  ];
}

function createAnchorMetric() {
  return {
    id: `${Date.now()}-${Math.random()}`,
    platformAccounts: '',
    anchorName: '',
    totalFans: '',
    totalViews: '',
    liveSessions: '',
    annualProfit: '',
    avgViewers: '',
    fanGrowthRate: '',
    conversionRate: '',
    avgGmv: '',
    unitPrice: '',
    last12MonthGmv: '',
    category: ''
  };
}

function createEmptyForm() {
  return {
    companyName: '星辰传媒有限公司',
    creditCode: '91110108MA01X000X',
    assetType: '机构资产',
    registerCapital: '',
    paidCapital: '',
    shareholders: '',
    financeHistory: '',
    relatedCompanies: '',
    foundedAt: '',
    staffCount: '',
    anchorCount: '',
    businessScopes: [],
    corePlatforms: [],
    certificates: [],
    officeAddress: '',
    honors: '',
    step2: {
      signedAnchorCount: '',
      exclusiveAnchorCount: '',
      fullTimeContractCount: '',
      businessContractCount: '',
      topAnchorCount: '',
      midAnchorCount: '',
      growthAnchorCount: '',
      coverCategories: [],
      incubationDescription: '',
      avgIncubationCost: '',
      totalIncubationCost: ''
    },
    step3: {
      assetValuation: '',
      valuationDescription: '',
      monthlyUpdateCount: '',
      viralRate: '',
      avgStaySeconds: '',
      fanInteractionRate: '',
      liveInteractionRate: '',
      crossPlatformAccountCount: '',
      selectionProcess: '',
      contentCompliance: ''
    },
    step4: {
      ownershipSubjects: [],
      authorizationFileName: '',
      usageFileName: '',
      incomeFileName: '',
      copyrightFileName: '',
      commercialFileName: ''
    },
    step5: {
      anchorMetrics: [createAnchorMetric()],
      summary: {
        annualGMV: '',
        annualRevenue: '',
        annualNetProfit: '',
        last12MonthsSessions: '',
        avgViewersCount: '',
        totalFanCoverage: ''
      },
      incomeStructure: {
        commissionRatio: '',
        slotFeeRatio: '',
        brandIncomeRatio: '',
        otherIncomeRatio: '',
        costRatio: '',
        netProfitRatio: ''
      },
      forecast: {
        shortTermIncome6: '',
        lifecycleIncome3: '',
        forecastBasis: '',
        thirdPartySupport: ''
      }
    },
    step6: {
      shortTermIncome12: '',
      lifecycleIncome5: '',
      confirmAgreement: false
    }
  };
}

function readJson(key, fallback) {
  try {
    const raw = window.localStorage.getItem(key);
    return raw ? JSON.parse(raw) : fallback;
  } catch (error) {
    return fallback;
  }
}

function writeJson(key, value) {
  window.localStorage.setItem(key, JSON.stringify(value));
}

function cloneDeep(value) {
  return JSON.parse(JSON.stringify(value));
}

export default {
  name: 'OrganizationAssetApplicationCreate',
  components: { UserShell },
  data() {
    return {
      apiEndpoints: API_ENDPOINTS,
      tipIcon,
      profile: {
        name: '星辰传媒有限公司',
        role: 'MCN机构',
        avatar: userAvatar,
        background: sidebarBg
      },
      menuItems: createMenu(),
      readonlyMode: false,
      currentId: '',
      currentStep: 1,
      form: createEmptyForm(),
      steps: [
        { no: 1, label: '基本信息' },
        { no: 2, label: '孵化数据' },
        { no: 3, label: '内容影响力' },
        { no: 4, label: '账号资产' },
        { no: 5, label: '运营数据' },
        { no: 6, label: '商业化评估' }
      ],
      businessScopeOptions: ['直播带货', '内容创作', '艺人经纪', '品牌代运营', '知识付费', 'IP授权'],
      corePlatformOptions: ['抖音', '快手', '视频号', '小红书', '淘宝直播', 'B站', 'YouTube', 'TikTok'],
      certificateOptions: ['营业性演出许可证', '网络文化经营许可证', 'ICP许可证', '广播电视节目制作'],
      extendedCategoryOptions: ['美妆护肤', '服饰穿搭', '食品饮料', '3C数码', '家居生活', '母婴育儿', '教育知识', '运动户外', '游戏电竞', '汽车房产', '珠宝文玩', '本地生活'],
      ownershipSubjectOptions: ['机构主体', '主播个人', '联合持有']
    };
  },
  computed: {
    anchorNameOptions() {
      const talents = readJson(TALENT_STORAGE_KEY, []);
      return talents.map(item => item.name).filter(Boolean);
    }
  },
  created() {
    this.initPage();
  },
  methods: {
    initPage() {
      const { mode, id, step } = this.$route.query;
      this.readonlyMode = mode === 'view';
      this.currentId = id || '';
      this.currentStep = Number(step || 1);
      if (this.currentId) {
        const list = readJson(LIST_STORAGE_KEY, []);
        const target = list.find(item => String(item.id) === String(this.currentId));
        if (target && (target.formData || target.formStep1)) {
          this.form = this.hydrateForm(target.formData || target.formStep1);
          return;
        }
      }
      this.form = this.hydrateForm(readJson(DRAFT_STORAGE_KEY, createEmptyForm()));
    },
    hydrateForm(source) {
      const base = createEmptyForm();
      const form = source || base;
      return {
        ...base,
        ...form,
        businessScopes: Array.isArray(form.businessScopes) ? form.businessScopes : [],
        corePlatforms: Array.isArray(form.corePlatforms) ? form.corePlatforms : [],
        certificates: Array.isArray(form.certificates) ? form.certificates : [],
        step2: {
          ...base.step2,
          ...(form.step2 || {}),
          coverCategories: Array.isArray(form.step2 && form.step2.coverCategories) ? form.step2.coverCategories : []
        },
        step3: {
          ...base.step3,
          ...(form.step3 || {})
        },
        step4: {
          ...base.step4,
          ...(form.step4 || {}),
          ownershipSubjects: Array.isArray(form.step4 && form.step4.ownershipSubjects) ? form.step4.ownershipSubjects : []
        },
        step5: {
          ...base.step5,
          ...(form.step5 || {}),
          anchorMetrics: Array.isArray(form.step5 && form.step5.anchorMetrics) && form.step5.anchorMetrics.length
            ? form.step5.anchorMetrics.map(item => ({ ...createAnchorMetric(), ...item }))
            : [createAnchorMetric()],
          summary: {
            ...base.step5.summary,
            ...((form.step5 && form.step5.summary) || {})
          },
          incomeStructure: {
            ...base.step5.incomeStructure,
            ...((form.step5 && form.step5.incomeStructure) || {})
          },
          forecast: {
            ...base.step5.forecast,
            ...((form.step5 && form.step5.forecast) || {})
          }
        },
        step6: {
          ...base.step6,
          ...(form.step6 || {})
        }
      };
    },
    stepState(no) {
      if (no < this.currentStep) {
        return 'done';
      }
      if (no === this.currentStep) {
        return 'active';
      }
      return 'pending';
    },
    jumpToStep(no) {
      this.currentStep = no;
      this.syncStepQuery();
    },
    syncStepQuery() {
      this.$router.replace({ query: { ...this.$route.query, step: String(this.currentStep) } });
    },
    triggerFile(refName) {
      if (this.readonlyMode) {
        return;
      }
      const ref = this.$refs[refName];
      const target = Array.isArray(ref) ? ref[0] : ref;
      if (target) {
        target.click();
      }
    },
    handleFileChange(event, field, maxSizeMb) {
      const file = event.target.files && event.target.files[0];
      if (!file) {
        return;
      }
      if (file.size > maxSizeMb * 1024 * 1024) {
        this.$message.warning(`文件大小不能超过${maxSizeMb}M`);
        event.target.value = '';
        return;
      }
      this.form.step4[field] = file.name;
      event.target.value = '';
    },
    addAnchorMetric() {
      this.form.step5.anchorMetrics.push(createAnchorMetric());
    },
    removeAnchorMetric(index) {
      this.form.step5.anchorMetrics.splice(index, 1);
    },
    validateCurrentStep() {
      if (this.currentStep === 1) {
        const checks = [
          ['companyName', '请输入MCN机构全称'],
          ['creditCode', '请输入统一社会信用代码'],
          ['registerCapital', '请输入注册资本'],
          ['foundedAt', '请选择成立时间'],
          ['staffCount', '请输入全职员工人数'],
          ['anchorCount', '请输入签约主播人数'],
          ['officeAddress', '请输入机构办公地址']
        ];
        for (let index = 0; index < checks.length; index += 1) {
          const [field, message] = checks[index];
          if (!this.form[field]) {
            this.$message.warning(message);
            return false;
          }
        }
        if (!this.form.businessScopes.length) {
          this.$message.warning('请选择主营业务范围');
          return false;
        }
        if (!this.form.corePlatforms.length) {
          this.$message.warning('请选择核心合作平台');
          return false;
        }
      }
      if (this.currentStep === 2) {
        if (!this.form.step2.signedAnchorCount || !this.form.step2.exclusiveAnchorCount) {
          this.$message.warning('请完整填写主播签约结构');
          return false;
        }
        if (!this.form.step2.coverCategories.length) {
          this.$message.warning('请选择主播覆盖垂类');
          return false;
        }
      }
      if (this.currentStep === 3) {
        if (!this.form.step3.assetValuation) {
          this.$message.warning('请输入主播资产综合估值');
          return false;
        }
      }
      if (this.currentStep === 4) {
        const requiredFiles = ['authorizationFileName', 'usageFileName', 'incomeFileName', 'copyrightFileName', 'commercialFileName'];
        const missing = requiredFiles.some(field => !this.form.step4[field]);
        if (missing) {
          this.$message.warning('请完整上传账号资产相关证明文件');
          return false;
        }
      }
      if (this.currentStep === 5) {
        if (!this.form.step5.anchorMetrics.length) {
          this.$message.warning('请至少添加一位主播');
          return false;
        }
        const invalidAnchor = this.form.step5.anchorMetrics.some(item => !item.anchorName);
        if (invalidAnchor) {
          this.$message.warning('请至少为每位主播选择主播名称');
          return false;
        }
        if (!this.form.step5.summary.annualGMV || !this.form.step5.summary.annualRevenue || !this.form.step5.summary.annualNetProfit) {
          this.$message.warning('请填写总体运营指标汇总');
          return false;
        }
      }
      if (this.currentStep === 6) {
        if (!this.form.step6.shortTermIncome12 || !this.form.step6.lifecycleIncome5) {
          this.$message.warning('请填写收入预测');
          return false;
        }
        if (!this.form.step6.confirmAgreement) {
          this.$message.warning('请先勾选协议确认');
          return false;
        }
      }
      return true;
    },
    buildRecord(status) {
      return {
        id: this.currentId ? Number(this.currentId) : Date.now(),
        applyNo: this.currentId ? `EV-${this.currentId}` : `EV-${Date.now().toString().slice(-9)}`,
        assetName: this.form.companyName,
        assetType: this.form.assetType || '机构资产',
        submitTime: new Date().toISOString().slice(0, 16).replace('T', ' '),
        status,
        formData: cloneDeep(this.form),
        formStep1: cloneDeep(this.form)
      };
    },
    upsertListRecord(status) {
      const list = readJson(LIST_STORAGE_KEY, []);
      const payload = this.buildRecord(status);
      const index = list.findIndex(item => String(item.id) === String(payload.id));
      if (index === -1) {
        list.unshift(payload);
      } else {
        list.splice(index, 1, payload);
      }
      writeJson(LIST_STORAGE_KEY, list);
      this.currentId = payload.id;
    },
    saveDraft() {
      writeJson(DRAFT_STORAGE_KEY, this.form);
      this.upsertListRecord('草稿');
      this.$message.success(`草稿已保存，接口待接入：${this.apiEndpoints.saveDraft}`);
    },
    goPrev() {
      if (this.currentStep > 1) {
        this.currentStep -= 1;
        this.syncStepQuery();
      }
    },
    goNext() {
      if (!this.validateCurrentStep()) {
        return;
      }
      writeJson(DRAFT_STORAGE_KEY, this.form);
      this.upsertListRecord('草稿');
      if (this.currentStep < 6) {
        this.currentStep += 1;
        this.syncStepQuery();
        this.$message.success(`当前步骤已保存，接口待接入：${this.apiEndpoints.stepSave}`);
      }
    },
    submitApplication() {
      if (!this.validateCurrentStep()) {
        return;
      }
      this.upsertListRecord('审核中');
      writeJson(DRAFT_STORAGE_KEY, this.form);
      this.$message.success(`评估申请已提交，接口待接入：${this.apiEndpoints.submit}`);
      this.$router.push('/user/org/assets');
    }
  },
  watch: {
    '$route.fullPath'() {
      this.initPage();
    }
  }
};
</script>

<style lang="scss" scoped>
.notice-box {
  display: flex;
  gap: 12px;
  padding: 16px 18px;
  border: 1px solid #a89eff;
  border-radius: 12px;
  background: rgba(111, 104, 243, 0.04);
  margin-top: 34px;
  color: #6f68f3;
  font-size: 15px;
}

.notice-icon {
  width: 20px;
  height: 20px;
  margin-top: 2px;
}

.notice-box strong {
  display: block;
  color: #6f68f3;
  font-size: 15px;
}

.notice-box p {
  margin-top: 8px;
  color: #7b87a4;
  font-size: 14px;
  line-height: 1.8;
}

.stepper {
  display: flex;
  justify-content: center;
  gap: 18px;
  margin-top: 28px;
  flex-wrap: wrap;
}

.step-item {
  border: 0;
  background: transparent;
  display: inline-flex;
  align-items: center;
  gap: 10px;
  color: #c1c7d7;
  font-size: 14px;
  cursor: pointer;
}

.step-no {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  border: 1px solid #dde3ef;
  line-height: 32px;
  text-align: center;
}

.step-item.done {
  color: #18b79b;
}

.step-item.done .step-no {
  border: 0;
  background: #18b79b;
  color: #fff;
}

.step-item.active {
  color: #3a425a;
  font-weight: 600;
}

.step-item.active .step-no {
  border: 0;
  background: #6f68f3;
  color: #fff;
}

.panel {
  margin-top: 34px;
  padding: 24px 24px 18px;
  border-radius: 14px;
  background: #fff;
  box-shadow: inset 0 0 0 1px #eef1f7;
}

.panel-title {
  color: #3D3D3D;
  font-size: 20px;
  font-weight: 700;
}

.panel-sub {
  margin-top: 8px;
  color: #98a2b3;
  font-size: 14px;
}

.sub-section {
  margin-top: 24px;
  padding-left: 10px;
  border-left: 2px solid #4F46E5;
  color: #4F46E5;
  font-size: 18px;
  font-weight: 600;
}

.form-grid {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 20px;
  margin-top: 18px;
}

.three-grid {
  grid-template-columns: repeat(3, minmax(0, 1fr));
}

.two-grid {
  grid-template-columns: repeat(2, minmax(0, 1fr));
}

.top-grid .wide {
  grid-column: span 2;
}

.anchor-grid .wide-two {
  grid-column: span 2;
}

.field-item label,
.textarea-item label,
.chips-block label,
.upload-title {
  display: block;
  margin-bottom: 10px;
  color: #3D3D3D;
  font-size: 16px;
  font-weight: 600;
}

.minor-tip {
  color: #98a2b3;
  font-size: 12px;
  font-weight: 400;
}

.required {
  color: #ff6a6a;
}

.control {
  width: 100%;
}

.control ::v-deep .el-input__inner,
.control ::v-deep .el-textarea__inner,
.control ::v-deep .el-select .el-input__inner {
  border-radius: 8px;
  border: 1px solid #e2e8f0;
  background: #f8fafc;
}

.control ::v-deep .el-input__inner {
  height: 42px;
}

.textarea-item {
  margin-top: 18px;
}

.textarea ::v-deep .el-textarea__inner {
  min-height: 72px !important;
}

.chips-block {
  margin-top: 22px;
}

.chips-group {
  display: flex;
  flex-wrap: wrap;
  gap: 12px 10px;
}

.chips-group ::v-deep .el-checkbox {
  margin-right: 0;
}

.chips-group ::v-deep .el-checkbox__label {
  padding: 0 14px;
  height: 32px;
  border: 1px solid #dce2ef;
  border-radius: 999px;
  line-height: 32px;
  color: #667085;
}

.chips-group ::v-deep .el-checkbox__input {
  display: none;
}

.chips-group ::v-deep .el-checkbox__input.is-checked + .el-checkbox__label {
  border-color: #6f68f3;
  background: #f0edff;
  color: #5f66ec;
}
.push-t-10{
	margin-top: 10px;
}
.dual-inputs {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
}

.estimate-row {
  margin-top: 18px;
  max-width: 50%;
}

.upload-top-field {
  margin-top: 18px;
  max-width: 520px;
}

.upload-select {
  max-width: 420px;
}

.upload-block {
  margin-top: 20px;
}

.upload-area {
  width: 100%;
  min-height: 144px;
  border: 1px dashed #d9dfeb;
  border-radius: 10px;
  background: #fff;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 8px;
  cursor: pointer;
}

.upload-area:disabled {
  cursor: default;
}

.upload-emoji {
  font-size: 34px;
  line-height: 1;
}

.upload-text {
  color: #68758e;
  font-size: 16px;
}

.upload-sub,
.upload-file-name {
  color: #a1a9c0;
  font-size: 13px;
}

.upload-file-name {
  color: #5f66ec;
}

.hidden-input {
  display: none;
}

.anchor-card {
  margin-top: 18px;
  padding: 16px 16px 18px;
  border: 1px solid #dfe4f0;
  border-radius: 12px;
  background: #fff;
}

.anchor-card-head {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 14px;
}

.anchor-card-head strong {
  color: #1e293b;
  font-size: 18px;
}

.remove-anchor-btn {
  border: 0;
  background: transparent;
  color: #f26666;
  font-size: 28px;
  line-height: 1;
  cursor: pointer;
}

.add-anchor-btn {
  margin-top: 16px;
  min-width: 110px;
  height: 38px;
  border: 1px dashed #9b8bff;
  border-radius: 8px;
  background: #fff;
  color: #6f68f3;
  cursor: pointer;
}

.confirm-box {
  margin-top: 18px;
  padding: 18px;
  border: 1px solid #efe6ff;
  border-radius: 12px;
  background: rgba(255, 166, 166, 0.04);
}

.confirm-title {
  color: #5f66ec;
  font-size: 18px;
  font-weight: 600;
}

.confirm-box ul {
  margin: 14px 0 0 18px;
  padding: 0;
  color: #6d758c;
  font-size: 14px;
  line-height: 2;
}

.footer-actions {
  display: flex;
  justify-content: flex-end;
  gap: 14px;
  margin-top: 30px;
}

.footer-actions.split {
  justify-content: space-between;
}

.right-actions {
  display: flex;
  gap: 14px;
}

.footer-btn {
  min-width: 110px;
  height: 40px;
  border-radius: 8px;
  cursor: pointer;
}

.footer-btn.back {
  border: 1px solid #d9dfeb;
  background: #fff;
  color: #6b7280;
}

.footer-btn.ghost {
  border: 1px solid #eac47f;
  background: #fffdf7;
  color: #d4982b;
}

.footer-btn.primary {
  border: 0;
  background: #6f68f3;
  color: #fff;
}

.footer-btn.submit {
  border: 0;
	color: #fff;
	width: 114px;
	height: 40px;
	background: #6F68F3;
	border-radius: 8px 8px 8px 8px;
  color: #fff;
}

@media (max-width: 960px) {
  .form-grid,
  .three-grid,
  .two-grid,
  .dual-inputs {
    grid-template-columns: 1fr;
  }

  .top-grid .wide,
  .anchor-grid .wide-two,
  .estimate-row {
    grid-column: auto;
    max-width: 100%;
  }

  .footer-actions,
  .footer-actions.split,
  .right-actions {
    flex-direction: column;
    align-items: flex-start;
  }
}
</style>
